summaryrefslogtreecommitdiffstats
path: root/layout/xul/nsSliderFrame.cpp
blob: 6d26f760353015fe343bea2b4e003f0a508b7b1a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
/* -*- 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 "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 "nsContentUtils.h"
#include "nsLayoutUtils.h"
#include "nsDisplayList.h"
#include "nsDeviceContext.h"
#include "nsRefreshDriver.h"     // for nsAPostRefreshObserver
#include "mozilla/Assertions.h"  // for MOZ_ASSERT
#include "mozilla/DisplayPortUtils.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_general.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/SVGIntegrationUtils.h"
#include "mozilla/Telemetry.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/Event.h"
#include "mozilla/layers/APZCCallbackHelper.h"
#include "mozilla/layers/AsyncDragMetrics.h"
#include "mozilla/layers/InputAPZContext.h"
#include "mozilla/layers/WebRenderLayerManager.h"
#include "mozilla/StaticPrefs_slider.h"
#include <algorithm>

using namespace mozilla;
using namespace mozilla::gfx;
using mozilla::dom::Document;
using mozilla::dom::Event;
using mozilla::layers::AsyncDragMetrics;
using mozilla::layers::InputAPZContext;
using mozilla::layers::ScrollbarData;
using mozilla::layers::ScrollDirection;

bool nsSliderFrame::gMiddlePref = false;

// Turn this on if you want to debug slider frames.
#undef DEBUG_SLIDER

nsIFrame* NS_NewSliderFrame(PresShell* 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(nsContainerFrame)

nsSliderFrame::nsSliderFrame(ComputedStyle* aStyle, nsPresContext* aPresContext)
    : nsContainerFrame(aStyle, aPresContext, kClassID),
      mRatio(0.0f),
      mDragStart(0),
      mThumbStart(0),
      mCurPos(0),
      mRepeatDirection(0),
      mDragFinished(true),
      mUserChanged(false),
      mScrollingWithAPZ(false),
      mSuppressionActive(false),
      mThumbMinLength(0) {}

// stop timer
nsSliderFrame::~nsSliderFrame() {
  if (mSuppressionActive) {
    if (auto* presShell = PresShell()) {
      presShell->SuppressDisplayport(false);
    }
  }
}

void nsSliderFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
                         nsIFrame* aPrevInFlow) {
  nsContainerFrame::Init(aContent, aParent, aPrevInFlow);

  static bool gotPrefs = false;
  if (!gotPrefs) {
    gotPrefs = true;

    gMiddlePref = Preferences::GetBool("middlemouse.scrollbarPosition");
  }

  mCurPos = GetCurrentPosition(aContent);
}

void nsSliderFrame::RemoveFrame(DestroyContext& aContext, ChildListID aListID,
                                nsIFrame* aOldFrame) {
  nsContainerFrame::RemoveFrame(aContext, aListID, aOldFrame);
  if (mFrames.IsEmpty()) {
    RemoveListener();
  }
}

void nsSliderFrame::InsertFrames(ChildListID aListID, nsIFrame* aPrevFrame,
                                 const nsLineList::iterator* aPrevFrameLine,
                                 nsFrameList&& aFrameList) {
  bool wasEmpty = mFrames.IsEmpty();
  nsContainerFrame::InsertFrames(aListID, aPrevFrame, aPrevFrameLine,
                                 std::move(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();
  nsContainerFrame::AppendFrames(aListID, std::move(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(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 =
      nsContainerFrame::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.

    nsScrollbarFrame* scrollbarBox = Scrollbar();
    nsCOMPtr<nsIContent> scrollbar = scrollbarBox->GetContent();
    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
      nsIScrollbarMediator* mediator = scrollbarBox->GetScrollbarMediator();
      scrollbarBox->SetIncrementToWhole(direction);
      if (mediator) {
        mediator->ScrollByWhole(scrollbarBox, direction,
                                ScrollSnapFlags::IntendedEndPosition);
      }
      // '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, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
  }

  return rv;
}

namespace mozilla {

// Draw any tick marks that show the position of find in page results.
class nsDisplaySliderMarks final : public nsPaintedDisplayItem {
 public:
  nsDisplaySliderMarks(nsDisplayListBuilder* aBuilder, nsSliderFrame* aFrame)
      : nsPaintedDisplayItem(aBuilder, aFrame) {
    MOZ_COUNT_CTOR(nsDisplaySliderMarks);
  }
  MOZ_COUNTED_DTOR_OVERRIDE(nsDisplaySliderMarks)

  NS_DISPLAY_DECL_NAME("SliderMarks", TYPE_SLIDER_MARKS)

  void PaintMarks(nsDisplayListBuilder* aDisplayListBuilder,
                  wr::DisplayListBuilder* aBuilder, gfxContext* aCtx);

  nsRect GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) const override {
    *aSnap = false;
    return mFrame->InkOverflowRectRelativeToSelf() + ToReferenceFrame();
  }

  bool CreateWebRenderCommands(
      wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
      const StackingContextHelper& aSc,
      layers::RenderRootStateManager* aManager,
      nsDisplayListBuilder* aDisplayListBuilder) override;

  void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
};

// This is shared between the webrender and Paint() paths. For the former,
// aBuilder should be assigned and aCtx will be null. For the latter, aBuilder
// should be null and aCtx should be the gfxContext for painting.
void nsDisplaySliderMarks::PaintMarks(nsDisplayListBuilder* aDisplayListBuilder,
                                      wr::DisplayListBuilder* aBuilder,
                                      gfxContext* aCtx) {
  DrawTarget* drawTarget = nullptr;
  if (aCtx) {
    drawTarget = aCtx->GetDrawTarget();
  } else {
    MOZ_ASSERT(aBuilder);
  }

  Document* doc = mFrame->GetContent()->GetUncomposedDoc();
  if (!doc) {
    return;
  }

  nsGlobalWindowInner* window =
      nsGlobalWindowInner::Cast(doc->GetInnerWindow());
  if (!window) {
    return;
  }

  nsSliderFrame* sliderFrame = static_cast<nsSliderFrame*>(mFrame);

  nsIFrame* scrollbarBox = sliderFrame->Scrollbar();
  nsCOMPtr<nsIContent> scrollbar = scrollbarBox->GetContent();

  int32_t minPos = sliderFrame->GetMinPosition(scrollbar);
  int32_t maxPos = sliderFrame->GetMaxPosition(scrollbar);

  // Use the text highlight color for the tick marks.
  nscolor highlightColor =
      LookAndFeel::Color(LookAndFeel::ColorID::TextHighlightBackground, mFrame);
  DeviceColor fillColor = ToDeviceColor(highlightColor);
  fillColor.a = 0.3;  // make the mark mostly transparent

  int32_t appUnitsPerDevPixel =
      sliderFrame->PresContext()->AppUnitsPerDevPixel();
  nsRect sliderRect = sliderFrame->GetRect();

  nsPoint refPoint = aDisplayListBuilder->ToReferenceFrame(mFrame);

  // Increase the height of the tick mark rectangle by one pixel. If the
  // desktop scale is greater than 1, it should be increased more.
  // The tick marks should be drawn ignoring any page zoom that is applied.
  float increasePixels = sliderFrame->PresContext()
                             ->DeviceContext()
                             ->GetDesktopToDeviceScale()
                             .scale;
  const bool isHorizontal = sliderFrame->Scrollbar()->IsHorizontal();
  float increasePixelsX = isHorizontal ? increasePixels : 0;
  float increasePixelsY = isHorizontal ? 0 : increasePixels;
  nsSize initialSize =
      isHorizontal ? nsSize(0, sliderRect.height) : nsSize(sliderRect.width, 0);

  nsTArray<uint32_t>& marks = window->GetScrollMarks();
  for (uint32_t m = 0; m < marks.Length(); m++) {
    uint32_t markValue = marks[m];
    if (markValue > (uint32_t)maxPos) {
      markValue = maxPos;
    }
    if (markValue < (uint32_t)minPos) {
      markValue = minPos;
    }

    // The values in the marks array range up to the window's
    // scrollMax{X,Y} - scrollMin{X,Y} (the same as the slider's maxpos).
    // Scale the values to fit within the slider's width or height.
    nsRect markRect(refPoint, initialSize);
    if (isHorizontal) {
      markRect.x +=
          (nscoord)((double)markValue / (maxPos - minPos) * sliderRect.width);
    } else {
      markRect.y +=
          (nscoord)((double)markValue / (maxPos - minPos) * sliderRect.height);
    }

    if (drawTarget) {
      Rect devPixelRect =
          NSRectToSnappedRect(markRect, appUnitsPerDevPixel, *drawTarget);
      devPixelRect.Inflate(increasePixelsX, increasePixelsY);
      drawTarget->FillRect(devPixelRect, ColorPattern(fillColor));
    } else {
      LayoutDeviceIntRect dRect = LayoutDeviceIntRect::FromAppUnitsToNearest(
          markRect, appUnitsPerDevPixel);
      dRect.Inflate(increasePixelsX, increasePixelsY);
      wr::LayoutRect layoutRect = wr::ToLayoutRect(dRect);
      aBuilder->PushRect(layoutRect, layoutRect, BackfaceIsHidden(), false,
                         false, wr::ToColorF(fillColor));
    }
  }
}

bool nsDisplaySliderMarks::CreateWebRenderCommands(
    wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
    const StackingContextHelper& aSc, layers::RenderRootStateManager* aManager,
    nsDisplayListBuilder* aDisplayListBuilder) {
  PaintMarks(aDisplayListBuilder, &aBuilder, nullptr);
  return true;
}

void nsDisplaySliderMarks::Paint(nsDisplayListBuilder* aBuilder,
                                 gfxContext* aCtx) {
  PaintMarks(aBuilder, nullptr, aCtx);
}

}  // namespace mozilla

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;
  }

  DisplayBorderBackgroundOutline(aBuilder, aLists);

  if (nsIFrame* thumb = mFrames.FirstChild()) {
    BuildDisplayListForThumb(aBuilder, thumb, aLists);
  }

  // If this is an scrollbar for the root frame, draw any markers.
  // Markers are not drawn for other scrollbars.
  // XXX seems like this should be done in nsScrollbarFrame instead perhaps?
  if (!aBuilder->IsForEventDelivery()) {
    nsScrollbarFrame* scrollbar = Scrollbar();
    if (nsIScrollableFrame* scrollFrame =
            do_QueryFrame(scrollbar->GetParent())) {
      if (scrollFrame->IsRootScrollFrameOfDocument()) {
        nsGlobalWindowInner* window = nsGlobalWindowInner::Cast(
            PresContext()->Document()->GetInnerWindow());
        if (window &&
            window->GetScrollMarksOnHScrollbar() == scrollbar->IsHorizontal() &&
            window->GetScrollMarks().Length() > 0) {
          aLists.Content()->AppendNewToTop<nsDisplaySliderMarks>(aBuilder,
                                                                 this);
        }
      }
    }
  }
}

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::BuildDisplayListForThumb(nsDisplayListBuilder* aBuilder,
                                             nsIFrame* aThumb,
                                             const nsDisplayListSet& aLists) {
  nsRect thumbRect(aThumb->GetRect());

  nsRect sliderTrack = GetRect();
  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 BuildDisplayList so that the event
  // region that gets created for the thumb is included in the nsDisplayOwnLayer
  // contents.

  const 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 OuterCSSCoord thumbLength = OuterCSSPixel::FromAppUnits(
        isHorizontal ? thumbRect.width : thumbRect.height);
    const OuterCSSCoord minThumbLength =
        OuterCSSPixel::FromAppUnits(mThumbMinLength);

    nsIFrame* scrollbarBox = Scrollbar();
    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 + scrollbarBox->GetPosition() - scrollPortOrigin;
    const OuterCSSCoord sliderTrackStart = OuterCSSPixel::FromAppUnits(
        isHorizontal ? sliderTrack.x : sliderTrack.y);
    const OuterCSSCoord sliderTrackLength = OuterCSSPixel::FromAppUnits(
        isHorizontal ? sliderTrack.width : sliderTrack.height);
    const OuterCSSCoord thumbStart =
        OuterCSSPixel::FromAppUnits(isHorizontal ? thumbRect.x : thumbRect.y);

    const nsRect overflow = aThumb->InkOverflowRectRelativeToParent();
    nsSize refSize = aBuilder->RootReferenceFrame()->GetSize();
    nsRect dirty = aBuilder->GetVisibleRect().Intersect(thumbRect);
    dirty = nsLayoutUtils::ComputePartialPrerenderArea(
        aThumb, 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);
    BuildDisplayListForChild(aBuilder, aThumb, tempLists);

    // This is a bit of a hack. Collect up all descendant display items
    // and merge them into a single Content() list.
    nsDisplayList masterList(aBuilder);
    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()->AppendNewToTopWithIndex<nsDisplayOwnLayer>(
        aBuilder, this,
        /* aIndex = */ nsDisplayOwnLayer::OwnLayerForScrollThumb, &masterList,
        ownLayerASR, nsDisplayOwnLayerFlags::None,
        ScrollbarData::CreateForThumb(*scrollDirection, GetThumbRatio(),
                                      thumbStart, thumbLength, minThumbLength,
                                      isAsyncDraggable, sliderTrackStart,
                                      sliderTrackLength, scrollTargetId),
        true, false);

    return;
  }

  BuildDisplayListForChild(aBuilder, aThumb, aLists);
}

