1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "nsRangeFrame.h"
8 
9 #include "mozilla/EventStates.h"
10 #include "mozilla/PresShell.h"
11 #include "mozilla/TouchEvents.h"
12 
13 #include "gfxContext.h"
14 #include "nsContentCreatorFunctions.h"
15 #include "nsCSSPseudoElements.h"
16 #include "nsCSSRendering.h"
17 #include "nsIContent.h"
18 #include "mozilla/dom/Document.h"
19 #include "nsNameSpaceManager.h"
20 #include "nsGkAtoms.h"
21 #include "mozilla/dom/HTMLInputElement.h"
22 #include "nsPresContext.h"
23 #include "nsPresContextInlines.h"
24 #include "nsNodeInfoManager.h"
25 #include "mozilla/dom/Element.h"
26 #include "mozilla/ServoStyleSet.h"
27 #include "nsStyleConsts.h"
28 
29 #ifdef ACCESSIBILITY
30 #  include "nsAccessibilityService.h"
31 #endif
32 
33 // Our intrinsic size is 12em in the main-axis and 1.3em in the cross-axis.
34 #define MAIN_AXIS_EM_SIZE 12
35 #define CROSS_AXIS_EM_SIZE 1.3f
36 
37 using namespace mozilla;
38 using namespace mozilla::dom;
39 using namespace mozilla::image;
40 
NS_NewRangeFrame(PresShell * aPresShell,ComputedStyle * aStyle)41 nsIFrame* NS_NewRangeFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
42   return new (aPresShell) nsRangeFrame(aStyle, aPresShell->GetPresContext());
43 }
44 
nsRangeFrame(ComputedStyle * aStyle,nsPresContext * aPresContext)45 nsRangeFrame::nsRangeFrame(ComputedStyle* aStyle, nsPresContext* aPresContext)
46     : nsContainerFrame(aStyle, aPresContext, kClassID) {}
47 
48 nsRangeFrame::~nsRangeFrame() = default;
49 
50 NS_IMPL_FRAMEARENA_HELPERS(nsRangeFrame)
51 
NS_QUERYFRAME_HEAD(nsRangeFrame)52 NS_QUERYFRAME_HEAD(nsRangeFrame)
53   NS_QUERYFRAME_ENTRY(nsRangeFrame)
54   NS_QUERYFRAME_ENTRY(nsIAnonymousContentCreator)
55 NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)
56 
57 void nsRangeFrame::DestroyFrom(nsIFrame* aDestructRoot,
58                                PostDestroyData& aPostDestroyData) {
59   NS_ASSERTION(!GetPrevContinuation() && !GetNextContinuation(),
60                "nsRangeFrame should not have continuations; if it does we "
61                "need to call RegUnregAccessKey only for the first.");
62 
63   aPostDestroyData.AddAnonymousContent(mTrackDiv.forget());
64   aPostDestroyData.AddAnonymousContent(mProgressDiv.forget());
65   aPostDestroyData.AddAnonymousContent(mThumbDiv.forget());
66   nsContainerFrame::DestroyFrom(aDestructRoot, aPostDestroyData);
67 }
68 
MakeAnonymousDiv(Element ** aResult,PseudoStyleType aPseudoType,nsTArray<ContentInfo> & aElements)69 nsresult nsRangeFrame::MakeAnonymousDiv(Element** aResult,
70                                         PseudoStyleType aPseudoType,
71                                         nsTArray<ContentInfo>& aElements) {
72   nsCOMPtr<Document> doc = mContent->GetComposedDoc();
73   RefPtr<Element> resultElement = doc->CreateHTMLElement(nsGkAtoms::div);
74 
75   // Associate the pseudo-element with the anonymous child.
76   resultElement->SetPseudoElementType(aPseudoType);
77 
78   // XXX(Bug 1631371) Check if this should use a fallible operation as it
79   // pretended earlier, or change the return type to void.
80   aElements.AppendElement(resultElement);
81 
82   resultElement.forget(aResult);
83   return NS_OK;
84 }
85 
CreateAnonymousContent(nsTArray<ContentInfo> & aElements)86 nsresult nsRangeFrame::CreateAnonymousContent(
87     nsTArray<ContentInfo>& aElements) {
88   nsresult rv;
89 
90   // Create the ::-moz-range-track pseudo-element (a div):
91   rv = MakeAnonymousDiv(getter_AddRefs(mTrackDiv),
92                         PseudoStyleType::mozRangeTrack, aElements);
93   NS_ENSURE_SUCCESS(rv, rv);
94 
95   // Create the ::-moz-range-progress pseudo-element (a div):
96   rv = MakeAnonymousDiv(getter_AddRefs(mProgressDiv),
97                         PseudoStyleType::mozRangeProgress, aElements);
98   NS_ENSURE_SUCCESS(rv, rv);
99 
100   // Create the ::-moz-range-thumb pseudo-element (a div):
101   rv = MakeAnonymousDiv(getter_AddRefs(mThumbDiv),
102                         PseudoStyleType::mozRangeThumb, aElements);
103   return rv;
104 }
105 
AppendAnonymousContentTo(nsTArray<nsIContent * > & aElements,uint32_t aFilter)106 void nsRangeFrame::AppendAnonymousContentTo(nsTArray<nsIContent*>& aElements,
107                                             uint32_t aFilter) {
108   if (mTrackDiv) {
109     aElements.AppendElement(mTrackDiv);
110   }
111 
112   if (mProgressDiv) {
113     aElements.AppendElement(mProgressDiv);
114   }
115 
116   if (mThumbDiv) {
117     aElements.AppendElement(mThumbDiv);
118   }
119 }
120 
BuildDisplayList(nsDisplayListBuilder * aBuilder,const nsDisplayListSet & aLists)121 void nsRangeFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
122                                     const nsDisplayListSet& aLists) {
123   const nsStyleDisplay* disp = StyleDisplay();
124   if (IsThemed(disp)) {
125     DisplayBorderBackgroundOutline(aBuilder, aLists);
126     // Only create items for the thumb. Specifically, we do not want
127     // the track to paint, since *our* background is used to paint
128     // the track, and we don't want the unthemed track painting over
129     // the top of the themed track.
130     // This logic is copied from
131     // nsContainerFrame::BuildDisplayListForNonBlockChildren as
132     // called by BuildDisplayListForInline.
133     nsIFrame* thumb = mThumbDiv->GetPrimaryFrame();
134     if (thumb) {
135       nsDisplayListSet set(aLists, aLists.Content());
136       BuildDisplayListForChild(aBuilder, thumb, set, DisplayChildFlag::Inline);
137     }
138   } else {
139     BuildDisplayListForInline(aBuilder, aLists);
140   }
141 }
142 
Reflow(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput,nsReflowStatus & aStatus)143 void nsRangeFrame::Reflow(nsPresContext* aPresContext,
144                           ReflowOutput& aDesiredSize,
145                           const ReflowInput& aReflowInput,
146                           nsReflowStatus& aStatus) {
147   MarkInReflow();
148   DO_GLOBAL_REFLOW_COUNT("nsRangeFrame");
149   DISPLAY_REFLOW(aPresContext, this, aReflowInput, aDesiredSize, aStatus);
150   MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
151 
152   NS_ASSERTION(mTrackDiv, "::-moz-range-track div must exist!");
153   NS_ASSERTION(mProgressDiv, "::-moz-range-progress div must exist!");
154   NS_ASSERTION(mThumbDiv, "::-moz-range-thumb div must exist!");
155   NS_ASSERTION(!GetPrevContinuation() && !GetNextContinuation(),
156                "nsRangeFrame should not have continuations; if it does we "
157                "need to call RegUnregAccessKey only for the first.");
158 
159   WritingMode wm = aReflowInput.GetWritingMode();
160   nscoord computedBSize = aReflowInput.ComputedBSize();
161   if (computedBSize == NS_UNCONSTRAINEDSIZE) {
162     computedBSize = 0;
163   }
164   const auto borderPadding = aReflowInput.ComputedLogicalBorderPadding(wm);
165   LogicalSize finalSize(
166       wm, aReflowInput.ComputedISize() + borderPadding.IStartEnd(wm),
167       computedBSize + borderPadding.BStartEnd(wm));
168   aDesiredSize.SetSize(wm, finalSize);
169 
170   ReflowAnonymousContent(aPresContext, aDesiredSize, aReflowInput);
171 
172   aDesiredSize.SetOverflowAreasToDesiredBounds();
173 
174   nsIFrame* trackFrame = mTrackDiv->GetPrimaryFrame();
175   if (trackFrame) {
176     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, trackFrame);
177   }
178 
179   nsIFrame* rangeProgressFrame = mProgressDiv->GetPrimaryFrame();
180   if (rangeProgressFrame) {
181     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, rangeProgressFrame);
182   }
183 
184   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
185   if (thumbFrame) {
186     ConsiderChildOverflow(aDesiredSize.mOverflowAreas, thumbFrame);
187   }
188 
189   FinishAndStoreOverflow(&aDesiredSize);
190 
191   MOZ_ASSERT(aStatus.IsEmpty(), "This type of frame can't be split.");
192 
193   NS_FRAME_SET_TRUNCATION(aStatus, aReflowInput, aDesiredSize);
194 }
195 
ReflowAnonymousContent(nsPresContext * aPresContext,ReflowOutput & aDesiredSize,const ReflowInput & aReflowInput)196 void nsRangeFrame::ReflowAnonymousContent(nsPresContext* aPresContext,
197                                           ReflowOutput& aDesiredSize,
198                                           const ReflowInput& aReflowInput) {
199   // The width/height of our content box, which is the available width/height
200   // for our anonymous content:
201   nscoord rangeFrameContentBoxWidth = aReflowInput.ComputedWidth();
202   nscoord rangeFrameContentBoxHeight = aReflowInput.ComputedHeight();
203   if (rangeFrameContentBoxHeight == NS_UNCONSTRAINEDSIZE) {
204     rangeFrameContentBoxHeight = 0;
205   }
206 
207   nsIFrame* trackFrame = mTrackDiv->GetPrimaryFrame();
208 
209   if (trackFrame) {  // display:none?
210 
211     // Position the track:
212     // The idea here is that we allow content authors to style the width,
213     // height, border and padding of the track, but we ignore margin and
214     // positioning properties and do the positioning ourself to keep the center
215     // of the track's border box on the center of the nsRangeFrame's content
216     // box.
217 
218     WritingMode wm = trackFrame->GetWritingMode();
219     LogicalSize availSize = aReflowInput.ComputedSize(wm);
220     availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
221     ReflowInput trackReflowInput(aPresContext, aReflowInput, trackFrame,
222                                  availSize);
223 
224     // Find the x/y position of the track frame such that it will be positioned
225     // as described above. These coordinates are with respect to the
226     // nsRangeFrame's border-box.
227     nscoord trackX = rangeFrameContentBoxWidth / 2;
228     nscoord trackY = rangeFrameContentBoxHeight / 2;
229 
230     // Account for the track's border and padding (we ignore its margin):
231     trackX -= trackReflowInput.ComputedPhysicalBorderPadding().left +
232               trackReflowInput.ComputedWidth() / 2;
233     trackY -= trackReflowInput.ComputedPhysicalBorderPadding().top +
234               trackReflowInput.ComputedHeight() / 2;
235 
236     // Make relative to our border box instead of our content box:
237     trackX += aReflowInput.ComputedPhysicalBorderPadding().left;
238     trackY += aReflowInput.ComputedPhysicalBorderPadding().top;
239 
240     nsReflowStatus frameStatus;
241     ReflowOutput trackDesiredSize(aReflowInput);
242     ReflowChild(trackFrame, aPresContext, trackDesiredSize, trackReflowInput,
243                 trackX, trackY, ReflowChildFlags::Default, frameStatus);
244     MOZ_ASSERT(
245         frameStatus.IsFullyComplete(),
246         "We gave our child unconstrained height, so it should be complete");
247     FinishReflowChild(trackFrame, aPresContext, trackDesiredSize,
248                       &trackReflowInput, trackX, trackY,
249                       ReflowChildFlags::Default);
250   }
251 
252   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
253 
254   if (thumbFrame) {  // display:none?
255     WritingMode wm = thumbFrame->GetWritingMode();
256     LogicalSize availSize = aReflowInput.ComputedSize(wm);
257     availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
258     ReflowInput thumbReflowInput(aPresContext, aReflowInput, thumbFrame,
259                                  availSize);
260 
261     // Where we position the thumb depends on its size, so we first reflow
262     // the thumb at {0,0} to obtain its size, then position it afterwards.
263 
264     nsReflowStatus frameStatus;
265     ReflowOutput thumbDesiredSize(aReflowInput);
266     ReflowChild(thumbFrame, aPresContext, thumbDesiredSize, thumbReflowInput, 0,
267                 0, ReflowChildFlags::Default, frameStatus);
268     MOZ_ASSERT(
269         frameStatus.IsFullyComplete(),
270         "We gave our child unconstrained height, so it should be complete");
271     FinishReflowChild(thumbFrame, aPresContext, thumbDesiredSize,
272                       &thumbReflowInput, 0, 0, ReflowChildFlags::Default);
273     DoUpdateThumbPosition(thumbFrame,
274                           nsSize(aDesiredSize.Width(), aDesiredSize.Height()));
275   }
276 
277   nsIFrame* rangeProgressFrame = mProgressDiv->GetPrimaryFrame();
278 
279   if (rangeProgressFrame) {  // display:none?
280     WritingMode wm = rangeProgressFrame->GetWritingMode();
281     LogicalSize availSize = aReflowInput.ComputedSize(wm);
282     availSize.BSize(wm) = NS_UNCONSTRAINEDSIZE;
283     ReflowInput progressReflowInput(aPresContext, aReflowInput,
284                                     rangeProgressFrame, availSize);
285 
286     // We first reflow the range-progress frame at {0,0} to obtain its
287     // unadjusted dimensions, then we adjust it to so that the appropriate edge
288     // ends at the thumb.
289 
290     nsReflowStatus frameStatus;
291     ReflowOutput progressDesiredSize(aReflowInput);
292     ReflowChild(rangeProgressFrame, aPresContext, progressDesiredSize,
293                 progressReflowInput, 0, 0, ReflowChildFlags::Default,
294                 frameStatus);
295     MOZ_ASSERT(
296         frameStatus.IsFullyComplete(),
297         "We gave our child unconstrained height, so it should be complete");
298     FinishReflowChild(rangeProgressFrame, aPresContext, progressDesiredSize,
299                       &progressReflowInput, 0, 0, ReflowChildFlags::Default);
300     DoUpdateRangeProgressFrame(
301         rangeProgressFrame,
302         nsSize(aDesiredSize.Width(), aDesiredSize.Height()));
303   }
304 }
305 
306 #ifdef ACCESSIBILITY
AccessibleType()307 a11y::AccType nsRangeFrame::AccessibleType() { return a11y::eHTMLRangeType; }
308 #endif
309 
GetValueAsFractionOfRange()310 double nsRangeFrame::GetValueAsFractionOfRange() {
311   MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::input), "bad cast");
312   auto* input = static_cast<dom::HTMLInputElement*>(GetContent());
313   MOZ_ASSERT(input->ControlType() == FormControlType::InputRange);
314 
315   Decimal value = input->GetValueAsDecimal();
316   Decimal minimum = input->GetMinimum();
317   Decimal maximum = input->GetMaximum();
318 
319   MOZ_ASSERT(value.isFinite() && minimum.isFinite() && maximum.isFinite(),
320              "type=range should have a default maximum/minimum");
321 
322   if (maximum <= minimum) {
323     // Avoid rounding triggering the assert by checking against an epsilon.
324     MOZ_ASSERT((value - minimum).abs().toDouble() <
325                    std::numeric_limits<float>::epsilon(),
326                "Unsanitized value");
327     return 0.0;
328   }
329 
330   MOZ_ASSERT(value >= minimum && value <= maximum, "Unsanitized value");
331 
332   return ((value - minimum) / (maximum - minimum)).toDouble();
333 }
334 
GetValueAtEventPoint(WidgetGUIEvent * aEvent)335 Decimal nsRangeFrame::GetValueAtEventPoint(WidgetGUIEvent* aEvent) {
336   MOZ_ASSERT(
337       aEvent->mClass == eMouseEventClass || aEvent->mClass == eTouchEventClass,
338       "Unexpected event type - aEvent->mRefPoint may be meaningless");
339 
340   MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::input), "bad cast");
341   dom::HTMLInputElement* input =
342       static_cast<dom::HTMLInputElement*>(GetContent());
343 
344   MOZ_ASSERT(input->ControlType() == FormControlType::InputRange);
345 
346   Decimal minimum = input->GetMinimum();
347   Decimal maximum = input->GetMaximum();
348   MOZ_ASSERT(minimum.isFinite() && maximum.isFinite(),
349              "type=range should have a default maximum/minimum");
350   if (maximum <= minimum) {
351     return minimum;
352   }
353   Decimal range = maximum - minimum;
354 
355   LayoutDeviceIntPoint absPoint;
356   if (aEvent->mClass == eTouchEventClass) {
357     MOZ_ASSERT(aEvent->AsTouchEvent()->mTouches.Length() == 1,
358                "Unexpected number of mTouches");
359     absPoint = aEvent->AsTouchEvent()->mTouches[0]->mRefPoint;
360   } else {
361     absPoint = aEvent->mRefPoint;
362   }
363   nsPoint point = nsLayoutUtils::GetEventCoordinatesRelativeTo(
364       aEvent, absPoint, RelativeTo{this});
365 
366   if (point == nsPoint(NS_UNCONSTRAINEDSIZE, NS_UNCONSTRAINEDSIZE)) {
367     // We don't want to change the current value for this error state.
368     return static_cast<dom::HTMLInputElement*>(GetContent())
369         ->GetValueAsDecimal();
370   }
371 
372   nsRect rangeContentRect = GetContentRectRelativeToSelf();
373   nsSize thumbSize;
374 
375   if (IsThemed()) {
376     // We need to get the size of the thumb from the theme.
377     nsPresContext* presContext = PresContext();
378     bool notUsedCanOverride;
379     LayoutDeviceIntSize size;
380     presContext->Theme()->GetMinimumWidgetSize(presContext, this,
381                                                StyleAppearance::RangeThumb,
382                                                &size, &notUsedCanOverride);
383     thumbSize.width = presContext->DevPixelsToAppUnits(size.width);
384     thumbSize.height = presContext->DevPixelsToAppUnits(size.height);
385     // For GTK, GetMinimumWidgetSize returns zero for the thumb dimension
386     // perpendicular to the orientation of the slider.  That's okay since we
387     // only care about the dimension in the direction of the slider when using
388     // |thumbSize| below, but it means this assertion need to check
389     // IsHorizontal().
390     MOZ_ASSERT((IsHorizontal() && thumbSize.width > 0) ||
391                    (!IsHorizontal() && thumbSize.height > 0),
392                "The thumb is expected to take up some slider space");
393   } else {
394     nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
395     if (thumbFrame) {  // diplay:none?
396       thumbSize = thumbFrame->GetSize();
397     }
398   }
399 
400   Decimal fraction;
401   if (IsHorizontal()) {
402     nscoord traversableDistance = rangeContentRect.width - thumbSize.width;
403     if (traversableDistance <= 0) {
404       return minimum;
405     }
406     nscoord posAtStart = rangeContentRect.x + thumbSize.width / 2;
407     nscoord posAtEnd = posAtStart + traversableDistance;
408     nscoord posOfPoint = mozilla::clamped(point.x, posAtStart, posAtEnd);
409     fraction = Decimal(posOfPoint - posAtStart) / Decimal(traversableDistance);
410     if (IsRightToLeft()) {
411       fraction = Decimal(1) - fraction;
412     }
413   } else {
414     nscoord traversableDistance = rangeContentRect.height - thumbSize.height;
415     if (traversableDistance <= 0) {
416       return minimum;
417     }
418     nscoord posAtStart = rangeContentRect.y + thumbSize.height / 2;
419     nscoord posAtEnd = posAtStart + traversableDistance;
420     nscoord posOfPoint = mozilla::clamped(point.y, posAtStart, posAtEnd);
421     // For a vertical range, the top (posAtStart) is the highest value, so we
422     // subtract the fraction from 1.0 to get that polarity correct.
423     fraction = Decimal(1) -
424                Decimal(posOfPoint - posAtStart) / Decimal(traversableDistance);
425   }
426 
427   MOZ_ASSERT(fraction >= Decimal(0) && fraction <= Decimal(1));
428   return minimum + fraction * range;
429 }
430 
UpdateForValueChange()431 void nsRangeFrame::UpdateForValueChange() {
432   if (IsSubtreeDirty()) {
433     return;  // we're going to be updated when we reflow
434   }
435   nsIFrame* rangeProgressFrame = mProgressDiv->GetPrimaryFrame();
436   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
437   if (!rangeProgressFrame && !thumbFrame) {
438     return;  // diplay:none?
439   }
440   if (rangeProgressFrame) {
441     DoUpdateRangeProgressFrame(rangeProgressFrame, GetSize());
442   }
443   if (thumbFrame) {
444     DoUpdateThumbPosition(thumbFrame, GetSize());
445   }
446   if (IsThemed()) {
447     // We don't know the exact dimensions or location of the thumb when native
448     // theming is applied, so we just repaint the entire range.
449     InvalidateFrame();
450   }
451 
452 #ifdef ACCESSIBILITY
453   if (nsAccessibilityService* accService =
454           PresShell::GetAccessibilityService()) {
455     accService->RangeValueChanged(PresShell(), mContent);
456   }
457 #endif
458 
459   SchedulePaint();
460 }
461 
DoUpdateThumbPosition(nsIFrame * aThumbFrame,const nsSize & aRangeSize)462 void nsRangeFrame::DoUpdateThumbPosition(nsIFrame* aThumbFrame,
463                                          const nsSize& aRangeSize) {
464   MOZ_ASSERT(aThumbFrame);
465 
466   // The idea here is that we want to position the thumb so that the center
467   // of the thumb is on an imaginary line drawn from the middle of one edge
468   // of the range frame's content box to the middle of the opposite edge of
469   // its content box (the opposite edges being the left/right edge if the
470   // range is horizontal, or else the top/bottom edges if the range is
471   // vertical). How far along this line the center of the thumb is placed
472   // depends on the value of the range.
473 
474   nsMargin borderAndPadding = GetUsedBorderAndPadding();
475   nsPoint newPosition(borderAndPadding.left, borderAndPadding.top);
476 
477   nsSize rangeContentBoxSize(aRangeSize);
478   rangeContentBoxSize.width -= borderAndPadding.LeftRight();
479   rangeContentBoxSize.height -= borderAndPadding.TopBottom();
480 
481   nsSize thumbSize = aThumbFrame->GetSize();
482   double fraction = GetValueAsFractionOfRange();
483   MOZ_ASSERT(fraction >= 0.0 && fraction <= 1.0);
484 
485   if (IsHorizontal()) {
486     if (thumbSize.width < rangeContentBoxSize.width) {
487       nscoord traversableDistance = rangeContentBoxSize.width - thumbSize.width;
488       if (IsRightToLeft()) {
489         newPosition.x += NSToCoordRound((1.0 - fraction) * traversableDistance);
490       } else {
491         newPosition.x += NSToCoordRound(fraction * traversableDistance);
492       }
493       newPosition.y += (rangeContentBoxSize.height - thumbSize.height) / 2;
494     }
495   } else {
496     if (thumbSize.height < rangeContentBoxSize.height) {
497       nscoord traversableDistance =
498           rangeContentBoxSize.height - thumbSize.height;
499       newPosition.x += (rangeContentBoxSize.width - thumbSize.width) / 2;
500       newPosition.y += NSToCoordRound((1.0 - fraction) * traversableDistance);
501     }
502   }
503   aThumbFrame->SetPosition(newPosition);
504 }
505 
DoUpdateRangeProgressFrame(nsIFrame * aRangeProgressFrame,const nsSize & aRangeSize)506 void nsRangeFrame::DoUpdateRangeProgressFrame(nsIFrame* aRangeProgressFrame,
507                                               const nsSize& aRangeSize) {
508   MOZ_ASSERT(aRangeProgressFrame);
509 
510   // The idea here is that we want to position the ::-moz-range-progress
511   // pseudo-element so that the center line running along its length is on the
512   // corresponding center line of the nsRangeFrame's content box. In the other
513   // dimension, we align the "start" edge of the ::-moz-range-progress
514   // pseudo-element's border-box with the corresponding edge of the
515   // nsRangeFrame's content box, and we size the progress element's border-box
516   // to have a length of GetValueAsFractionOfRange() times the nsRangeFrame's
517   // content-box size.
518 
519   nsMargin borderAndPadding = GetUsedBorderAndPadding();
520   nsSize progSize = aRangeProgressFrame->GetSize();
521   nsRect progRect(borderAndPadding.left, borderAndPadding.top, progSize.width,
522                   progSize.height);
523 
524   nsSize rangeContentBoxSize(aRangeSize);
525   rangeContentBoxSize.width -= borderAndPadding.LeftRight();
526   rangeContentBoxSize.height -= borderAndPadding.TopBottom();
527 
528   double fraction = GetValueAsFractionOfRange();
529   MOZ_ASSERT(fraction >= 0.0 && fraction <= 1.0);
530 
531   if (IsHorizontal()) {
532     nscoord progLength = NSToCoordRound(fraction * rangeContentBoxSize.width);
533     if (IsRightToLeft()) {
534       progRect.x += rangeContentBoxSize.width - progLength;
535     }
536     progRect.y += (rangeContentBoxSize.height - progSize.height) / 2;
537     progRect.width = progLength;
538   } else {
539     nscoord progLength = NSToCoordRound(fraction * rangeContentBoxSize.height);
540     progRect.x += (rangeContentBoxSize.width - progSize.width) / 2;
541     progRect.y += rangeContentBoxSize.height - progLength;
542     progRect.height = progLength;
543   }
544   aRangeProgressFrame->SetRect(progRect);
545 }
546 
AttributeChanged(int32_t aNameSpaceID,nsAtom * aAttribute,int32_t aModType)547 nsresult nsRangeFrame::AttributeChanged(int32_t aNameSpaceID,
548                                         nsAtom* aAttribute, int32_t aModType) {
549   NS_ASSERTION(mTrackDiv, "The track div must exist!");
550   NS_ASSERTION(mThumbDiv, "The thumb div must exist!");
551 
552   if (aNameSpaceID == kNameSpaceID_None) {
553     if (aAttribute == nsGkAtoms::value || aAttribute == nsGkAtoms::min ||
554         aAttribute == nsGkAtoms::max || aAttribute == nsGkAtoms::step) {
555       // We want to update the position of the thumb, except in one special
556       // case: If the value attribute is being set, it is possible that we are
557       // in the middle of a type change away from type=range, under the
558       // SetAttr(..., nsGkAtoms::value, ...) call in HTMLInputElement::
559       // HandleTypeChange. In that case the HTMLInputElement's type will
560       // already have changed, and if we call UpdateForValueChange()
561       // we'll fail the asserts under that call that check the type of our
562       // HTMLInputElement. Given that we're changing away from being a range
563       // and this frame will shortly be destroyed, there's no point in calling
564       // UpdateForValueChange() anyway.
565       MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::input), "bad cast");
566       bool typeIsRange =
567           static_cast<dom::HTMLInputElement*>(GetContent())->ControlType() ==
568           FormControlType::InputRange;
569       // If script changed the <input>'s type before setting these attributes
570       // then we don't need to do anything since we are going to be reframed.
571       if (typeIsRange) {
572         UpdateForValueChange();
573       }
574     } else if (aAttribute == nsGkAtoms::orient) {
575       PresShell()->FrameNeedsReflow(this, IntrinsicDirty::Resize,
576                                     NS_FRAME_IS_DIRTY);
577     }
578   }
579 
580   return nsContainerFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
581 }
582 
AutoCrossSize(Length aEm)583 nscoord nsRangeFrame::AutoCrossSize(Length aEm) {
584   nscoord minCrossSize(0);
585   if (IsThemed()) {
586     bool unused;
587     LayoutDeviceIntSize size;
588     nsPresContext* pc = PresContext();
589     pc->Theme()->GetMinimumWidgetSize(pc, this, StyleAppearance::RangeThumb,
590                                       &size, &unused);
591     minCrossSize =
592         pc->DevPixelsToAppUnits(IsHorizontal() ? size.height : size.width);
593   }
594   return std::max(minCrossSize, aEm.ScaledBy(CROSS_AXIS_EM_SIZE).ToAppUnits());
595 }
596 
OneEm(nsRangeFrame * aFrame)597 static mozilla::Length OneEm(nsRangeFrame* aFrame) {
598   return aFrame->StyleFont()->mFont.size.ScaledBy(
599       nsLayoutUtils::FontSizeInflationFor(aFrame));
600 }
601 
ComputeAutoSize(gfxContext * aRenderingContext,WritingMode aWM,const LogicalSize & aCBSize,nscoord aAvailableISize,const LogicalSize & aMargin,const LogicalSize & aBorderPadding,const StyleSizeOverrides & aSizeOverrides,ComputeSizeFlags aFlags)602 LogicalSize nsRangeFrame::ComputeAutoSize(
603     gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
604     nscoord aAvailableISize, const LogicalSize& aMargin,
605     const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
606     ComputeSizeFlags aFlags) {
607   bool isInlineOriented = IsInlineOriented();
608   auto em = OneEm(this);
609 
610   const WritingMode wm = GetWritingMode();
611   LogicalSize autoSize(wm);
612   if (isInlineOriented) {
613     autoSize.ISize(wm) = em.ScaledBy(MAIN_AXIS_EM_SIZE).ToAppUnits();
614     autoSize.BSize(wm) = AutoCrossSize(em);
615   } else {
616     autoSize.ISize(wm) = AutoCrossSize(em);
617     autoSize.BSize(wm) = em.ScaledBy(MAIN_AXIS_EM_SIZE).ToAppUnits();
618   }
619 
620   return autoSize.ConvertTo(aWM, wm);
621 }
622 
GetMinISize(gfxContext * aRenderingContext)623 nscoord nsRangeFrame::GetMinISize(gfxContext* aRenderingContext) {
624   auto pos = StylePosition();
625   auto wm = GetWritingMode();
626   if (pos->ISize(wm).HasPercent()) {
627     // https://drafts.csswg.org/css-sizing-3/#percentage-sizing
628     // https://drafts.csswg.org/css-sizing-3/#min-content-zero
629     return nsLayoutUtils::ResolveToLength<true>(
630         pos->ISize(wm).AsLengthPercentage(), nscoord(0));
631   }
632   return GetPrefISize(aRenderingContext);
633 }
634 
GetPrefISize(gfxContext * aRenderingContext)635 nscoord nsRangeFrame::GetPrefISize(gfxContext* aRenderingContext) {
636   auto em = OneEm(this);
637   if (IsInlineOriented()) {
638     return em.ScaledBy(MAIN_AXIS_EM_SIZE).ToAppUnits();
639   }
640   return AutoCrossSize(em);
641 }
642 
IsHorizontal() const643 bool nsRangeFrame::IsHorizontal() const {
644   dom::HTMLInputElement* element =
645       static_cast<dom::HTMLInputElement*>(GetContent());
646   return element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::orient,
647                               nsGkAtoms::horizontal, eCaseMatters) ||
648          (!element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::orient,
649                                 nsGkAtoms::vertical, eCaseMatters) &&
650           GetWritingMode().IsVertical() ==
651               element->AttrValueIs(kNameSpaceID_None, nsGkAtoms::orient,
652                                    nsGkAtoms::block, eCaseMatters));
653 }
654 
GetMin() const655 double nsRangeFrame::GetMin() const {
656   return static_cast<dom::HTMLInputElement*>(GetContent())
657       ->GetMinimum()
658       .toDouble();
659 }
660 
GetMax() const661 double nsRangeFrame::GetMax() const {
662   return static_cast<dom::HTMLInputElement*>(GetContent())
663       ->GetMaximum()
664       .toDouble();
665 }
666 
GetValue() const667 double nsRangeFrame::GetValue() const {
668   return static_cast<dom::HTMLInputElement*>(GetContent())
669       ->GetValueAsDecimal()
670       .toDouble();
671 }
672 
673 #define STYLES_DISABLING_NATIVE_THEMING \
674   NS_AUTHOR_SPECIFIED_BORDER_OR_BACKGROUND | NS_AUTHOR_SPECIFIED_PADDING
675 
ShouldUseNativeStyle() const676 bool nsRangeFrame::ShouldUseNativeStyle() const {
677   nsIFrame* trackFrame = mTrackDiv->GetPrimaryFrame();
678   nsIFrame* progressFrame = mProgressDiv->GetPrimaryFrame();
679   nsIFrame* thumbFrame = mThumbDiv->GetPrimaryFrame();
680 
681   return StyleDisplay()->EffectiveAppearance() == StyleAppearance::Range &&
682          trackFrame &&
683          !PresContext()->HasAuthorSpecifiedRules(
684              trackFrame, STYLES_DISABLING_NATIVE_THEMING) &&
685          progressFrame &&
686          !PresContext()->HasAuthorSpecifiedRules(
687              progressFrame, STYLES_DISABLING_NATIVE_THEMING) &&
688          thumbFrame &&
689          !PresContext()->HasAuthorSpecifiedRules(
690              thumbFrame, STYLES_DISABLING_NATIVE_THEMING);
691 }
692