This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathnsSliderFrame.cpp
More file actions
1481 lines (1240 loc) · 47.3 KB
/
Copy pathnsSliderFrame.cpp
File metadata and controls
1481 lines (1240 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//
// Eric Vaughan
// Netscape Communications
//
// See documentation in associated header file
//
#include "nsSliderFrame.h"
#include "gfxPrefs.h"
#include "mozilla/ComputedStyle.h"
#include "nsPresContext.h"
#include "nsIContent.h"
#include "nsCOMPtr.h"
#include "nsNameSpaceManager.h"
#include "nsGkAtoms.h"
#include "nsHTMLParts.h"
#include "nsCSSRendering.h"
#include "nsScrollbarButtonFrame.h"
#include "nsIScrollableFrame.h"
#include "nsIScrollbarMediator.h"
#include "nsISupportsImpl.h"
#include "nsScrollbarFrame.h"
#include "nsRepeatService.h"
#include "nsBoxLayoutState.h"
#include "nsSprocketLayout.h"
#include "nsIServiceManager.h"
#include "nsContentUtils.h"
#include "nsLayoutUtils.h"
#include "nsDisplayList.h"
#include "nsRefreshDriver.h" // for nsAPostRefreshObserver
#include "nsSVGIntegrationUtils.h"
#include "mozilla/Assertions.h" // for MOZ_ASSERT
#include "mozilla/LookAndFeel.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/Telemetry.h"
#include "mozilla/dom/Event.h"
#include "mozilla/gfx/gfxVars.h"
#include "mozilla/layers/APZCCallbackHelper.h"
#include "mozilla/layers/AsyncDragMetrics.h"
#include "mozilla/layers/InputAPZContext.h"
#include <algorithm>
using namespace mozilla;
using mozilla::dom::Event;
using mozilla::layers::APZCCallbackHelper;
using mozilla::layers::AsyncDragMetrics;
using mozilla::layers::InputAPZContext;
using mozilla::layers::ScrollbarData;
using mozilla::layers::ScrollDirection;
bool nsSliderFrame::gMiddlePref = false;
int32_t nsSliderFrame::gSnapMultiplier;
// Turn this on if you want to debug slider frames.
#undef DEBUG_SLIDER
static already_AddRefed<nsIContent> GetContentOfBox(nsIFrame* aBox) {
nsCOMPtr<nsIContent> content = aBox->GetContent();
return content.forget();
}
nsIFrame* NS_NewSliderFrame(nsIPresShell* aPresShell, ComputedStyle* aStyle) {
return new (aPresShell) nsSliderFrame(aStyle, aPresShell->GetPresContext());
}
NS_IMPL_FRAMEARENA_HELPERS(nsSliderFrame)
NS_QUERYFRAME_HEAD(nsSliderFrame)
NS_QUERYFRAME_ENTRY(nsSliderFrame)
NS_QUERYFRAME_TAIL_INHERITING(nsBoxFrame)
nsSliderFrame::nsSliderFrame(ComputedStyle* aStyle, nsPresContext* aPresContext)
: nsBoxFrame(aStyle, aPresContext, kClassID),
mRatio(0.0f),
mDragStart(0),
mThumbStart(0),
mCurPos(0),
mChange(0),
mDragFinished(true),
mUserChanged(false),
mScrollingWithAPZ(false),
mSuppressionActive(false) {}
// stop timer
nsSliderFrame::~nsSliderFrame() {
if (mSuppressionActive) {
if (mozilla::PresShell* presShell = PresShell()) {
presShell->SuppressDisplayport(false);
}
}
}
void nsSliderFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
nsIFrame* aPrevInFlow) {
nsBoxFrame::Init(aContent, aParent, aPrevInFlow);
static bool gotPrefs = false;
if (!gotPrefs) {
gotPrefs = true;
gMiddlePref = Preferences::GetBool("middlemouse.scrollbarPosition");
gSnapMultiplier = Preferences::GetInt("slider.snapMultiplier");
}
mCurPos = GetCurrentPosition(aContent);
}
void nsSliderFrame::RemoveFrame(ChildListID aListID, nsIFrame* aOldFrame) {
nsBoxFrame::RemoveFrame(aListID, aOldFrame);
if (mFrames.IsEmpty()) RemoveListener();
}
void nsSliderFrame::InsertFrames(ChildListID aListID, nsIFrame* aPrevFrame,
nsFrameList& aFrameList) {
bool wasEmpty = mFrames.IsEmpty();
nsBoxFrame::InsertFrames(aListID, aPrevFrame, aFrameList);
if (wasEmpty) AddListener();
}
void nsSliderFrame::AppendFrames(ChildListID aListID, nsFrameList& aFrameList) {
// if we have no children and on was added then make sure we add the
// listener
bool wasEmpty = mFrames.IsEmpty();
nsBoxFrame::AppendFrames(aListID, aFrameList);
if (wasEmpty) AddListener();
}
int32_t nsSliderFrame::GetCurrentPosition(nsIContent* content) {
return GetIntegerAttribute(content, nsGkAtoms::curpos, 0);
}
int32_t nsSliderFrame::GetMinPosition(nsIContent* content) {
return GetIntegerAttribute(content, nsGkAtoms::minpos, 0);
}
int32_t nsSliderFrame::GetMaxPosition(nsIContent* content) {
return GetIntegerAttribute(content, nsGkAtoms::maxpos, 100);
}
int32_t nsSliderFrame::GetIncrement(nsIContent* content) {
return GetIntegerAttribute(content, nsGkAtoms::increment, 1);
}
int32_t nsSliderFrame::GetPageIncrement(nsIContent* content) {
return GetIntegerAttribute(content, nsGkAtoms::pageincrement, 10);
}
int32_t nsSliderFrame::GetIntegerAttribute(nsIContent* content, nsAtom* atom,
int32_t defaultValue) {
nsAutoString value;
if (content->IsElement()) {
content->AsElement()->GetAttr(kNameSpaceID_None, atom, value);
}
if (!value.IsEmpty()) {
nsresult error;
// convert it to an integer
defaultValue = value.ToInteger(&error);
}
return defaultValue;
}
nsresult nsSliderFrame::AttributeChanged(int32_t aNameSpaceID,
nsAtom* aAttribute, int32_t aModType) {
nsresult rv =
nsBoxFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
// if the current position changes
if (aAttribute == nsGkAtoms::curpos) {
CurrentPositionChanged();
} else if (aAttribute == nsGkAtoms::minpos ||
aAttribute == nsGkAtoms::maxpos) {
// bounds check it.
nsIFrame* scrollbarBox = GetScrollbar();
nsCOMPtr<nsIContent> scrollbar = GetContentOfBox(scrollbarBox);
int32_t current = GetCurrentPosition(scrollbar);
int32_t min = GetMinPosition(scrollbar);
int32_t max = GetMaxPosition(scrollbar);
if (current < min || current > max) {
int32_t direction = 0;
if (current < min || max < min) {
current = min;
direction = -1;
} else if (current > max) {
current = max;
direction = 1;
}
// set the new position and notify observers
nsScrollbarFrame* scrollbarFrame = do_QueryFrame(scrollbarBox);
if (scrollbarFrame) {
nsIScrollbarMediator* mediator = scrollbarFrame->GetScrollbarMediator();
scrollbarFrame->SetIncrementToWhole(direction);
if (mediator) {
mediator->ScrollByWhole(scrollbarFrame, direction,
nsIScrollbarMediator::ENABLE_SNAP);
}
}
// 'this' might be destroyed here
nsContentUtils::AddScriptRunner(new nsSetAttrRunnable(
scrollbar->AsElement(), nsGkAtoms::curpos, current));
}
}
if (aAttribute == nsGkAtoms::minpos || aAttribute == nsGkAtoms::maxpos ||
aAttribute == nsGkAtoms::pageincrement ||
aAttribute == nsGkAtoms::increment) {
PresShell()->FrameNeedsReflow(this, nsIPresShell::eStyleChange,
NS_FRAME_IS_DIRTY);
}
return rv;
}
void nsSliderFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
const nsDisplayListSet& aLists) {
if (aBuilder->IsForEventDelivery() && isDraggingThumb()) {
// This is EVIL, we shouldn't be messing with event delivery just to get
// thumb mouse drag events to arrive at the slider!
aLists.Outlines()->AppendNewToTop<nsDisplayEventReceiver>(aBuilder, this);
return;
}
nsBoxFrame::BuildDisplayList(aBuilder, aLists);
}
static bool UsesCustomScrollbarMediator(nsIFrame* scrollbarBox) {
if (nsScrollbarFrame* scrollbarFrame = do_QueryFrame(scrollbarBox)) {
if (nsIScrollbarMediator* mediator =
scrollbarFrame->GetScrollbarMediator()) {
nsIScrollableFrame* scrollFrame = do_QueryFrame(mediator);
// The scrollbar mediator is not the scroll frame.
// That means this scroll frame has a custom scrollbar mediator.
if (!scrollFrame) {
return true;
}
}
}
return false;
}
void nsSliderFrame::BuildDisplayListForChildren(
nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
// if we are too small to have a thumb don't paint it.
nsIFrame* thumb = nsBox::GetChildXULBox(this);
if (thumb) {
nsRect thumbRect(thumb->GetRect());
nsMargin m;
thumb->GetXULMargin(m);
thumbRect.Inflate(m);
nsRect sliderTrack;
GetXULClientRect(sliderTrack);
if (sliderTrack.width < thumbRect.width ||
sliderTrack.height < thumbRect.height)
return;
// If this scrollbar is the scrollbar of an actively scrolled scroll frame,
// layerize the scrollbar thumb, wrap it in its own ContainerLayer and
// attach scrolling information to it.
// We do this here and not in the thumb's nsBoxFrame::BuildDisplayList so
// that the event region that gets created for the thumb is included in
// the nsDisplayOwnLayer contents.
const mozilla::layers::ScrollableLayerGuid::ViewID scrollTargetId =
aBuilder->GetCurrentScrollbarTarget();
const bool thumbGetsLayer =
(scrollTargetId != layers::ScrollableLayerGuid::NULL_SCROLL_ID);
if (thumbGetsLayer) {
const Maybe<ScrollDirection> scrollDirection =
aBuilder->GetCurrentScrollbarDirection();
MOZ_ASSERT(scrollDirection.isSome());
const bool isHorizontal =
*scrollDirection == ScrollDirection::eHorizontal;
const float appUnitsPerCss = float(AppUnitsPerCSSPixel());
const CSSCoord thumbLength = NSAppUnitsToFloatPixels(
isHorizontal ? thumbRect.width : thumbRect.height, appUnitsPerCss);
nsIFrame* scrollbarBox = GetScrollbar();
bool isAsyncDraggable = !UsesCustomScrollbarMediator(scrollbarBox);
nsPoint scrollPortOrigin;
if (nsIScrollableFrame* scrollFrame =
do_QueryFrame(scrollbarBox->GetParent())) {
scrollPortOrigin = scrollFrame->GetScrollPortRect().TopLeft();
} else {
isAsyncDraggable = false;
}
// This rect is the range in which the scroll thumb can slide in.
sliderTrack = sliderTrack + GetRect().TopLeft() +
scrollbarBox->GetPosition() - scrollPortOrigin;
const CSSCoord sliderTrackStart = NSAppUnitsToFloatPixels(
isHorizontal ? sliderTrack.x : sliderTrack.y, appUnitsPerCss);
const CSSCoord sliderTrackLength = NSAppUnitsToFloatPixels(
isHorizontal ? sliderTrack.width : sliderTrack.height,
appUnitsPerCss);
const CSSCoord thumbStart = NSAppUnitsToFloatPixels(
isHorizontal ? thumbRect.x : thumbRect.y, appUnitsPerCss);
const nsRect overflow = thumb->GetVisualOverflowRectRelativeToParent();
nsSize refSize = aBuilder->RootReferenceFrame()->GetSize();
const gfxSize scale = nsLayoutUtils::GetTransformToAncestorScale(thumb);
if (scale.width != 0 && scale.height != 0) {
refSize.width /= scale.width;
refSize.height /= scale.height;
}
nsRect dirty = aBuilder->GetVisibleRect().Intersect(thumbRect);
dirty = nsLayoutUtils::ComputePartialPrerenderArea(
aBuilder->GetVisibleRect(), overflow, refSize);
nsDisplayListBuilder::AutoBuildingDisplayList buildingDisplayList(
aBuilder, this, dirty, dirty);
// Clip the thumb layer to the slider track. This is necessary to ensure
// FrameLayerBuilder is able to merge content before and after the
// scrollframe into the same layer (otherwise it thinks the thumb could
// potentially move anywhere within the existing clip).
DisplayListClipState::AutoSaveRestore thumbClipState(aBuilder);
thumbClipState.ClipContainingBlockDescendants(
GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(this));
// Have the thumb's container layer capture the current clip, so
// it doesn't apply to the thumb's contents. This allows the contents
// to be fully rendered even if they're partially or fully offscreen,
// so async scrolling can still bring it into view.
DisplayListClipState::AutoSaveRestore thumbContentsClipState(aBuilder);
thumbContentsClipState.Clear();
nsDisplayListBuilder::AutoContainerASRTracker contASRTracker(aBuilder);
nsDisplayListCollection tempLists(aBuilder);
nsBoxFrame::BuildDisplayListForChildren(aBuilder, tempLists);
// This is a bit of a hack. Collect up all descendant display items
// and merge them into a single Content() list.
nsDisplayList masterList;
masterList.AppendToTop(tempLists.BorderBackground());
masterList.AppendToTop(tempLists.BlockBorderBackgrounds());
masterList.AppendToTop(tempLists.Floats());
masterList.AppendToTop(tempLists.Content());
masterList.AppendToTop(tempLists.PositionedDescendants());
masterList.AppendToTop(tempLists.Outlines());
// Restore the saved clip so it applies to the thumb container layer.
thumbContentsClipState.Restore();
// Wrap the list to make it its own layer.
const ActiveScrolledRoot* ownLayerASR = contASRTracker.GetContainerASR();
aLists.Content()->AppendNewToTop<nsDisplayOwnLayer>(
aBuilder, this, &masterList, ownLayerASR,
nsDisplayOwnLayerFlags::eNone,
ScrollbarData::CreateForThumb(*scrollDirection, GetThumbRatio(),
thumbStart, thumbLength,
isAsyncDraggable, sliderTrackStart,
sliderTrackLength, scrollTargetId));
return;
}
}
nsBoxFrame::BuildDisplayListForChildren(aBuilder, aLists);
}
NS_IMETHODIMP
nsSliderFrame::DoXULLayout(nsBoxLayoutState& aState) {
// get the thumb should be our only child
nsIFrame* thumbBox = nsBox::GetChildXULBox(this);
if (!thumbBox) {
SyncLayout(aState);
return NS_OK;
}
EnsureOrient();
// get the content area inside our borders
nsRect clientRect;
GetXULClientRect(clientRect);
// get the scrollbar
nsIFrame* scrollbarBox = GetScrollbar();
nsCOMPtr<nsIContent> scrollbar = GetContentOfBox(scrollbarBox);
// get the thumb's pref size
nsSize thumbSize = thumbBox->GetXULPrefSize(aState);
if (IsXULHorizontal())
thumbSize.height = clientRect.height;
else
thumbSize.width = clientRect.width;
int32_t curPos = GetCurrentPosition(scrollbar);
int32_t minPos = GetMinPosition(scrollbar);
int32_t maxPos = GetMaxPosition(scrollbar);
int32_t pageIncrement = GetPageIncrement(scrollbar);
maxPos = std::max(minPos, maxPos);
curPos = clamped(curPos, minPos, maxPos);
nscoord& availableLength =
IsXULHorizontal() ? clientRect.width : clientRect.height;
nscoord& thumbLength = IsXULHorizontal() ? thumbSize.width : thumbSize.height;
if ((pageIncrement + maxPos - minPos) > 0 && thumbBox->GetXULFlex() > 0) {
float ratio = float(pageIncrement) / float(maxPos - minPos + pageIncrement);
thumbLength =
std::max(thumbLength, NSToCoordRound(availableLength * ratio));
}
// Round the thumb's length to device pixels.
nsPresContext* presContext = PresContext();
thumbLength = presContext->DevPixelsToAppUnits(
presContext->AppUnitsToDevPixels(thumbLength));
// mRatio translates the thumb position in app units to the value.
mRatio = (minPos != maxPos)
? float(availableLength - thumbLength) / float(maxPos - minPos)
: 1;
// in reverse mode, curpos is reversed such that lower values are to the
// right or bottom and increase leftwards or upwards. In this case, use the
// offset from the end instead of the beginning.
bool reverse = mContent->AsElement()->AttrValueIs(
kNameSpaceID_None, nsGkAtoms::dir, nsGkAtoms::reverse, eCaseMatters);
nscoord pos = reverse ? (maxPos - curPos) : (curPos - minPos);
// set the thumb's coord to be the current pos * the ratio.
nsRect thumbRect(clientRect.x, clientRect.y, thumbSize.width,
thumbSize.height);
int32_t& thumbPos = (IsXULHorizontal() ? thumbRect.x : thumbRect.y);
thumbPos += NSToCoordRound(pos * mRatio);
nsRect oldThumbRect(thumbBox->GetRect());
LayoutChildAt(aState, thumbBox, thumbRect);
SyncLayout(aState);
// Redraw only if thumb changed size.
if (!oldThumbRect.IsEqualInterior(thumbRect)) XULRedraw(aState);
return NS_OK;
}
nsresult nsSliderFrame::HandleEvent(nsPresContext* aPresContext,
WidgetGUIEvent* aEvent,
nsEventStatus* aEventStatus) {
NS_ENSURE_ARG_POINTER(aEventStatus);
if (mAPZDragInitiated &&
*mAPZDragInitiated == InputAPZContext::GetInputBlockId() &&
aEvent->mMessage == eMouseDown) {
// If we get the mousedown after the APZ notification, then immediately
// switch into the state corresponding to an APZ thumb-drag. Note that
// we can't just do this in AsyncScrollbarDragInitiated() directly because
// the handling for this mousedown event in the presShell will reset the
// capturing content which makes isDraggingThumb() return false. We check
// the input block here to make sure that we correctly handle any ordering
// of {eMouseDown arriving, AsyncScrollbarDragInitiated() being called}.
mAPZDragInitiated = Nothing();
DragThumb(true);
mScrollingWithAPZ = true;
return NS_OK;
}
// If a web page calls event.preventDefault() we still want to
// scroll when scroll arrow is clicked. See bug 511075.
if (!mContent->IsInNativeAnonymousSubtree() &&
nsEventStatus_eConsumeNoDefault == *aEventStatus) {
return NS_OK;
}
if (!mDragFinished && !isDraggingThumb()) {
StopDrag();
return NS_OK;
}
nsIFrame* scrollbarBox = GetScrollbar();
nsCOMPtr<nsIContent> scrollbar;
scrollbar = GetContentOfBox(scrollbarBox);
bool isHorizontal = IsXULHorizontal();
if (isDraggingThumb()) {
switch (aEvent->mMessage) {
case eTouchMove:
case eMouseMove: {
if (mScrollingWithAPZ) {
break;
}
nsPoint eventPoint;
if (!GetEventPoint(aEvent, eventPoint)) {
break;
}
if (mChange) {
// On Linux the destination point is determined by the initial click
// on the scrollbar track and doesn't change until the mouse button
// is released.
#ifndef MOZ_WIDGET_GTK
// On the other platforms we need to update the destination point now.
mDestinationPoint = eventPoint;
StopRepeat();
StartRepeat();
#endif
break;
}
nscoord pos = isHorizontal ? eventPoint.x : eventPoint.y;
nsIFrame* thumbFrame = mFrames.FirstChild();
if (!thumbFrame) {
return NS_OK;
}
// take our current position and subtract the start location
pos -= mDragStart;
bool isMouseOutsideThumb = false;
if (gSnapMultiplier) {
nsSize thumbSize = thumbFrame->GetSize();
if (isHorizontal) {
// horizontal scrollbar - check if mouse is above or below thumb
// XXXbz what about looking at the .y of the thumb's rect? Is that
// always zero here?
if (eventPoint.y < -gSnapMultiplier * thumbSize.height ||
eventPoint.y >
thumbSize.height + gSnapMultiplier * thumbSize.height)
isMouseOutsideThumb = true;
} else {
// vertical scrollbar - check if mouse is left or right of thumb
if (eventPoint.x < -gSnapMultiplier * thumbSize.width ||
eventPoint.x >
thumbSize.width + gSnapMultiplier * thumbSize.width)
isMouseOutsideThumb = true;
}
}
if (aEvent->mClass == eTouchEventClass) {
*aEventStatus = nsEventStatus_eConsumeNoDefault;
}
if (isMouseOutsideThumb) {
SetCurrentThumbPosition(scrollbar, mThumbStart, false, false);
return NS_OK;
}
// set it
SetCurrentThumbPosition(scrollbar, pos, false, true); // with snapping
} break;
case eTouchEnd:
case eMouseUp:
if (ShouldScrollForEvent(aEvent)) {
StopDrag();
// we MUST call nsFrame HandleEvent for mouse ups to maintain the
// selection state and capture state.
return nsFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
}
break;
default:
break;
}
// return nsFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
return NS_OK;
} else if (ShouldScrollToClickForEvent(aEvent)) {
nsPoint eventPoint;
if (!GetEventPoint(aEvent, eventPoint)) {
return NS_OK;
}
nscoord pos = isHorizontal ? eventPoint.x : eventPoint.y;
// adjust so that the middle of the thumb is placed under the click
nsIFrame* thumbFrame = mFrames.FirstChild();
if (!thumbFrame) {
return NS_OK;
}
nsSize thumbSize = thumbFrame->GetSize();
nscoord thumbLength = isHorizontal ? thumbSize.width : thumbSize.height;
// set it
AutoWeakFrame weakFrame(this);
// should aMaySnap be true here?
SetCurrentThumbPosition(scrollbar, pos - thumbLength / 2, false, false);
NS_ENSURE_TRUE(weakFrame.IsAlive(), NS_OK);
DragThumb(true);
#ifdef MOZ_WIDGET_GTK
RefPtr<Element> thumb = thumbFrame->GetContent()->AsElement();
thumb->SetAttr(kNameSpaceID_None, nsGkAtoms::active,
NS_LITERAL_STRING("true"), true);
#endif
if (aEvent->mClass == eTouchEventClass) {
*aEventStatus = nsEventStatus_eConsumeNoDefault;
}
if (isHorizontal)
mThumbStart = thumbFrame->GetPosition().x;
else
mThumbStart = thumbFrame->GetPosition().y;
mDragStart = pos - mThumbStart;
}
#ifdef MOZ_WIDGET_GTK
else if (ShouldScrollForEvent(aEvent) && aEvent->mClass == eMouseEventClass &&
aEvent->AsMouseEvent()->button == WidgetMouseEvent::eRightButton) {
// HandlePress and HandleRelease are usually called via
// nsFrame::HandleEvent, but only for the left mouse button.
if (aEvent->mMessage == eMouseDown) {
HandlePress(aPresContext, aEvent, aEventStatus);
} else if (aEvent->mMessage == eMouseUp) {
HandleRelease(aPresContext, aEvent, aEventStatus);
}
return NS_OK;
}
#endif
// XXX hack until handle release is actually called in nsframe.
// if (aEvent->mMessage == eMouseOut ||
// aEvent->mMessage == NS_MOUSE_RIGHT_BUTTON_UP ||
// aEvent->mMessage == NS_MOUSE_LEFT_BUTTON_UP) {
// HandleRelease(aPresContext, aEvent, aEventStatus);
// }
if (aEvent->mMessage == eMouseOut && mChange)
HandleRelease(aPresContext, aEvent, aEventStatus);
return nsFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
}
// Helper function to collect the "scroll to click" metric. Beware of
// caching this, users expect to be able to change the system preference
// and see the browser change its behavior immediately.
bool nsSliderFrame::GetScrollToClick() {
if (GetScrollbar() != this) {
return LookAndFeel::GetInt(LookAndFeel::eIntID_ScrollToClick, false);
}
if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
nsGkAtoms::movetoclick,
nsGkAtoms::_true, eCaseMatters)) {
return true;
}
if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None,
nsGkAtoms::movetoclick,
nsGkAtoms::_false, eCaseMatters)) {
return false;
}
#ifdef XP_MACOSX
return true;
#else
return false;
#endif
}
nsIFrame* nsSliderFrame::GetScrollbar() {
// if we are in a scrollbar then return the scrollbar's content node
// if we are not then return ours.
nsIFrame* scrollbar;
nsScrollbarButtonFrame::GetParentWithTag(nsGkAtoms::scrollbar, this,
scrollbar);
if (scrollbar == nullptr) return this;
return scrollbar->IsXULBoxFrame() ? scrollbar : this;
}
void nsSliderFrame::PageUpDown(nscoord change) {
// on a page up or down get our page increment. We get this by getting the
// scrollbar we are in and asking it for the current position and the page
// increment. If we are not in a scrollbar we will get the values from our own
// node.
nsIFrame* scrollbarBox = GetScrollbar();
nsCOMPtr<nsIContent> scrollbar;
scrollbar = GetContentOfBox(scrollbarBox);
nscoord pageIncrement = GetPageIncrement(scrollbar);
int32_t curpos = GetCurrentPosition(scrollbar);
int32_t minpos = GetMinPosition(scrollbar);
int32_t maxpos = GetMaxPosition(scrollbar);
// get the new position and make sure it is in bounds
int32_t newpos = curpos + change * pageIncrement;
if (newpos < minpos || maxpos < minpos)
newpos = minpos;
else if (newpos > maxpos)
newpos = maxpos;
SetCurrentPositionInternal(scrollbar, newpos, true);
}
// called when the current position changed and we need to update the thumb's
// location
void nsSliderFrame::CurrentPositionChanged() {
nsIFrame* scrollbarBox = GetScrollbar();
nsCOMPtr<nsIContent> scrollbar = GetContentOfBox(scrollbarBox);
// get the current position
int32_t curPos = GetCurrentPosition(scrollbar);
// do nothing if the position did not change
if (mCurPos == curPos) return;
// get our current min and max position from our content node
int32_t minPos = GetMinPosition(scrollbar);
int32_t maxPos = GetMaxPosition(scrollbar);
maxPos = std::max(minPos, maxPos);
curPos = clamped(curPos, minPos, maxPos);
// get the thumb's rect
nsIFrame* thumbFrame = mFrames.FirstChild();
if (!thumbFrame) return; // The thumb may stream in asynchronously via XBL.
nsRect thumbRect = thumbFrame->GetRect();
nsRect clientRect;
GetXULClientRect(clientRect);
// figure out the new rect
nsRect newThumbRect(thumbRect);
bool reverse = mContent->AsElement()->AttrValueIs(
kNameSpaceID_None, nsGkAtoms::dir, nsGkAtoms::reverse, eCaseMatters);
nscoord pos = reverse ? (maxPos - curPos) : (curPos - minPos);
if (IsXULHorizontal())
newThumbRect.x = clientRect.x + NSToCoordRound(pos * mRatio);
else
newThumbRect.y = clientRect.y + NSToCoordRound(pos * mRatio);
// avoid putting the scroll thumb at subpixel positions which cause needless
// invalidations
nscoord appUnitsPerPixel = PresContext()->AppUnitsPerDevPixel();
nsPoint snappedThumbLocation =
ToAppUnits(newThumbRect.TopLeft().ToNearestPixels(appUnitsPerPixel),
appUnitsPerPixel);
if (IsXULHorizontal()) {
newThumbRect.x = snappedThumbLocation.x;
} else {
newThumbRect.y = snappedThumbLocation.y;
}
// set the rect
thumbFrame->SetRect(newThumbRect);
// Request a repaint of the scrollbar
nsScrollbarFrame* scrollbarFrame = do_QueryFrame(scrollbarBox);
nsIScrollbarMediator* mediator =
scrollbarFrame ? scrollbarFrame->GetScrollbarMediator() : nullptr;
if (!mediator || !mediator->ShouldSuppressScrollbarRepaints()) {
SchedulePaint();
}
mCurPos = curPos;
}
static void UpdateAttribute(Element* aScrollbar, nscoord aNewPos, bool aNotify,
bool aIsSmooth) {
nsAutoString str;
str.AppendInt(aNewPos);
if (aIsSmooth) {
aScrollbar->SetAttr(kNameSpaceID_None, nsGkAtoms::smooth,
NS_LITERAL_STRING("true"), false);
}
aScrollbar->SetAttr(kNameSpaceID_None, nsGkAtoms::curpos, str, aNotify);
if (aIsSmooth) {
aScrollbar->UnsetAttr(kNameSpaceID_None, nsGkAtoms::smooth, false);
}
}
// Use this function when you want to set the scroll position via the position
// of the scrollbar thumb, e.g. when dragging the slider. This function scrolls
// the content in such a way that thumbRect.x/.y becomes aNewThumbPos.
void nsSliderFrame::SetCurrentThumbPosition(nsIContent* aScrollbar,
nscoord aNewThumbPos,
bool aIsSmooth, bool aMaySnap) {
nsRect crect;
GetXULClientRect(crect);
nscoord offset = IsXULHorizontal() ? crect.x : crect.y;
int32_t newPos = NSToIntRound((aNewThumbPos - offset) / mRatio);
if (aMaySnap &&
mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::snap,
nsGkAtoms::_true, eCaseMatters)) {
// If snap="true", then the slider may only be set to min + (increment * x).
// Otherwise, the slider may be set to any positive integer.
int32_t increment = GetIncrement(aScrollbar);
newPos = NSToIntRound(newPos / float(increment)) * increment;
}
SetCurrentPosition(aScrollbar, newPos, aIsSmooth);
}
// Use this function when you know the target scroll position of the scrolled
// content. aNewPos should be passed to this function as a position as if the
// minpos is 0. That is, the minpos will be added to the position by this
// function. In a reverse direction slider, the newpos should be the distance
// from the end.
void nsSliderFrame::SetCurrentPosition(nsIContent* aScrollbar, int32_t aNewPos,
bool aIsSmooth) {
// get min and max position from our content node
int32_t minpos = GetMinPosition(aScrollbar);
int32_t maxpos = GetMaxPosition(aScrollbar);
// in reverse direction sliders, flip the value so that it goes from
// right to left, or bottom to top.
if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::dir,
nsGkAtoms::reverse, eCaseMatters))
aNewPos = maxpos - aNewPos;
else
aNewPos += minpos;
// get the new position and make sure it is in bounds
if (aNewPos < minpos || maxpos < minpos)
aNewPos = minpos;
else if (aNewPos > maxpos)
aNewPos = maxpos;
SetCurrentPositionInternal(aScrollbar, aNewPos, aIsSmooth);
}
void nsSliderFrame::SetCurrentPositionInternal(nsIContent* aScrollbar,
int32_t aNewPos,
bool aIsSmooth) {
nsCOMPtr<nsIContent> scrollbar = aScrollbar;
nsIFrame* scrollbarBox = GetScrollbar();
AutoWeakFrame weakFrame(this);
mUserChanged = true;
nsScrollbarFrame* scrollbarFrame = do_QueryFrame(scrollbarBox);
if (scrollbarFrame) {
// See if we have a mediator.
nsIScrollbarMediator* mediator = scrollbarFrame->GetScrollbarMediator();
if (mediator) {
nscoord oldPos =
nsPresContext::CSSPixelsToAppUnits(GetCurrentPosition(scrollbar));
nscoord newPos = nsPresContext::CSSPixelsToAppUnits(aNewPos);
mediator->ThumbMoved(scrollbarFrame, oldPos, newPos);
if (!weakFrame.IsAlive()) {
return;
}
UpdateAttribute(scrollbar->AsElement(), aNewPos, /* aNotify */ false,
aIsSmooth);
CurrentPositionChanged();
mUserChanged = false;
return;
}
}
UpdateAttribute(scrollbar->AsElement(), aNewPos, true, aIsSmooth);
if (!weakFrame.IsAlive()) {
return;
}
mUserChanged = false;
#ifdef DEBUG_SLIDER
printf("Current Pos=%d\n", aNewPos);
#endif
}
void nsSliderFrame::SetInitialChildList(ChildListID aListID,
nsFrameList& aChildList) {
nsBoxFrame::SetInitialChildList(aListID, aChildList);
if (aListID == kPrincipalList) {
AddListener();
}
}
nsresult nsSliderMediator::HandleEvent(dom::Event* aEvent) {
// Only process the event if the thumb is not being dragged.
if (mSlider && !mSlider->isDraggingThumb()) return mSlider->StartDrag(aEvent);
return NS_OK;
}
class AsyncScrollbarDragStarter final : public nsAPostRefreshObserver {
public:
AsyncScrollbarDragStarter(nsIPresShell* aPresShell, nsIWidget* aWidget,
const AsyncDragMetrics& aDragMetrics)
: mPresShell(aPresShell), mWidget(aWidget), mDragMetrics(aDragMetrics) {}
virtual ~AsyncScrollbarDragStarter() {}
void DidRefresh() override {
if (!mPresShell) {
MOZ_ASSERT_UNREACHABLE(
"Post-refresh observer fired again after failed attempt at "
"unregistering it");
return;
}
mWidget->StartAsyncScrollbarDrag(mDragMetrics);
if (!mPresShell->RemovePostRefreshObserver(this)) {
MOZ_ASSERT_UNREACHABLE(
"Unable to unregister post-refresh observer! Leaking it instead of "
"leaving garbage registered");
// Graceful handling, just in case...
mPresShell = nullptr;
mWidget = nullptr;
return;
}
delete this;
}
private:
RefPtr<nsIPresShell> mPresShell;
RefPtr<nsIWidget> mWidget;
AsyncDragMetrics mDragMetrics;
};
static bool UsesSVGEffects(nsIFrame* aFrame) {
return aFrame->StyleEffects()->HasFilters() ||
nsSVGIntegrationUtils::UsingMaskOrClipPathForFrame(aFrame);
}
static bool ScrollFrameWillBuildScrollInfoLayer(nsIFrame* aScrollFrame) {
if (gfx::gfxVars::UseWebRender()) {
// If WebRender is enabled, even scrollframes enclosed in SVG effects can
// be drag-scrolled by APZ.
return false;
}
nsIFrame* current = aScrollFrame;
while (current) {
if (UsesSVGEffects(current)) {
return true;
}
current = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(current);
}
return false;
}
nsIScrollableFrame* nsSliderFrame::GetScrollFrame() {
nsIFrame* scrollbarBox = GetScrollbar();
if (!scrollbarBox) {
return nullptr;
}
nsContainerFrame* scrollFrame = scrollbarBox->GetParent();
if (!scrollFrame) {
return nullptr;
}
nsIScrollableFrame* scrollFrameAsScrollable = do_QueryFrame(scrollFrame);
return scrollFrameAsScrollable;
}
void nsSliderFrame::StartAPZDrag(WidgetGUIEvent* aEvent) {
if (!aEvent->mFlags.mHandledByAPZ) {
return;
}
if (!gfxPlatform::GetPlatform()->SupportsApzDragInput()) {
return;
}
nsIFrame* scrollbarBox = GetScrollbar();
nsContainerFrame* scrollFrame = scrollbarBox->GetParent();
if (!scrollFrame) {
return;
}
nsIContent* scrollableContent = scrollFrame->GetContent();
if (!scrollableContent) {
return;
}
// APZ dragging requires the scrollbar to be layerized, which doesn't
// happen for scroll info layers.
if (ScrollFrameWillBuildScrollInfoLayer(scrollFrame)) {
return;
}
// Custom scrollbar mediators are not supported in the APZ codepath.
if (UsesCustomScrollbarMediator(scrollbarBox)) {
return;
}
bool isHorizontal = IsXULHorizontal();
mozilla::layers::ScrollableLayerGuid::ViewID scrollTargetId;
bool hasID = nsLayoutUtils::FindIDFor(scrollableContent, &scrollTargetId);