void nsSliderFrame::Reflow(nsPresContext* aPresContext,
                           ReflowOutput& aDesiredSize,
                           const ReflowInput& aReflowInput,
                           nsReflowStatus& aStatus) {
  MarkInReflow();
  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
  NS_ASSERTION(aReflowInput.AvailableWidth() != NS_UNCONSTRAINEDSIZE,
               "Bogus avail width");
  NS_ASSERTION(aReflowInput.AvailableHeight() != NS_UNCONSTRAINEDSIZE,
               "Bogus avail height");

  const auto wm = GetWritingMode();

  // We always take all the space we're given.
  aDesiredSize.SetSize(wm, aReflowInput.ComputedSize(wm));
  aDesiredSize.SetOverflowAreasToDesiredBounds();

  // Get the thumb, should be our only child.
  nsIFrame* thumbBox = mFrames.FirstChild();
  if (NS_WARN_IF(!thumbBox)) {
    return;
  }

  nsScrollbarFrame* scrollbarBox = Scrollbar();
  nsIContent* scrollbar = scrollbarBox->GetContent();
  const bool horizontal = scrollbarBox->IsHorizontal();
  nsSize availSize = aDesiredSize.PhysicalSize();
  ReflowInput thumbRI(aPresContext, aReflowInput, thumbBox,
                      aReflowInput.AvailableSize(wm));

  // Get the thumb's pref size.
  nsSize thumbSize = thumbRI.ComputedMinSize(wm).GetPhysicalSize(wm);
  if (horizontal) {
    thumbSize.height = availSize.height;
  } else {
    thumbSize.width = availSize.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);

  // If modifying the logic here, be sure to modify the corresponding
  // compositor-side calculation in ScrollThumbUtils::ApplyTransformForAxis().
  nscoord& availableLength = horizontal ? availSize.width : availSize.height;
  nscoord& thumbLength = horizontal ? thumbSize.width : thumbSize.height;
  mThumbMinLength = thumbLength;

  if ((pageIncrement + maxPos - minPos) > 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.
  nsPoint thumbPos;
  if (horizontal) {
    thumbPos.x = NSToCoordRound(pos * mRatio);
  } else {
    thumbPos.y = NSToCoordRound(pos * mRatio);
  }

  // Same to `snappedThumbLocation` in `nsSliderFrame::CurrentPositionChanged`,
  // to avoid putting the scroll thumb at subpixel positions which cause
  // needless invalidations
  nscoord appUnitsPerPixel = PresContext()->AppUnitsPerDevPixel();
  thumbPos =
      ToAppUnits(thumbPos.ToNearestPixels(appUnitsPerPixel), appUnitsPerPixel);

  const LogicalPoint logicalPos(wm, thumbPos, availSize);
  // TODO: It seems like a lot of this stuff should really belong in the thumb's
  // reflow code rather than here, but since we rely on the frame tree structure
  // heavily this matches the previous code more closely for now.
  ReflowOutput thumbDesiredSize(wm);
  const auto flags = ReflowChildFlags::Default;
  nsReflowStatus status;
  thumbRI.SetComputedISize(thumbSize.width);
  thumbRI.SetComputedBSize(thumbSize.height);
  ReflowChild(thumbBox, aPresContext, thumbDesiredSize, thumbRI, wm, logicalPos,
              availSize, flags, status);
  FinishReflowChild(thumbBox, aPresContext, thumbDesiredSize, &thumbRI, wm,
                    logicalPos, availSize, flags);
}

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;
  }

  nsScrollbarFrame* scrollbarBox = Scrollbar();
  nsCOMPtr<nsIContent> scrollbar = scrollbarBox->GetContent();
  bool isHorizontal = scrollbarBox->IsHorizontal();

  if (isDraggingThumb()) {
    switch (aEvent->mMessage) {
      case eTouchMove:
      case eMouseMove: {
        if (mScrollingWithAPZ) {
          break;
        }
        nsPoint eventPoint;
        if (!GetEventPoint(aEvent, eventPoint)) {
          break;
        }
        if (mRepeatDirection) {
          // 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;
        const int32_t snapMultiplier = StaticPrefs::slider_snapMultiplier();
        if (snapMultiplier) {
          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 < -snapMultiplier * thumbSize.height ||
                eventPoint.y >
                    thumbSize.height + snapMultiplier * thumbSize.height) {
              isMouseOutsideThumb = true;
            }
          } else {
            // vertical scrollbar - check if mouse is left or right of thumb
            if (eventPoint.x < -snapMultiplier * thumbSize.width ||
                eventPoint.x >
                    thumbSize.width + snapMultiplier * 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 nsIFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
        }
        break;

      default:
        break;
    }

    // return nsIFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
    return NS_OK;
  }

  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);

    if (aEvent->mClass == eTouchEventClass) {
      *aEventStatus = nsEventStatus_eConsumeNoDefault;
    }

    SetupDrag(aEvent, thumbFrame, pos, isHorizontal);
  }
