1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #include "nsRangeFrame.h"
7 
8 #include "mozilla/EventStates.h"
9 #include "mozilla/TouchEvents.h"
10 
11 #include "nsContentCreatorFunctions.h"
12 #include "nsContentList.h"
13 #include "nsContentUtils.h"
14 #include "nsCSSPseudoElements.h"
15 #include "nsCSSRendering.h"
16 #include "nsFormControlFrame.h"
17 #include "nsIContent.h"
18 #include "nsIDocument.h"
19 #include "nsNameSpaceManager.h"
20 #include "nsIPresShell.h"
21 #include "nsGkAtoms.h"
22 #include "mozilla/dom/HTMLInputElement.h"
23 #include "nsPresContext.h"
24 #include "nsNodeInfoManager.h"
25 #include "nsRenderingContext.h"
26 #include "mozilla/dom/Element.h"
27 #include "mozilla/StyleSetHandle.h"
28 #include "mozilla/StyleSetHandleInlines.h"
29 #include "nsThemeConstants.h"
30 
31 #ifdef ACCESSIBILITY
32 #include "nsAccessibilityService.h"
33 #endif
34 
35 #define LONG_SIDE_TO_SHORT_SIDE_RATIO 10
36 
37 using namespace mozilla;
38 using namespace mozilla::dom;
39 using namespace mozilla::image;
40 
NS_IMPL_ISUPPORTS(nsRangeFrame::DummyTouchListener,nsIDOMEventListener)41 NS_IMPL_ISUPPORTS(nsRangeFrame::DummyTouchListener, nsIDOMEventListener)
42 
43 nsIFrame*
44 NS_NewRangeFrame(nsIPresShell* aPresShell, nsStyleContext* aContext)
45 {
46   return new (aPresShell) nsRangeFrame(aContext);
47 }
48 
nsRangeFrame(nsStyleContext * aContext)49 nsRangeFrame::nsRangeFrame(nsStyleContext* aContext)
50   : nsContainerFrame(aContext)
51 {
52 }
53 
~nsRangeFrame()54 nsRangeFrame::~nsRangeFrame()
55 {
56 #ifdef DEBUG
57   if (mOuterFocusStyle) {
58     mOuterFocusStyle->FrameRelease();
59   }
60 #endif
61 }
62 
63 NS_IMPL_FRAMEARENA_HELPERS(nsRangeFrame)
64 
NS_QUERYFRAME_HEAD(nsRangeFrame)65 NS_QUERYFRAME_HEAD(nsRangeFrame)
66   NS_QUERYFRAME_ENTRY(nsRangeFrame)
67   NS_QUERYFRAME_ENTRY(nsIAnonymousContentCreator)
68 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
69 
70 void
71 nsRangeFrame::Init(nsIContent*       aContent,
72                    nsContainerFrame* aParent,
73                    nsIFrame*         aPrevInFlow)
74 {
75   // With APZ enabled, touch events may be handled directly by the APZC code
76   // if the APZ knows that there is no content interested in the touch event.
77   // The range input element *is* interested in touch events, but doesn't use
78   // the usual mechanism (i.e. registering an event listener) to handle touch
79   // input. Instead, we do it here so that the APZ finds out about it, and
80   // makes sure to wait for content to run handlers before handling the touch
81   // input itself.
82   if (!mDummyTouchListener) {
83     mDummyTouchListener = new DummyTouchListener();
84   }
85   aContent->AddEventListener(NS_LITERAL_STRING("touchstart"), mDummyTouchListener, false);
86 
87   StyleSetHandle styleSet = PresContext()->StyleSet();
88 
89   mOuterFocusStyle =
90     styleSet->ProbePseudoElementStyle(aContent->AsElement(),
91                                       CSSPseudoElementType::mozFocusOuter,
92                                       StyleContext());
93 
94   return nsContainerFrame::Init(aContent, aParent, aPrevInFlow);
95 }
96 
97 void
DestroyFrom(nsIFrame * aDestructRoot)98 nsRangeFrame::DestroyFrom(nsIFrame* aDestructRoot)
99 {
100   NS_ASSERTION(!GetPrevContinuation() && !GetNextContinuation(),
101                "nsRangeFrame should not have continuations; if it does we "
102                "need to call RegUnregAccessKey only for the first.");
103 
104   mContent->RemoveEventListener(NS_LITERAL_STRING("touchstart"), mDummyTouchListener, false);
105 
106   nsFormControlFrame::RegUnRegAccessKey(static_cast<nsIFrame*>(this), false);
107   nsContentUtils::DestroyAnonymousContent(&mTrackDiv);
108   nsContentUtils::DestroyAnonymousContent(&mProgressDiv);
109   nsContentUtils::DestroyAnonymousContent(&mThumbDiv);
110   nsContainerFrame::DestroyFrom(aDestructRoot);
111 }
112 
113 nsresult
MakeAnonymousDiv(Element ** aResult,CSSPseudoElementType aPseudoType,nsTArray<ContentInfo> & aElements)114 nsRangeFrame::MakeAnonymousDiv(Element** aResult,
115                                CSSPseudoElementType aPseudoType,
116                                nsTArray<ContentInfo>& aElements)
117 {
118   nsCOMPtr<nsIDocument> doc = mContent->GetComposedDoc();
119   RefPtr<Element> resultElement = doc->CreateHTMLElement(nsGkAtoms::div);
120 
121   // Associate the pseudo-element with the anonymous child.
122   RefPtr<nsStyleContext> newStyleContext =
123     PresContext()->StyleSet()->ResolvePseudoElementStyle(mContent->AsElement(),
124                                                          aPseudoType,
125                                                          StyleContext(),
126                                                          resultElement);
127 
128   if (!aElements.AppendElement(ContentInfo(resultElement, newStyleContext))) {
129     return NS_ERROR_OUT_OF_MEMORY;
130   }
131 
132   resultElement.forget(aResult);
133   return NS_OK;
134 }
135 
136 nsresult
CreateAnonymousContent(nsTArray<ContentInfo> & aElements)137 nsRangeFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
138 {
139   nsresult rv;
140 
141   // Create the ::-moz-range-track pseuto-element (a div):
142   rv = MakeAnonymousDiv(getter_AddRefs(mTrackDiv),
143                         CSSPseudoElementType::mozRangeTrack,
144                         aElements);
145   NS_ENSURE_SUCCESS(rv, rv);
146 
147   // Create the ::-moz-range-progress pseudo-element (a div):
148   rv = MakeAnonymousDiv(getter_AddRefs(mProgressDiv),
149                         CSSPseudoElementType::mozRangeProgress,
150                         aElements);
151   NS_ENSURE_SUCCESS(rv, rv);
152 
153   // Create the ::-moz-range-thumb pseudo-element (a div):
154   rv = MakeAnonymousDiv(getter_AddRefs(mThumbDiv),
155                         CSSPseudoElementType::mozRangeThumb,
156                         aElements);
157   return rv;
158 }
159 
160 void
AppendAnonymousContentTo(nsTArray<nsIContent * > & aElements,uint32_t aFilter)161 nsRangeFrame::AppendAnonymousContentTo(nsTArray<nsIContent*>& aElements,
162                                        uint32_t aFilter)
163 {
164   if (mTrackDiv) {
165     aElements.AppendElement(mTrackDiv);
166   }
167 
168   if (mProgressDiv) {
169     aElements.AppendElement(mProgressDiv);
170   }
171 
172   if (mThumbDiv) {
173     aElements.AppendElement(mThumbDiv);
174   }
175 }
176 
177 class nsDisplayRangeFocusRing : public nsDisplayItem
178 {
179 public:
nsDisplayRangeFocusRing(nsDisplayListBuilder * aBuilder,nsIFrame * aFrame)180   nsDisplayRangeFocusRing(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
181     : nsDisplayItem(aBuilder, aFrame) {
182     MOZ_COUNT_CTOR(nsDisplayRangeFocusRing);
183   }
184 #ifdef NS_BUILD_REFCNT_LOGGING
~nsDisplayRangeFocusRing()185   virtual ~nsDisplayRangeFocusRing() {
186     MOZ_COUNT_DTOR(nsDisplayRangeFocusRing);
187   }
188 #endif
189 
190   nsDisplayItemGeometry* AllocateGeometry(nsDisplayListBuilder* aBuilder) override;
191   void ComputeInvalidationRegion(nsDisplayListBuilder* aBuilder,
192                                  const nsDisplayItemGeometry* aGeometry,
193                                  nsRegion *aInvalidRegion) override;
194   virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) override;
195   virtual void Paint(nsDisplayListBuilder* aBuilder, nsRenderingContext* aCtx) override;
196   NS_DISPLAY_DECL_NAME("RangeFocusRing", TYPE_RANGE_FOCUS_RING)
197 };
198 
199 nsDisplayItemGeometry*
AllocateGeometry(nsDisplayListBuilder * aBuilder)200 nsDisplayRangeFocusRing::AllocateGeometry(nsDisplayListBuilder* aBuilder)
201 {
202   return new nsDisplayItemGenericImageGeometry(this, aBuilder);
203 }
204 
205 void
ComputeInvalidationRegion(nsDisplayListBuilder * aBuilder,const nsDisplayItemGeometry * aGeometry,nsRegion * aInvalidRegion)206 nsDisplayRangeFocusRing::ComputeInvalidationRegion(
207   nsDisplayListBuilder* aBuilder,
208   const nsDisplayItemGeometry* aGeometry,
209   nsRegion* aInvalidRegion)
210 {
211   auto geometry =
212     static_cast<const nsDisplayItemGenericImageGeometry*>(aGeometry);
213 
214   if (aBuilder->ShouldSyncDecodeImages() &&
215       geometry->ShouldInvalidateToSyncDecodeImages()) {
216     bool snap;
217     aInvalidRegion->Or(*aInvalidRegion, GetBounds(aBuilder, &snap));
218   }
219 
220   nsDisplayItem::ComputeInvalidationRegion(aBuilder, aGeometry, aInvalidRegion);
221 }
222 
223 nsRect
GetBounds(nsDisplayListBuilder * aBuilder,bool * aSnap)224 nsDisplayRangeFocusRing::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap)
225 {
226   *aSnap = false;
227   nsRect rect(ToReferenceFrame(), Frame()->GetSize());
228 
229   // We want to paint as if specifying a border for ::-moz-focus-outer
230   // specifies an outline for our frame, so inflate by the border widths:
231   nsStyleContext* styleContext =
232     static_cast<nsRangeFrame*>(mFrame)->mOuterFocusStyle;
233   MOZ_ASSERT(styleContext, "We only exist if mOuterFocusStyle is non-null");
234   rect.Inflate(styleContext->StyleBorder()->GetComputedBorder());
235 
236   return rect;
237 }
238 
239 void
Paint(nsDisplayListBuilder * aBuilder,nsRenderingContext * aCtx)240 nsDisplayRangeFocusRing::Paint(nsDisplayListBuilder* aBuilder,
241                                nsRenderingContext* aCtx)
242 {
243   bool unused;
244   nsStyleContext* styleContext =
245     static_cast<nsRangeFrame*>(mFrame)->mOuterFocusStyle;
246   MOZ_ASSERT(styleContext, "We only exist if mOuterFocusStyle is non-null");
247 
248   PaintBorderFlags flags = aBuilder->ShouldSyncDecodeImages()
249                          ? PaintBorderFlags::SYNC_DECODE_IMAGES
250                          : PaintBorderFlags();
251 
252   DrawResult result =
253     nsCSSRendering::PaintBorder(mFrame->PresContext(), *aCtx, mFrame,
254                                 mVisibleRect, GetBounds(aBuilder, &unused),
255                                 styleContext, flags);
256 
257   nsDisplayItemGenericImageGeometry::UpdateDrawResult(this, result);
258 }
259 
260 void
BuildDisplayList(nsDisplayListBuilder * aBuilder,const nsRect & aDirtyRect,const nsDisplayListSet & aLists)261 nsRangeFrame::BuildDisplayList(nsDisplayListBuilder*   aBuilder,
262                                const nsRect&           aDirtyRect,
263                                const nsDisplayListSet& aLists)
264 {
265   if (IsThemed()) {
266     DisplayBorderBackgroundOutline(aBuilder, aLists);
267     // Only create items for the thumb. Specifically, we do not want
268     // the track to paint, since *our* background is used to paint
269     // the track, and we don't want the unthemed track painting over
270     // the top of the themed track.
271     // This logic is copied from
272     // nsContainerFrame::BuildDisplayListForNonBlockChildren as
273     // called by BuildDisplayListForInline.
274     nsIFrame* thumb = mThumbDiv->GetPrimaryFrame();
275     if (thumb) {
276       nsDisplayListSet set(aLists, aLists.Content());
277       BuildDisplayListForChild(aBuilder, thumb, aDirtyRect, set, DISPLAY_CHILD_INLINE);
278     }
279   } else {
280     BuildDisplayListForInline(aBuilder, aDirtyRect, aLists);
281   }
282 
283   // Draw a focus outline if appropriate:
284 
285   if (!aBuilder->IsForPainting() ||
286       !IsVisibleForPainting(aBuilder)) {
287     // we don't want the focus ring item for hit-testing or if the item isn't
288     // in the area being [re]painted
289     return;
290   }
291 
292   EventStates eventStates = mContent->AsElement()->State();
293   if (eventStates.HasState(NS_EVENT_STATE_DISABLED) ||
294       !eventStates.HasState(NS_EVENT_STATE_FOCUSRING)) {
295     return; // can't have focus or doesn't match :-moz-focusring
296   }
297 
298   if (!mOuterFocusStyle ||
299       !mOuterFocusStyle->StyleBorder()->HasBorder()) {
300     // no ::-moz-focus-outer specified border (how style specifies a focus ring
301     // for range)
302     return;
303   }
304 
305   const nsStyleDisplay *disp = StyleDisplay();
306   if (IsThemed(disp) &&
307       PresContext()->GetTheme()->ThemeDrawsFocusForWidget(disp->mAppearance)) {
308     return; // the native theme displays its own visual indication of focus
309   }
310 
311   aLists.Content()->AppendNewToTop(
312     new (aBuilder) nsDisplayRangeFocusRing(aBuilder, this));
313 }
314 
315 void
Reflow(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput,nsReflowStatus & aStatus)316 nsRangeFrame::Reflow(nsPresContext*           aPresContext,
317                      ReflowOutput&     aDesiredSize,
318                      const ReflowInput& aReflowInput,
319                      nsReflowStatus&          aStatus)
320 {
321   MarkInReflow();
322   DO_GLOBAL_REFLOW_COUNT("nsRangeFrame");
323   DISPLAY_REFLOW(aPresContext, this, aReflowInput, aDesiredSize, aStatus);
324 
325   NS_ASSERTION(mTrackDiv, "::-moz-range-track div must exist!");
326   NS_ASSERTION(mProgressDiv, "::-moz-range-progress div must exist!");
327   NS_ASSERTION(mThumbDiv, "::-moz-range-thumb div must exist!");
328   NS_ASSERTION(!GetPrevContinuation() && !GetNextContinuation(),
329                "nsRangeFrame should not have continuations; if it does we "
330                "need to call RegUnregAccessKey only for the first.");
331 
332   if (mState & NS_FRAME_FIRST_REFLOW) {
333     nsFormControlFrame::RegUnRegAccessKey(this, true);
334   }
335 
336   WritingMode wm = aReflowInput.GetWritingMode();
337   nscoord computedBSize = aReflowInput.ComputedBSize();
338   if (computedBSize == NS_AUTOHEIGHT) {
339     computedBSize = 0;
340   }
341   LogicalSize
342     finalSize(wm,
343               aReflowInput.ComputedISize() +
344               aReflowInput.ComputedLogicalBorderPadding().IStartEnd(wm),
345               computedBSize +
346               aReflowInput.ComputedLogicalBorderPadding().BStartEnd(wm));
347   aDesiredSize.SetSize(wm, finalSize);
348 
349   ReflowAnonymousContent(aPresContext, aDesiredSize, aReflowInput);
350 
351   aDesiredSize.SetOverflowAreasToDesiredBounds();
352 
353   nsIFrame* trackFrame = mTrackDiv->GetPrimaryFrame();
354   if (trackFrame) {
355     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, trackFrame);
356   }
357 
358   nsIFrame* rangeProgressFrame = mProgressDiv->GetPrimaryFrame();
359   if (rangeProgressFrame) {
360     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, rangeProgressFrame);
361   }
362 
363   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
364   if (thumbFrame) {
365     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, thumbFrame);
366   }
367 
368   FinishAndStoreOverflow(&aDesiredSize);
369 
370   aStatus = NS_FRAME_COMPLETE;
371 
372   NS_FRAME_SET_TRUNCATION(aStatus, aReflowInput, aDesiredSize);
373 }
374 
375 void
ReflowAnonymousContent(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput)376 nsRangeFrame::ReflowAnonymousContent(nsPresContext*           aPresContext,
377                                      ReflowOutput&     aDesiredSize,
378                                      const ReflowInput& aReflowInput)
379 {
380   // The width/height of our content box, which is the available width/height
381   // for our anonymous content:
382   nscoord rangeFrameContentBoxWidth = aReflowInput.ComputedWidth();
383   nscoord rangeFrameContentBoxHeight = aReflowInput.ComputedHeight();
384   if (rangeFrameContentBoxHeight == NS_AUTOHEIGHT) {
385     rangeFrameContentBoxHeight = 0;
386   }
387 
388   nsIFrame* trackFrame = mTrackDiv->GetPrimaryFrame();
389 
390   if (trackFrame) { // display:none?
391 
392     // Position the track:
393     // The idea here is that we allow content authors to style the width,
394     // height, border and padding of the track, but we ignore margin and
395     // positioning properties and do the positioning ourself to keep the center
396     // of the track's border box on the center of the nsRangeFrame's content
397     // box.
398 
399     WritingMode wm = trackFrame->GetWritingMode();
400     LogicalSize availSize = aReflowInput.ComputedSize(wm);
401     availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
402     ReflowInput trackReflowInput(aPresContext, aReflowInput,
403                                        trackFrame, availSize);
404 
405     // Find the x/y position of the track frame such that it will be positioned
406     // as described above. These coordinates are with respect to the
407     // nsRangeFrame's border-box.
408     nscoord trackX = rangeFrameContentBoxWidth / 2;
409     nscoord trackY = rangeFrameContentBoxHeight / 2;
410 
411     // Account for the track's border and padding (we ignore its margin):
412     trackX -= trackReflowInput.ComputedPhysicalBorderPadding().left +
413                 trackReflowInput.ComputedWidth() / 2;
414     trackY -= trackReflowInput.ComputedPhysicalBorderPadding().top +
415                 trackReflowInput.ComputedHeight() / 2;
416 
417     // Make relative to our border box instead of our content box:
418     trackX += aReflowInput.ComputedPhysicalBorderPadding().left;
419     trackY += aReflowInput.ComputedPhysicalBorderPadding().top;
420 
421     nsReflowStatus frameStatus;
422     ReflowOutput trackDesiredSize(aReflowInput);
423     ReflowChild(trackFrame, aPresContext, trackDesiredSize,
424                 trackReflowInput, trackX, trackY, 0, frameStatus);
425     MOZ_ASSERT(NS_FRAME_IS_FULLY_COMPLETE(frameStatus),
426                "We gave our child unconstrained height, so it should be complete");
427     FinishReflowChild(trackFrame, aPresContext, trackDesiredSize,
428                       &trackReflowInput, trackX, trackY, 0);
429   }
430 
431   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
432 
433   if (thumbFrame) { // display:none?
434     WritingMode wm = thumbFrame->GetWritingMode();
435     LogicalSize availSize = aReflowInput.ComputedSize(wm);
436     availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
437     ReflowInput thumbReflowInput(aPresContext, aReflowInput,
438                                        thumbFrame, availSize);
439 
440     // Where we position the thumb depends on its size, so we first reflow
441     // the thumb at {0,0} to obtain its size, then position it afterwards.
442 
443     nsReflowStatus frameStatus;
444     ReflowOutput thumbDesiredSize(aReflowInput);
445     ReflowChild(thumbFrame, aPresContext, thumbDesiredSize,
446                 thumbReflowInput, 0, 0, 0, frameStatus);
447     MOZ_ASSERT(NS_FRAME_IS_FULLY_COMPLETE(frameStatus),
448                "We gave our child unconstrained height, so it should be complete");
449     FinishReflowChild(thumbFrame, aPresContext, thumbDesiredSize,
450                       &thumbReflowInput, 0, 0, 0);
451     DoUpdateThumbPosition(thumbFrame, nsSize(aDesiredSize.Width(),
452                                              aDesiredSize.Height()));
453   }
454 
455   nsIFrame* rangeProgressFrame = mProgressDiv->GetPrimaryFrame();
456 
457   if (rangeProgressFrame) { // display:none?
458     WritingMode wm = rangeProgressFrame->GetWritingMode();
459     LogicalSize availSize = aReflowInput.ComputedSize(wm);
460     availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
461     ReflowInput progressReflowInput(aPresContext, aReflowInput,
462                                           rangeProgressFrame, availSize);
463 
464     // We first reflow the range-progress frame at {0,0} to obtain its
465     // unadjusted dimensions, then we adjust it to so that the appropriate edge
466     // ends at the thumb.
467 
468     nsReflowStatus frameStatus;
469     ReflowOutput progressDesiredSize(aReflowInput);
470     ReflowChild(rangeProgressFrame, aPresContext,
471                 progressDesiredSize, progressReflowInput, 0, 0,
472                 0, frameStatus);
473     MOZ_ASSERT(NS_FRAME_IS_FULLY_COMPLETE(frameStatus),
474                "We gave our child unconstrained height, so it should be complete");
475     FinishReflowChild(rangeProgressFrame, aPresContext,
476                       progressDesiredSize, &progressReflowInput, 0, 0, 0);
477     DoUpdateRangeProgressFrame(rangeProgressFrame, nsSize(aDesiredSize.Width(),
478                                                           aDesiredSize.Height()));
479   }
480 }
481 
482 #ifdef ACCESSIBILITY
483 a11y::AccType
AccessibleType()484 nsRangeFrame::AccessibleType()
485 {
486   return a11y::eHTMLRangeType;
487 }
488 #endif
489 
490 double
GetValueAsFractionOfRange()491 nsRangeFrame::GetValueAsFractionOfRange()
492 {
493   MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::input), "bad cast");
494   dom::HTMLInputElement* input = static_cast<dom::HTMLInputElement*>(mContent);
495 
496   MOZ_ASSERT(input->GetType() == NS_FORM_INPUT_RANGE);
497 
498   Decimal value = input->GetValueAsDecimal();
499   Decimal minimum = input->GetMinimum();
500   Decimal maximum = input->GetMaximum();
501 
502   MOZ_ASSERT(value.isFinite() && minimum.isFinite() && maximum.isFinite(),
503              "type=range should have a default maximum/minimum");
504 
505   if (maximum <= minimum) {
506     MOZ_ASSERT(value == minimum, "Unsanitized value");
507     return 0.0;
508   }
509 
510   MOZ_ASSERT(value >= minimum && value <= maximum, "Unsanitized value");
511 
512   return ((value - minimum) / (maximum - minimum)).toDouble();
513 }
514 
515 Decimal
GetValueAtEventPoint(WidgetGUIEvent * aEvent)516 nsRangeFrame::GetValueAtEventPoint(WidgetGUIEvent* aEvent)
517 {
518   MOZ_ASSERT(aEvent->mClass == eMouseEventClass ||
519              aEvent->mClass == eTouchEventClass,
520              "Unexpected event type - aEvent->mRefPoint may be meaningless");
521 
522   MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::input), "bad cast");
523   dom::HTMLInputElement* input = static_cast<dom::HTMLInputElement*>(mContent);
524 
525   MOZ_ASSERT(input->GetType() == NS_FORM_INPUT_RANGE);
526 
527   Decimal minimum = input->GetMinimum();
528   Decimal maximum = input->GetMaximum();
529   MOZ_ASSERT(minimum.isFinite() && maximum.isFinite(),
530              "type=range should have a default maximum/minimum");
531   if (maximum <= minimum) {
532     return minimum;
533   }
534   Decimal range = maximum - minimum;
535 
536   LayoutDeviceIntPoint absPoint;
537   if (aEvent->mClass == eTouchEventClass) {
538     MOZ_ASSERT(aEvent->AsTouchEvent()->mTouches.Length() == 1,
539                "Unexpected number of mTouches");
540     absPoint = aEvent->AsTouchEvent()->mTouches[0]->mRefPoint;
541   } else {
542     absPoint = aEvent->mRefPoint;
543   }
544   nsPoint point =
545     nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, absPoint, this);
546 
547   if (point == nsPoint(NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE)) {
548     // We don't want to change the current value for this error state.
549     return static_cast<dom::HTMLInputElement*>(mContent)->GetValueAsDecimal();
550   }
551 
552   nsRect rangeContentRect = GetContentRectRelativeToSelf();
553   nsSize thumbSize;
554 
555   if (IsThemed()) {
556     // We need to get the size of the thumb from the theme.
557     nsPresContext *presContext = PresContext();
558     bool notUsedCanOverride;
559     LayoutDeviceIntSize size;
560     presContext->GetTheme()->
561       GetMinimumWidgetSize(presContext, this, NS_THEME_RANGE_THUMB, &size,
562                            &notUsedCanOverride);
563     thumbSize.width = presContext->DevPixelsToAppUnits(size.width);
564     thumbSize.height = presContext->DevPixelsToAppUnits(size.height);
565     MOZ_ASSERT(thumbSize.width > 0 && thumbSize.height > 0);
566   } else {
567     nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
568     if (thumbFrame) { // diplay:none?
569       thumbSize = thumbFrame->GetSize();
570     }
571   }
572 
573   Decimal fraction;
574   if (IsHorizontal()) {
575     nscoord traversableDistance = rangeContentRect.width - thumbSize.width;
576     if (traversableDistance <= 0) {
577       return minimum;
578     }
579     nscoord posAtStart = rangeContentRect.x + thumbSize.width/2;
580     nscoord posAtEnd = posAtStart + traversableDistance;
581     nscoord posOfPoint = mozilla::clamped(point.x, posAtStart, posAtEnd);
582     fraction = Decimal(posOfPoint - posAtStart) / Decimal(traversableDistance);
583     if (IsRightToLeft()) {
584       fraction = Decimal(1) - fraction;
585     }
586   } else {
587     nscoord traversableDistance = rangeContentRect.height - thumbSize.height;
588     if (traversableDistance <= 0) {
589       return minimum;
590     }
591     nscoord posAtStart = rangeContentRect.y + thumbSize.height/2;
592     nscoord posAtEnd = posAtStart + traversableDistance;
593     nscoord posOfPoint = mozilla::clamped(point.y, posAtStart, posAtEnd);
594     // For a vertical range, the top (posAtStart) is the highest value, so we
595     // subtract the fraction from 1.0 to get that polarity correct.
596     fraction = Decimal(1) - Decimal(posOfPoint - posAtStart) / Decimal(traversableDistance);
597   }
598 
599   MOZ_ASSERT(fraction >= Decimal(0) && fraction <= Decimal(1));
600   return minimum + fraction * range;
601 }
602 
603 void
UpdateForValueChange()604 nsRangeFrame::UpdateForValueChange()
605 {
606   if (NS_SUBTREE_DIRTY(this)) {
607     return; // we're going to be updated when we reflow
608   }
609   nsIFrame* rangeProgressFrame = mProgressDiv->GetPrimaryFrame();
610   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
611   if (!rangeProgressFrame && !thumbFrame) {
612     return; // diplay:none?
613   }
614   if (rangeProgressFrame) {
615     DoUpdateRangeProgressFrame(rangeProgressFrame, GetSize());
616   }
617   if (thumbFrame) {
618     DoUpdateThumbPosition(thumbFrame, GetSize());
619   }
620   if (IsThemed()) {
621     // We don't know the exact dimensions or location of the thumb when native
622     // theming is applied, so we just repaint the entire range.
623     InvalidateFrame();
624   }
625 
626 #ifdef ACCESSIBILITY
627   nsAccessibilityService* accService = nsIPresShell::AccService();
628   if (accService) {
629     accService->RangeValueChanged(PresContext()->PresShell(), mContent);
630   }
631 #endif
632 
633   SchedulePaint();
634 }
635 
636 void
DoUpdateThumbPosition(nsIFrame * aThumbFrame,const nsSize & aRangeSize)637 nsRangeFrame::DoUpdateThumbPosition(nsIFrame* aThumbFrame,
638                                     const nsSize& aRangeSize)
639 {
640   MOZ_ASSERT(aThumbFrame);
641 
642   // The idea here is that we want to position the thumb so that the center
643   // of the thumb is on an imaginary line drawn from the middle of one edge
644   // of the range frame's content box to the middle of the opposite edge of
645   // its content box (the opposite edges being the left/right edge if the
646   // range is horizontal, or else the top/bottom edges if the range is
647   // vertical). How far along this line the center of the thumb is placed
648   // depends on the value of the range.
649 
650   nsMargin borderAndPadding = GetUsedBorderAndPadding();
651   nsPoint newPosition(borderAndPadding.left, borderAndPadding.top);
652 
653   nsSize rangeContentBoxSize(aRangeSize);
654   rangeContentBoxSize.width -= borderAndPadding.LeftRight();
655   rangeContentBoxSize.height -= borderAndPadding.TopBottom();
656 
657   nsSize thumbSize = aThumbFrame->GetSize();
658   double fraction = GetValueAsFractionOfRange();
659   MOZ_ASSERT(fraction >= 0.0 && fraction <= 1.0);
660 
661   if (IsHorizontal()) {
662     if (thumbSize.width < rangeContentBoxSize.width) {
663       nscoord traversableDistance =
664         rangeContentBoxSize.width - thumbSize.width;
665       if (IsRightToLeft()) {
666         newPosition.x += NSToCoordRound((1.0 - fraction) * traversableDistance);
667       } else {
668         newPosition.x += NSToCoordRound(fraction * traversableDistance);
669       }
670       newPosition.y += (rangeContentBoxSize.height - thumbSize.height)/2;
671     }
672   } else {
673     if (thumbSize.height < rangeContentBoxSize.height) {
674       nscoord traversableDistance =
675         rangeContentBoxSize.height - thumbSize.height;
676       newPosition.x += (rangeContentBoxSize.width - thumbSize.width)/2;
677       newPosition.y += NSToCoordRound((1.0 - fraction) * traversableDistance);
678     }
679   }
680   aThumbFrame->SetPosition(newPosition);
681 }
682 
683 void
DoUpdateRangeProgressFrame(nsIFrame * aRangeProgressFrame,const nsSize & aRangeSize)684 nsRangeFrame::DoUpdateRangeProgressFrame(nsIFrame* aRangeProgressFrame,
685                                          const nsSize& aRangeSize)
686 {
687   MOZ_ASSERT(aRangeProgressFrame);
688 
689   // The idea here is that we want to position the ::-moz-range-progress
690   // pseudo-element so that the center line running along its length is on the
691   // corresponding center line of the nsRangeFrame's content box. In the other
692   // dimension, we align the "start" edge of the ::-moz-range-progress
693   // pseudo-element's border-box with the corresponding edge of the
694   // nsRangeFrame's content box, and we size the progress element's border-box
695   // to have a length of GetValueAsFractionOfRange() times the nsRangeFrame's
696   // content-box size.
697 
698   nsMargin borderAndPadding = GetUsedBorderAndPadding();
699   nsSize progSize = aRangeProgressFrame->GetSize();
700   nsRect progRect(borderAndPadding.left, borderAndPadding.top,
701                   progSize.width, progSize.height);
702 
703   nsSize rangeContentBoxSize(aRangeSize);
704   rangeContentBoxSize.width -= borderAndPadding.LeftRight();
705   rangeContentBoxSize.height -= borderAndPadding.TopBottom();
706 
707   double fraction = GetValueAsFractionOfRange();
708   MOZ_ASSERT(fraction >= 0.0 && fraction <= 1.0);
709 
710   if (IsHorizontal()) {
711     nscoord progLength = NSToCoordRound(fraction * rangeContentBoxSize.width);
712     if (IsRightToLeft()) {
713       progRect.x += rangeContentBoxSize.width - progLength;
714     }
715     progRect.y += (rangeContentBoxSize.height - progSize.height)/2;
716     progRect.width = progLength;
717   } else {
718     nscoord progLength = NSToCoordRound(fraction * rangeContentBoxSize.height);
719     progRect.x += (rangeContentBoxSize.width - progSize.width)/2;
720     progRect.y += rangeContentBoxSize.height - progLength;
721     progRect.height = progLength;
722   }
723   aRangeProgressFrame->SetRect(progRect);
724 }
725 
726 nsresult
AttributeChanged(int32_t aNameSpaceID,nsIAtom * aAttribute,int32_t aModType)727 nsRangeFrame::AttributeChanged(int32_t  aNameSpaceID,
728                                nsIAtom* aAttribute,
729                                int32_t  aModType)
730 {
731   NS_ASSERTION(mTrackDiv, "The track div must exist!");
732   NS_ASSERTION(mThumbDiv, "The thumb div must exist!");
733 
734   if (aNameSpaceID == kNameSpaceID_None) {
735     if (aAttribute == nsGkAtoms::value ||
736         aAttribute == nsGkAtoms::min ||
737         aAttribute == nsGkAtoms::max ||
738         aAttribute == nsGkAtoms::step) {
739       // We want to update the position of the thumb, except in one special
740       // case: If the value attribute is being set, it is possible that we are
741       // in the middle of a type change away from type=range, under the
742       // SetAttr(..., nsGkAtoms::value, ...) call in HTMLInputElement::
743       // HandleTypeChange. In that case the HTMLInputElement's type will
744       // already have changed, and if we call UpdateForValueChange()
745       // we'll fail the asserts under that call that check the type of our
746       // HTMLInputElement. Given that we're changing away from being a range
747       // and this frame will shortly be destroyed, there's no point in calling
748       // UpdateForValueChange() anyway.
749       MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::input), "bad cast");
750       bool typeIsRange = static_cast<dom::HTMLInputElement*>(mContent)->GetType() ==
751                            NS_FORM_INPUT_RANGE;
752       // If script changed the <input>'s type before setting these attributes
753       // then we don't need to do anything since we are going to be reframed.
754       if (typeIsRange) {
755         UpdateForValueChange();
756       }
757     } else if (aAttribute == nsGkAtoms::orient) {
758       PresContext()->PresShell()->FrameNeedsReflow(this, nsIPresShell::eResize,
759                                                    NS_FRAME_IS_DIRTY);
760     }
761   }
762 
763   return nsContainerFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
764 }
765 
766 LogicalSize
ComputeAutoSize(nsRenderingContext * aRenderingContext,WritingMode aWM,const LogicalSize & aCBSize,nscoord aAvailableISize,const LogicalSize & aMargin,const LogicalSize & aBorder,const LogicalSize & aPadding,ComputeSizeFlags aFlags)767 nsRangeFrame::ComputeAutoSize(nsRenderingContext* aRenderingContext,
768                               WritingMode         aWM,
769                               const LogicalSize&  aCBSize,
770                               nscoord             aAvailableISize,
771                               const LogicalSize&  aMargin,
772                               const LogicalSize&  aBorder,
773                               const LogicalSize&  aPadding,
774                               ComputeSizeFlags    aFlags)
775 {
776   nscoord oneEm = NSToCoordRound(StyleFont()->mFont.size *
777                                  nsLayoutUtils::FontSizeInflationFor(this)); // 1em
778 
779   bool isInlineOriented = IsInlineOriented();
780 
781   const WritingMode wm = GetWritingMode();
782   LogicalSize autoSize(wm);
783 
784   // nsFrame::ComputeSize calls GetMinimumWidgetSize to prevent us from being
785   // given too small a size when we're natively themed. If we're themed, we set
786   // our "thickness" dimension to zero below and rely on that
787   // GetMinimumWidgetSize check to correct that dimension to the natural
788   // thickness of a slider in the current theme.
789 
790   if (isInlineOriented) {
791     autoSize.ISize(wm) = LONG_SIDE_TO_SHORT_SIDE_RATIO * oneEm;
792     autoSize.BSize(wm) = IsThemed() ? 0 : oneEm;
793   } else {
794     autoSize.ISize(wm) = IsThemed() ? 0 : oneEm;
795     autoSize.BSize(wm) = LONG_SIDE_TO_SHORT_SIDE_RATIO * oneEm;
796   }
797 
798   return autoSize.ConvertTo(aWM, wm);
799 }
800 
801 nscoord
GetMinISize(nsRenderingContext * aRenderingContext)802 nsRangeFrame::GetMinISize(nsRenderingContext *aRenderingContext)
803 {
804   // nsFrame::ComputeSize calls GetMinimumWidgetSize to prevent us from being
805   // given too small a size when we're natively themed. If we aren't native
806   // themed, we don't mind how small we're sized.
807   return nscoord(0);
808 }
809 
810 nscoord
GetPrefISize(nsRenderingContext * aRenderingContext)811 nsRangeFrame::GetPrefISize(nsRenderingContext *aRenderingContext)
812 {
813   bool isInline = IsInlineOriented();
814 
815   if (!isInline && IsThemed()) {
816     // nsFrame::ComputeSize calls GetMinimumWidgetSize to prevent us from being
817     // given too small a size when we're natively themed. We return zero and
818     // depend on that correction to get our "natural" width when we're a
819     // vertical slider.
820     return 0;
821   }
822 
823   nscoord prefISize = NSToCoordRound(StyleFont()->mFont.size *
824                                      nsLayoutUtils::FontSizeInflationFor(this)); // 1em
825 
826   if (isInline) {
827     prefISize *= LONG_SIDE_TO_SHORT_SIDE_RATIO;
828   }
829 
830   return prefISize;
831 }
832 
833 bool
IsHorizontal() const834 nsRangeFrame::IsHorizontal() const
835 {
836   dom::HTMLInputElement* element =
837     static_cast<dom::HTMLInputElement*>(mContent);
838   return element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::orient,
839                               nsGkAtoms::horizontal, eCaseMatters) ||
840          (!element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::orient,
841                                nsGkAtoms::vertical, eCaseMatters) &&
842           GetWritingMode().IsVertical() ==
843             element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::orient,
844                                  nsGkAtoms::block, eCaseMatters));
845 }
846 
847 double
GetMin() const848 nsRangeFrame::GetMin() const
849 {
850   return static_cast<dom::HTMLInputElement*>(mContent)->GetMinimum().toDouble();
851 }
852 
853 double
GetMax() const854 nsRangeFrame::GetMax() const
855 {
856   return static_cast<dom::HTMLInputElement*>(mContent)->GetMaximum().toDouble();
857 }
858 
859 double
GetValue() const860 nsRangeFrame::GetValue() const
861 {
862   return static_cast<dom::HTMLInputElement*>(mContent)->GetValueAsDecimal().toDouble();
863 }
864 
865 nsIAtom*
GetType() const866 nsRangeFrame::GetType() const
867 {
868   return nsGkAtoms::rangeFrame;
869 }
870 
871 #define STYLES_DISABLING_NATIVE_THEMING \
872   NS_AUTHOR_SPECIFIED_BACKGROUND | \
873   NS_AUTHOR_SPECIFIED_PADDING | \
874   NS_AUTHOR_SPECIFIED_BORDER
875 
876 bool
ShouldUseNativeStyle() const877 nsRangeFrame::ShouldUseNativeStyle() const
878 {
879   nsIFrame* trackFrame = mTrackDiv->GetPrimaryFrame();
880   nsIFrame* progressFrame = mProgressDiv->GetPrimaryFrame();
881   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
882 
883   return (StyleDisplay()->mAppearance == NS_THEME_RANGE) &&
884          !PresContext()->HasAuthorSpecifiedRules(this,
885                                                  (NS_AUTHOR_SPECIFIED_BORDER |
886                                                   NS_AUTHOR_SPECIFIED_BACKGROUND)) &&
887          trackFrame &&
888          !PresContext()->HasAuthorSpecifiedRules(trackFrame,
889                                                  STYLES_DISABLING_NATIVE_THEMING) &&
890          progressFrame &&
891          !PresContext()->HasAuthorSpecifiedRules(progressFrame,
892                                                  STYLES_DISABLING_NATIVE_THEMING) &&
893          thumbFrame &&
894          !PresContext()->HasAuthorSpecifiedRules(thumbFrame,
895                                                  STYLES_DISABLING_NATIVE_THEMING);
896 }
897 
898 Element*
GetPseudoElement(CSSPseudoElementType aType)899 nsRangeFrame::GetPseudoElement(CSSPseudoElementType aType)
900 {
901   if (aType == CSSPseudoElementType::mozRangeTrack) {
902     return mTrackDiv;
903   }
904 
905   if (aType == CSSPseudoElementType::mozRangeThumb) {
906     return mThumbDiv;
907   }
908 
909   if (aType == CSSPseudoElementType::mozRangeProgress) {
910     return mProgressDiv;
911   }
912 
913   return nsContainerFrame::GetPseudoElement(aType);
914 }
915 
916 nsStyleContext*
GetAdditionalStyleContext(int32_t aIndex) const917 nsRangeFrame::GetAdditionalStyleContext(int32_t aIndex) const
918 {
919   // We only implement this so that SetAdditionalStyleContext will be
920   // called if style changes that would change the -moz-focus-outer
921   // pseudo-element have occurred.
922   if (aIndex != 0) {
923     return nullptr;
924   }
925   return mOuterFocusStyle;
926 }
927 
928 void
SetAdditionalStyleContext(int32_t aIndex,nsStyleContext * aStyleContext)929 nsRangeFrame::SetAdditionalStyleContext(int32_t aIndex,
930                                         nsStyleContext* aStyleContext)
931 {
932   MOZ_ASSERT(aIndex == 0,
933              "GetAdditionalStyleContext is handling other indexes?");
934 
935 #ifdef DEBUG
936   if (mOuterFocusStyle) {
937     mOuterFocusStyle->FrameRelease();
938   }
939 #endif
940 
941   // The -moz-focus-outer pseudo-element's style has changed.
942   mOuterFocusStyle = aStyleContext;
943 
944 #ifdef DEBUG
945   if (mOuterFocusStyle) {
946     mOuterFocusStyle->FrameAddRef();
947   }
948 #endif
949 }
950