#ifdef MOZ_WIDGET_GTK
  else if (ShouldScrollForEvent(aEvent) && aEvent->mClass == eMouseEventClass &&
           aEvent->AsMouseEvent()->mButton == MouseButton::eSecondary) {
    // HandlePress and HandleRelease are usually called via
    // nsIFrame::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 && mRepeatDirection) {
    HandleRelease(aPresContext, aEvent, aEventStatus);
  }

  return nsIFrame::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() {
  return LookAndFeel::GetInt(LookAndFeel::IntID::ScrollToClick, false);
}

nsScrollbarFrame* nsSliderFrame::Scrollbar() {
  MOZ_ASSERT(GetParent());
  MOZ_DIAGNOSTIC_ASSERT(
      static_cast<nsScrollbarFrame*>(do_QueryFrame(GetParent())));
  return static_cast<nsScrollbarFrame*>(GetParent());
}

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 = Scrollbar();
  nsCOMPtr<nsIContent> scrollbar = scrollbarBox->GetContent();

  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() {
  nsScrollbarFrame* scrollbarBox = Scrollbar();
  nsCOMPtr<nsIContent> scrollbar = scrollbarBox->GetContent();

  // 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;
  }

  bool reverse = mContent->AsElement()->AttrValueIs(
      kNameSpaceID_None, nsGkAtoms::dir, nsGkAtoms::reverse, eCaseMatters);
  nscoord pos = reverse ? (maxPos - curPos) : (curPos - minPos);
  const bool horizontal = Scrollbar()->IsHorizontal();

  // figure out the new rect
  nsRect thumbRect = thumbFrame->GetRect();
  nsRect newThumbRect(thumbRect);
  if (horizontal) {
    newThumbRect.x = NSToCoordRound(pos * mRatio);
  } else {
    newThumbRect.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 (horizontal) {
    newThumbRect.x = snappedThumbLocation.x;
  } else {
    newThumbRect.y = snappedThumbLocation.y;
  }

  // set the rect
  // XXX This out-of-band update of the frame tree is rather fishy!
  thumbFrame->SetRect(newThumbRect);

  // When the thumb changes position, the mThumbStart value stored in
  // ScrollbarData for the purpose of telling APZ about the thumb
  // position painted by the main thread is invalidated. The ScrollbarData
  // is stored on the nsDisplayOwnLayer item built by *this* frame, so
  // we need to mark this frame as needing its fisplay item rebuilt.
  MarkNeedsDisplayItemRebuild();

  // Request a repaint of the scrollbar
  nsIScrollbarMediator* mediator = scrollbarBox->GetScrollbarMediator();
  if (!mediator || !mediator->ShouldSuppressScrollbarRepaints()) {
    SchedulePaint();
  }

  mCurPos = curPos;
}

static void UpdateAttribute(dom::Element* aScrollbar, nscoord aNewPos,
                            bool aNotify, bool aIsSmooth) {
  nsAutoString str;
  str.AppendInt(aNewPos);

  if (aIsSmooth) {
    aScrollbar->SetAttr(kNameSpaceID_None, nsGkAtoms::smooth, u"true"_ns,
                        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) {
  int32_t newPos = NSToIntRound(aNewThumbPos / 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;
  nsScrollbarFrame* scrollbarBox = Scrollbar();
  AutoWeakFrame weakFrame(this);

  mUserChanged = true;

  // See if we have a mediator.
  if (nsIScrollbarMediator* mediator = scrollbarBox->GetScrollbarMediator()) {
    nscoord oldPos =
        nsPresContext::CSSPixelsToAppUnits(GetCurrentPosition(scrollbar));
    nscoord newPos = nsPresContext::CSSPixelsToAppUnits(aNewPos);
    mediator->ThumbMoved(scrollbarBox, 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) {
  nsContainerFrame::SetInitialChildList(aListID, std::move(aChildList));
  if (aListID == FrameChildListID::Principal) {
    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;
}

static bool ScrollFrameWillBuildScrollInfoLayer(nsIFrame* aScrollFrame) {
  /*
   * Note: if changing the conditions in this function, make a corresponding
   * change to nsDisplayListBuilder::ShouldBuildScrollInfoItemsForHoisting()
   * in nsDisplayList.cpp.
   */
  nsIFrame* current = aScrollFrame;
  while (current) {
    if (SVGIntegrationUtils::UsesSVGEffectsNotSupportedInCompositor(current)) {
      return true;
    }
    current = nsLayoutUtils::GetParentOrPlaceholderForCrossDoc(current);
  }
  return false;
}

nsIScrollableFrame* nsSliderFrame::GetScrollFrame() {
  return do_QueryFrame(Scrollbar()->GetParent());
}

void nsSliderFrame::StartAPZDrag(WidgetGUIEvent* aEvent) {
  if (!aEvent->mFlags.mHandledByAPZ) {
    return;
  }

  if (!gfxPlatform::GetPlatform()->SupportsApzDragInput()) {
    return;
  }

  if (aEvent->AsMouseEvent() &&
      aEvent->AsMouseEvent()->mButton != MouseButton::ePrimary) {
    return;
  }

  nsIFrame* scrollbarBox = Scrollbar();
  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 = Scrollbar()->IsHorizontal();

  layers::ScrollableLayerGuid::ViewID scrollTargetId;
  bool hasID = nsLayoutUtils::FindIDFor(scrollableContent, &scrollTargetId);
  bool hasAPZView =
      hasID && scrollTargetId != layers::ScrollableLayerGuid::NULL_SCROLL_ID;

  if (!hasAPZView) {
    return;
  }

  if (!DisplayPortUtils::HasNonMinimalDisplayPort(scrollableContent)) {
    return;
  }

  auto* presShell = PresShell();
  uint64_t inputblockId = InputAPZContext::GetInputBlockId();
  uint32_t presShellId = presShell->GetPresShellId();
  AsyncDragMetrics dragMetrics(
      scrollTargetId, presShellId, inputblockId,
      OuterCSSPixel::FromAppUnits(mDragStart),
      isHorizontal ? ScrollDirection::eHorizontal : ScrollDirection::eVertical);

  // It's important to set this before calling
  // nsIWidget::StartAsyncScrollbarDrag(), because in some configurations, that
  // can call AsyncScrollbarDragRejected() synchronously, which clears the flag
  // (and we want it to stay cleared in that case).
  mScrollingWithAPZ = true;

  // When we start an APZ drag, we wont get mouse events for the drag.
  // APZ will consume them all and only notify us of the new scroll position.
  bool waitForRefresh = InputAPZContext::HavePendingLayerization();
  nsIWidget* widget = this->GetNearestWidget();
  if (waitForRefresh) {
    waitForRefresh = false;
    if (nsPresContext* presContext = presShell->GetPresContext()) {
      presContext->RegisterManagedPostRefreshObserver(
          new ManagedPostRefreshObserver(
              presContext, [widget = RefPtr<nsIWidget>(widget),
                            dragMetrics](bool aWasCanceled) {
                if (!aWasCanceled) {
                  widget->StartAsyncScrollbarDrag(dragMetrics);
                }
                return ManagedPostRefreshObserver::Unregister::Yes;
              }));
      waitForRefresh = true;
    }
  }
  if (!waitForRefresh) {
    widget->StartAsyncScrollbarDrag(dragMetrics);
  }
}

nsresult nsSliderFrame::StartDrag(Event* aEvent) {
#ifdef DEBUG_SLIDER
  printf("Begin dragging\n");
#endif
  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
                                         nsGkAtoms::_true, eCaseMatters))
    return NS_OK;

  WidgetGUIEvent* event = aEvent->WidgetEventPtr()->AsGUIEvent();

  if (!ShouldScrollForEvent(event)) {
    return NS_OK;
  }

  nsPoint pt;
  if (!GetEventPoint(event, pt)) {
    return NS_OK;
  }
  bool isHorizontal = Scrollbar()->IsHorizontal();
  nscoord pos = isHorizontal ? pt.x : pt.y;

  // If we should scroll-to-click, first place the middle of the slider thumb
  // under the mouse.
  nsCOMPtr<nsIContent> scrollbar;
  nscoord newpos = pos;
  bool scrollToClick = ShouldScrollToClickForEvent(event);
  if (scrollToClick) {
    // 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;

    newpos -= (thumbLength / 2);

    scrollbar = Scrollbar()->GetContent();
  }

  DragThumb(true);

  if (scrollToClick) {
    // should aMaySnap be true here?
    SetCurrentThumbPosition(scrollbar, newpos, false, false);
  }

  nsIFrame* thumbFrame = mFrames.FirstChild();
  if (!thumbFrame) {
    return NS_OK;
  }

  SetupDrag(event, thumbFrame, pos, isHorizontal);

  return NS_OK;
}

nsresult nsSliderFrame::StopDrag() {
  AddListener();
  DragThumb(false);

  mScrollingWithAPZ = false;

  UnsuppressDisplayport();

  if (mRepeatDirection) {
    StopRepeat();
    mRepeatDirection = 0;
  }
  return NS_OK;
}

void nsSliderFrame::DragThumb(bool aGrabMouseEvents) {
  mDragFinished = !aGrabMouseEvents;

  if (aGrabMouseEvents) {
    PresShell::SetCapturingContent(
        GetContent(),
        CaptureFlags::IgnoreAllowedState | CaptureFlags::PreventDragStart);
  } else {
    PresShell::ReleaseCapturingContent();
  }
}

bool nsSliderFrame::isDraggingThumb() const {
  return PresShell::GetCapturingContent() == GetContent();
}

void nsSliderFrame::AddListener() {
  if (!mMediator) {
    mMediator = new nsSliderMediator(this);
  }

  nsIFrame* thumbFrame = mFrames.FirstChild();
  if (!thumbFrame) {
    return;
  }
  thumbFrame->GetContent()->AddSystemEventListener(u"mousedown"_ns, mMediator,
                                                   false, false);
  thumbFrame->GetContent()->AddSystemEventListener(u"touchstart"_ns, mMediator,
                                                   false, false);
}

void nsSliderFrame::RemoveListener() {
  NS_ASSERTION(mMediator, "No listener was ever added!!");

  nsIFrame* thumbFrame = mFrames.FirstChild();
  if (!thumbFrame) return;

  thumbFrame->GetContent()->RemoveSystemEventListener(u"mousedown"_ns,
                                                      mMediator, false);
  thumbFrame->GetContent()->RemoveSystemEventListener(u"touchstart"_ns,
                                                      mMediator, false);
}

bool nsSliderFrame::ShouldScrollForEvent(WidgetGUIEvent* aEvent) {
  switch (aEvent->mMessage) {
    case eTouchStart:
    case eTouchEnd:
      return true;
    case eMouseDown:
    case eMouseUp: {
      uint16_t button = aEvent->AsMouseEvent()->mButton;
#ifdef MOZ_WIDGET_GTK
      return (button == MouseButton::ePrimary) ||
             (button == MouseButton::eSecondary && GetScrollToClick()) ||
             (button == MouseButton::eMiddle && gMiddlePref &&
              !GetScrollToClick());
#else
      return (button == MouseButton::ePrimary) ||
             (button == MouseButton::eMiddle && gMiddlePref);
#endif
    }
    default:
      return false;
  }
}

bool nsSliderFrame::ShouldScrollToClickForEvent(WidgetGUIEvent* aEvent) {
  if (!ShouldScrollForEvent(aEvent)) {
    return false;
  }

  if (aEvent->mMessage != eMouseDown && aEvent->mMessage != eTouchStart) {
    return false;
  }

#if defined(XP_MACOSX) || defined(MOZ_WIDGET_GTK)
  // On Mac and Linux, clicking the scrollbar thumb should never scroll to
  // click.
  if (IsEventOverThumb(aEvent)) {
    return false;
  }
#endif

  if (aEvent->mMessage == eTouchStart) {
    return GetScrollToClick();
  }

  WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
  if (mouseEvent->mButton == MouseButton::ePrimary) {
#ifdef XP_MACOSX
    bool invertPref = mouseEvent->IsAlt();
#else
    bool invertPref = mouseEvent->IsShift();
#endif
    return GetScrollToClick() != invertPref;
  }

#ifdef MOZ_WIDGET_GTK
  if (mouseEvent->mButton == MouseButton::eSecondary) {
    return !GetScrollToClick();
  }
#endif

  return true;
}

bool nsSliderFrame::IsEventOverThumb(WidgetGUIEvent* aEvent) {
  nsIFrame* thumbFrame = mFrames.FirstChild();
  if (!thumbFrame) {
    return false;
  }

  nsPoint eventPoint;
  if (!GetEventPoint(aEvent, eventPoint)) {
    return false;
  }

  const nsRect thumbRect = thumbFrame->GetRect();
  const bool isHorizontal = Scrollbar()->IsHorizontal();
  nscoord eventPos = isHorizontal ? eventPoint.x : eventPoint.y;
  nscoord thumbStart = isHorizontal ? thumbRect.x : thumbRect.y;
  nscoord thumbEnd = isHorizontal ? thumbRect.XMost() : thumbRect.YMost();
  return eventPos >= thumbStart && eventPos < thumbEnd;
}

NS_IMETHODIMP
nsSliderFrame::HandlePress(nsPresContext* aPresContext, WidgetGUIEvent* aEvent,
                           nsEventStatus* aEventStatus) {
  if (!ShouldScrollForEvent(aEvent) || ShouldScrollToClickForEvent(aEvent)) {
    return NS_OK;
  }

  if (IsEventOverThumb(aEvent)) {
    return NS_OK;
  }

  nsIFrame* thumbFrame = mFrames.FirstChild();
  if (!thumbFrame)  // display:none?
    return NS_OK;

  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
                                         nsGkAtoms::_true, eCaseMatters))
    return NS_OK;

  nsRect thumbRect = thumbFrame->GetRect();

  nscoord change = 1;
  nsPoint eventPoint;
  if (!GetEventPoint(aEvent, eventPoint)) {
    return NS_OK;
  }

  if (Scrollbar()->IsHorizontal() ? eventPoint.x < thumbRect.x
                                  : eventPoint.y < thumbRect.y) {
    change = -1;
  }

  mRepeatDirection = change;
  DragThumb(true);
  if (StaticPrefs::layout_scrollbars_click_and_hold_track_continue_to_end()) {
    // Set the destination point to the very end of the scrollbar so that
    // scrolling doesn't stop halfway through.
    if (change > 0) {
      mDestinationPoint = nsPoint(GetRect().width, GetRect().height);
    } else {
      mDestinationPoint = nsPoint(0, 0);
    }
  } else {
    mDestinationPoint = eventPoint;
  }
  StartRepeat();
  PageScroll(false);

  return NS_OK;
}

NS_IMETHODIMP
nsSliderFrame::HandleRelease(nsPresContext* aPresContext,
                             WidgetGUIEvent* aEvent,
                             nsEventStatus* aEventStatus) {
  StopRepeat();

  nsScrollbarFrame* sb = Scrollbar();
  if (nsIScrollbarMediator* m = sb->GetScrollbarMediator()) {
    m->ScrollbarReleased(sb);
  }
  return NS_OK;
}

void nsSliderFrame::Destroy(DestroyContext& aContext) {
  // tell our mediator if we have one we are gone.
  if (mMediator) {
    mMediator->SetSlider(nullptr);
    mMediator = nullptr;
  }
  StopRepeat();

  // call base class Destroy()
  nsContainerFrame::Destroy(aContext);
}

void nsSliderFrame::Notify() {
  bool stop = false;

  nsIFrame* thumbFrame = mFrames.FirstChild();
  if (!thumbFrame) {
    StopRepeat();
    return;
  }
  nsRect thumbRect = thumbFrame->GetRect();

  const bool isHorizontal = Scrollbar()->IsHorizontal();

  // See if the thumb has moved past our destination point.
  // if it has we want to stop.
  if (isHorizontal) {
    if (mRepeatDirection < 0) {
      if (thumbRect.x < mDestinationPoint.x) stop = true;
    } else {
      if (thumbRect.x + thumbRect.width > mDestinationPoint.x) stop = true;
    }
  } else {
    if (mRepeatDirection < 0) {
      if (thumbRect.y < mDestinationPoint.y) stop = true;
    } else {
      if (thumbRect.y + thumbRect.height > mDestinationPoint.y) stop = true;
    }
  }

  if (stop) {
    StopRepeat();
  } else {
    PageScroll(true);
  }
}

void nsSliderFrame::PageScroll(bool aClickAndHold) {
  int32_t changeDirection = mRepeatDirection;
  if (mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::dir,
                                         nsGkAtoms::reverse, eCaseMatters)) {
    changeDirection = -changeDirection;
  }
  nsScrollbarFrame* sb = Scrollbar();

  nsIScrollableFrame* sf = GetScrollFrame();
  const ScrollSnapFlags scrollSnapFlags =
      ScrollSnapFlags::IntendedDirection | ScrollSnapFlags::IntendedEndPosition;

  // If our nsIScrollbarMediator implementation is an nsIScrollableFrame,
  // use ScrollTo() to ensure we do not scroll past the intended
  // destination. Otherwise, the combination of smooth scrolling and
  // ScrollBy() semantics (which adds the delta to the current destination
  // if there is a smooth scroll in progress) can lead to scrolling too far
  // (bug 1331390).
  // Only do this when the page scroll is triggered by the repeat timer
  // when the mouse is being held down. For multiple clicks in
  // succession, we want to make sure we scroll by a full page for
  // each click, so we use ScrollByPage().
  if (aClickAndHold && sf) {
    const bool isHorizontal = sb->IsHorizontal();

    nsIFrame* thumbFrame = mFrames.FirstChild();
    if (!thumbFrame) {
      return;
    }

    nsRect thumbRect = thumbFrame->GetRect();

    nscoord maxDistanceAlongTrack;
    if (isHorizontal) {
      maxDistanceAlongTrack =
          mDestinationPoint.x - thumbRect.x - thumbRect.width / 2;
    } else {
      maxDistanceAlongTrack =
          mDestinationPoint.y - thumbRect.y - thumbRect.height / 2;
    }

    // Convert distance along scrollbar track to amount of scrolled content.
    nscoord maxDistanceToScroll = maxDistanceAlongTrack / GetThumbRatio();

    nsIContent* content = sb->GetContent();
    const CSSIntCoord pageLength = GetPageIncrement(content);

    nsPoint pos = sf->GetScrollPosition();

    if (mCurrentClickHoldDestination) {
      // We may not have arrived at the destination of the scroll from the
      // previous repeat timer tick, some of that scroll may still be pending.
      nsPoint pendingScroll =
          *mCurrentClickHoldDestination - sf->GetScrollPosition();

      // Scroll by one page relative to the previous destination, so that we
      // scroll at a rate of a full page per repeat timer tick.
      pos += pendingScroll;

      // Make a corresponding adjustment to the maxium distance we can scroll,
      // so we successfully avoid overshoot.
      maxDistanceToScroll -= (isHorizontal ? pendingScroll.x : pendingScroll.y);
    }

    nscoord distanceToScroll =
        std::min(abs(maxDistanceToScroll),
                 CSSPixel::ToAppUnits(CSSCoord(pageLength))) *
        changeDirection;

    if (isHorizontal) {
      pos.x += distanceToScroll;
    } else {
      pos.y += distanceToScroll;
    }

    mCurrentClickHoldDestination = Some(pos);
    sf->ScrollTo(pos,
                 StaticPrefs::general_smoothScroll() &&
                         StaticPrefs::general_smoothScroll_pages()
                     ? ScrollMode::Smooth
                     : ScrollMode::Instant,
                 nullptr, scrollSnapFlags);

    return;
  }

  sb->SetIncrementToPage(changeDirection);
  if (nsIScrollbarMediator* m = sb->GetScrollbarMediator()) {
    m->ScrollByPage(sb, changeDirection, scrollSnapFlags);
    return;
  }
  PageUpDown(changeDirection);
}

void nsSliderFrame::SetupDrag(WidgetGUIEvent* aEvent, nsIFrame* aThumbFrame,
                              nscoord aPos, bool aIsHorizontal) {
  if (aIsHorizontal) {
    mThumbStart = aThumbFrame->GetPosition().x;
  } else {
    mThumbStart = aThumbFrame->GetPosition().y;
  }

  mDragStart = aPos - mThumbStart;

  mScrollingWithAPZ = false;
  StartAPZDrag(aEvent);  // sets mScrollingWithAPZ=true if appropriate

#ifdef DEBUG_SLIDER
  printf("Pressed mDragStart=%d\n", mDragStart);
#endif

  if (!mScrollingWithAPZ) {
    SuppressDisplayport();
  }
}

float nsSliderFrame::GetThumbRatio() const {
  // mRatio is in thumb app units per scrolled css pixels. Convert it to a
  // ratio of the thumb's CSS pixels per scrolled CSS pixels. (Note the thumb
  // is in the scrollframe's parent's space whereas the scrolled CSS pixels
  // are in the scrollframe's space).
  return mRatio / AppUnitsPerCSSPixel();
}

void nsSliderFrame::AsyncScrollbarDragInitiated(uint64_t aDragBlockId) {
  mAPZDragInitiated = Some(aDragBlockId);
}

void nsSliderFrame::AsyncScrollbarDragRejected() {
  mScrollingWithAPZ = false;
  // Only suppress the displayport if we're still dragging the thumb.
  // Otherwise, no one will unsuppress it.
  if (isDraggingThumb()) {
    SuppressDisplayport();
  }
}

void nsSliderFrame::SuppressDisplayport() {
  if (!mSuppressionActive) {
    PresShell()->SuppressDisplayport(true);
    mSuppressionActive = true;
  }
}

void nsSliderFrame::UnsuppressDisplayport() {
  if (mSuppressionActive) {
    PresShell()->SuppressDisplayport(false);
    mSuppressionActive = false;
  }
}

bool nsSliderFrame::OnlySystemGroupDispatch(EventMessage aMessage) const {
  // If we are in a native anonymous subtree, do not dispatch mouse-move or
  // pointer-move events targeted at this slider frame to web content. This
  // matches the behaviour of other browsers.
  return (aMessage == eMouseMove || aMessage == ePointerMove) &&
         isDraggingThumb() && GetContent()->IsInNativeAnonymousSubtree();
}

bool nsSliderFrame::GetEventPoint(WidgetGUIEvent* aEvent, nsPoint& aPoint) {
  LayoutDeviceIntPoint refPoint;
  if (!GetEventPoint(aEvent, refPoint)) {
    return false;
  }
  aPoint = nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, refPoint,
                                                        RelativeTo{this});
  return true;
}

bool nsSliderFrame::GetEventPoint(WidgetGUIEvent* aEvent,
                                  LayoutDeviceIntPoint& aPoint) {
  NS_ENSURE_TRUE(aEvent, false);
  WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent();
  if (touchEvent) {
    // return false if there is more than one touch on the page, or if
    // we can't find a touch point
    if (touchEvent->mTouches.Length() != 1) {
      return false;
    }

    dom::Touch* touch = touchEvent->mTouches.SafeElementAt(0);
    if (!touch) {
      return false;
    }
    aPoint = touch->mRefPoint;
  } else {
    aPoint = aEvent->mRefPoint;
  }
  return true;
}

NS_IMPL_ISUPPORTS(nsSliderMediator, nsIDOMEventListener)