File: RenderListBox.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (1233 lines) | stat: -rw-r--r-- 43,703 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (C) 2006-2024 Apple Inc. All rights reserved.
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *               2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer. 
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution. 
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "RenderListBox.h"

#include "AXObjectCache.h"
#include "CSSFontSelector.h"
#include "DocumentInlines.h"
#include "EventHandler.h"
#include "FocusController.h"
#include "FrameSelection.h"
#include "GraphicsContext.h"
#include "HTMLNames.h"
#include "HTMLOptionElement.h"
#include "HTMLOptGroupElement.h"
#include "HTMLSelectElement.h"
#include "HitTestResult.h"
#include "LocalFrame.h"
#include "LocalFrameView.h"
#include "NodeRenderStyle.h"
#include "Page.h"
#include "PaintInfo.h"
#include "RenderBoxInlines.h"
#include "RenderBoxModelObjectInlines.h"
#include "RenderElementInlines.h"
#include "RenderLayer.h"
#include "RenderLayerScrollableArea.h"
#include "RenderLayoutState.h"
#include "RenderScrollbar.h"
#include "RenderText.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "ScrollAnimator.h"
#include "Scrollbar.h"
#include "ScrollbarTheme.h"
#include "Settings.h"
#include "SpatialNavigation.h"
#include "StyleResolver.h"
#include "StyleTreeResolver.h"
#include "UnicodeBidi.h"
#include "WheelEventTestMonitor.h"
#include <math.h>
#include <wtf/StackStats.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/MakeString.h>

namespace WebCore {

using namespace HTMLNames;

WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(RenderListBox);
 
const int itemBlockSpacing = 1;

const int optionsSpacingInlineStart = 2;

// Default size when the multiple attribute is present but size attribute is absent.
const int defaultSize = 4;

// FIXME: This hardcoded baselineAdjustment is what we used to do for the old
// widget, but I'm not sure this is right for the new control.
const int baselineAdjustment = 7;

RenderListBox::RenderListBox(HTMLSelectElement& element, RenderStyle&& style)
    : RenderBlockFlow(Type::ListBox, element, WTFMove(style))
{
    view().frameView().addScrollableArea(this);
}

// Do not add any code in below destructor. Add it to willBeDestroyed() instead.
RenderListBox::~RenderListBox() = default;

void RenderListBox::willBeDestroyed()
{
    destroyScrollbar();
    view().frameView().removeScrollableArea(this);
    RenderBlockFlow::willBeDestroyed();
}

HTMLSelectElement& RenderListBox::selectElement() const
{
    return downcast<HTMLSelectElement>(nodeForNonAnonymous());
}

static FontCascade bolder(Document& document, const FontCascade& font)
{
    auto description = font.fontDescription();
    description.setWeight(description.bolderWeight());
    FontCascade result(WTFMove(description), font);
    result.update(&document.fontSelector());
    return result;
}

void RenderListBox::updateFromElement()
{
    if (m_optionsChanged) {
        float logicalWidth = 0;
        auto& normalFont = style().fontCascade();
        std::optional<FontCascade> boldFont;
        for (auto& element : selectElement().listItems()) {
            String text;
            Function<const FontCascade&()> selectFont = [&normalFont] () -> const FontCascade& {
                return normalFont;
            };
            if (RefPtr optionElement = dynamicDowncast<HTMLOptionElement>(element.get()))
                text = optionElement->textIndentedToRespectGroupLabel();
            else if (RefPtr optGroupElement = dynamicDowncast<HTMLOptGroupElement>(element.get())) {
                text = optGroupElement->groupLabelText();
                selectFont = [this, &normalFont, &boldFont] () -> const FontCascade& {
                    if (!boldFont)
                        boldFont = bolder(document(), normalFont);
                    return boldFont.value();
                };
            }
            if (text.isEmpty())
                continue;
            text = applyTextTransform(style(), text);
            auto textRun = constructTextRun(text, style(), ExpansionBehavior::allowRightOnly());
            logicalWidth = std::max(logicalWidth, selectFont().width(textRun));
        }
        // FIXME: Is ceiling right here, or should we be doing some kind of rounding instead?
        m_optionsLogicalWidth = static_cast<int>(std::ceil(logicalWidth));
        m_optionsChanged = false;

        setHasScrollbar(scrollbarOrientationForWritingMode());

        computeFirstIndexesVisibleInPaddingBeforeAfterAreas();

        setNeedsLayoutAndPrefWidthsRecalc();
    }
}

void RenderListBox::selectionChanged()
{
    repaint();
    if (!m_inAutoscroll) {
        if (m_optionsChanged || needsLayout())
            m_scrollToRevealSelectionAfterLayout = true;
        else
            scrollToRevealSelection();
    }
    
    if (AXObjectCache* cache = document().existingAXObjectCache())
        cache->deferSelectedChildrenChangedIfNeeded(selectElement());
}

void RenderListBox::layout()
{
    StackStats::LayoutCheckPoint layoutCheckPoint;
    RenderBlockFlow::layout();

    if (m_scrollbar) {
        bool enabled = numVisibleItems() < numItems();
        m_scrollbar->setEnabled(enabled);
        m_scrollbar->setSteps(1, std::max(1, numVisibleItems() - 1), itemLogicalHeight());
        m_scrollbar->setProportion(numVisibleItems(), numItems());
        if (!enabled) {
            scrollToOffsetWithoutAnimation(m_scrollbar->orientation(), 0);
            m_scrollPosition = { };
        }

        if (writingMode().isBlockFlipped()) {
            auto scrollOrigin = IntPoint(0, numItems() - numVisibleItems());
            if (m_scrollbar->orientation() == ScrollbarOrientation::Horizontal)
                scrollOrigin = scrollOrigin.transposedPoint();
            setScrollOrigin(scrollOrigin);
            m_scrollbar->offsetDidChange();
        } else
            setScrollOrigin(IntPoint());
    }

    if (m_scrollToRevealSelectionAfterLayout) {
        LayoutStateDisabler layoutStateDisabler(view().frameView().layoutContext());
        scrollToRevealSelection();
    }
}

void RenderListBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
    RenderBlockFlow::styleDidChange(diff, oldStyle);

    if (oldStyle && oldStyle->writingMode() != style().writingMode()) {
        if (m_scrollbar)
            setHasScrollbar(scrollbarOrientationForWritingMode());
    }
}

void RenderListBox::scrollToRevealSelection()
{    
    m_scrollToRevealSelectionAfterLayout = false;

    int firstIndex = selectElement().activeSelectionStartListIndex();
    if (firstIndex >= 0 && !listIndexIsVisible(selectElement().activeSelectionEndListIndex()))
        scrollToRevealElementAtListIndex(firstIndex);
}

void RenderListBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
    if (shouldApplySizeOrInlineSizeContainment()) {
        if (auto logicalWidth = explicitIntrinsicInnerLogicalWidth())
            maxLogicalWidth = logicalWidth.value();
        else
            maxLogicalWidth = 2 * optionsSpacingInlineStart;
    } else
        maxLogicalWidth = 2 * optionsSpacingInlineStart + m_optionsLogicalWidth;

    if (m_scrollbar)
        maxLogicalWidth += m_scrollbar->orientation() == ScrollbarOrientation::Vertical ? m_scrollbar->width() : m_scrollbar->height();

    auto& logicalWidth = style().logicalWidth();
    if (logicalWidth.isCalculated())
        minLogicalWidth = std::max(0_lu, valueForLength(logicalWidth, 0_lu));
    else if (!logicalWidth.isPercent())
        minLogicalWidth = maxLogicalWidth;
}

void RenderListBox::computePreferredLogicalWidths()
{
    // Nested style recal do not fire post recal callbacks. see webkit.org/b/153767
    ASSERT(!m_optionsChanged || Style::postResolutionCallbacksAreSuspended());

    m_minPreferredLogicalWidth = 0;
    m_maxPreferredLogicalWidth = 0;

    if (style().logicalWidth().isFixed() && style().logicalWidth().value() > 0)
        m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(style().logicalWidth());
    else
        computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);

    RenderBox::computePreferredLogicalWidths(style().logicalMinWidth(), style().logicalMaxWidth(), writingMode().isHorizontal() ? horizontalBorderAndPaddingExtent() : verticalBorderAndPaddingExtent());

    setPreferredLogicalWidthsDirty(false);
}

unsigned RenderListBox::size() const
{
    if (style().fieldSizing() == FieldSizing::Content)
        return static_cast<unsigned>(numItems());

    unsigned specifiedSize = selectElement().size();
    if (specifiedSize >= 1)
        return specifiedSize;

    return defaultSize;
}

int RenderListBox::numVisibleItems(ConsiderPadding considerPadding) const
{
    // Only count fully visible rows. But don't return 0 even if only part of a row shows.
    int visibleItemsExcludingPadding = std::max<int>(1, (contentBoxLogicalHeight() + itemBlockSpacing) / itemLogicalHeight());
    if (considerPadding == ConsiderPadding::No)
        return visibleItemsExcludingPadding;

    return numberOfVisibleItemsInPaddingBefore() + visibleItemsExcludingPadding + numberOfVisibleItemsInPaddingAfter();
}

int RenderListBox::numItems() const
{
    return selectElement().listItems().size();
}

LayoutUnit RenderListBox::listLogicalHeight() const
{
    return itemLogicalHeight() * numItems() - itemBlockSpacing;
}

RenderBox::LogicalExtentComputedValues RenderListBox::computeLogicalHeight(LayoutUnit, LayoutUnit logicalTop) const
{
    LayoutUnit logicalHeight = itemLogicalHeight() * size() - itemBlockSpacing;

    if (shouldApplySizeContainment()) {
        if (auto explicitIntrinsicHeight = explicitIntrinsicInnerLogicalHeight())
            logicalHeight = explicitIntrinsicHeight.value();
    }

    cacheIntrinsicContentLogicalHeightForFlexItem(logicalHeight);
    logicalHeight += writingMode().isHorizontal() ? verticalBorderAndPaddingExtent() : horizontalBorderAndPaddingExtent();
    return RenderBox::computeLogicalHeight(logicalHeight, logicalTop);
}

LayoutUnit RenderListBox::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode lineDirection, LinePositionMode linePositionMode) const
{
    auto baseline = RenderBox::baselinePosition(baselineType, firstLine, lineDirection, linePositionMode);
    if (!shouldApplyLayoutContainment())
        baseline -= baselineAdjustment;
    return baseline;
}

LayoutRect RenderListBox::itemBoundingBoxRect(const LayoutPoint& additionalOffset, int index) const
{
    LayoutUnit x = additionalOffset.x() + borderLeft() + paddingLeft();
    LayoutUnit y = additionalOffset.y() + borderTop() + paddingTop();

    if (auto* vBar = verticalScrollbar(); vBar && shouldPlaceVerticalScrollbarOnLeft())
        x += vBar->occupiedWidth();

    auto itemOffset = itemLogicalHeight() * (index - indexOffset());
    if (writingMode().isBlockFlipped())
        itemOffset = contentBoxLogicalHeight() - itemLogicalHeight() - itemOffset;

    if (writingMode().isVertical())
        return LayoutRect(x + itemOffset, y, itemLogicalHeight(), contentBoxHeight());

    return LayoutRect(x, y + itemOffset, contentBoxWidth(), itemLogicalHeight());
}

std::optional<int> RenderListBox::optionRowIndex(const HTMLOptionElement& optionElement) const
{
    // We can't use optionElement.index(), because it doesn't account for optgroup items.
    int rowIndex = 0;
    for (auto& item : selectElement().listItems()) {
        if (item == &optionElement)
            return rowIndex;

        ++rowIndex;
    }

    return { };
}

std::optional<LayoutRect> RenderListBox::localBoundsOfOption(const HTMLOptionElement& optionElement) const
{
    auto rowIndex = optionRowIndex(optionElement);
    if (!rowIndex)
        return { };

    return itemBoundingBoxRect({ }, *rowIndex);
}

std::optional<LayoutRect> RenderListBox::localBoundsOfOptGroup(const HTMLOptGroupElement& optGroupElement) const
{
    if (optGroupElement.ownerSelectElement() != &selectElement())
        return { };

    std::optional<LayoutRect> boundingBox;
    int rowIndex = 0;

    for (auto& item : selectElement().listItems()) {
        if (is<HTMLOptGroupElement>(*item)) {
            if (item == &optGroupElement)
                boundingBox = itemBoundingBoxRect({ }, rowIndex);
        } else if (is<HTMLOptionElement>(*item)) {
            if (item->parentNode() != &optGroupElement)
                break;

            boundingBox->setHeight(boundingBox->height() + itemBoundingBoxRect({ }, rowIndex).height());
        }
        ++rowIndex;
    }

    return boundingBox;
}

void RenderListBox::paintItem(PaintInfo& paintInfo, const LayoutPoint& paintOffset, const PaintFunction& paintFunction)
{
    int listItemsSize = numItems();
    int firstVisibleItem = m_indexOfFirstVisibleItemInsidePaddingBeforeArea.value_or(indexOffset());
    int endIndex = firstVisibleItem + numVisibleItems(ConsiderPadding::Yes);
    for (int i = firstVisibleItem; i < listItemsSize && i < endIndex; ++i)
        paintFunction(paintInfo, paintOffset, i);
}

void RenderListBox::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
    if (style().usedVisibility() != Visibility::Visible)
        return;
    
    if (paintInfo.phase == PaintPhase::Foreground) {
        paintItem(paintInfo, paintOffset, [this](PaintInfo& paintInfo, const LayoutPoint& paintOffset, int listItemIndex) {
            paintItemForeground(paintInfo, paintOffset, listItemIndex);
        });
    }

    // Paint the children.
    RenderBlockFlow::paintObject(paintInfo, paintOffset);

    switch (paintInfo.phase) {
    // Depending on whether we have overlay scrollbars they
    // get rendered in the foreground or background phases
    case PaintPhase::Foreground:
        if (m_scrollbar->isOverlayScrollbar())
            paintScrollbar(paintInfo, paintOffset, *m_scrollbar);
        break;
    case PaintPhase::BlockBackground:
        if (!m_scrollbar->isOverlayScrollbar())
            paintScrollbar(paintInfo, paintOffset, *m_scrollbar);
        break;
    case PaintPhase::ChildBlockBackground:
    case PaintPhase::ChildBlockBackgrounds: {
        paintItem(paintInfo, paintOffset, [this](PaintInfo& paintInfo, const LayoutPoint& paintOffset, int listItemIndex) {
            paintItemBackground(paintInfo, paintOffset, listItemIndex);
        });
        break;
    }
    default:
        break;
    }
}

void RenderListBox::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer) const
{
    if (!selectElement().allowsNonContiguousSelection())
        return RenderBlockFlow::addFocusRingRects(rects, additionalOffset, paintContainer);

    // Focus the last selected item.
    int selectedItem = selectElement().activeSelectionEndListIndex();
    if (selectedItem >= 0) {
        rects.append(snappedIntRect(itemBoundingBoxRect(additionalOffset, selectedItem)));
        return;
    }

    // No selected items, find the first non-disabled item.
    int indexOfFirstEnabledOption = 0;
    for (auto& item : selectElement().listItems()) {
        if (is<HTMLOptionElement>(item.get()) && !item->isDisabledFormControl()) {
            selectElement().setActiveSelectionEndIndex(indexOfFirstEnabledOption);
            rects.append(itemBoundingBoxRect(additionalOffset, indexOfFirstEnabledOption));
            return;
        }
        indexOfFirstEnabledOption++;
    }
}

bool RenderListBox::useDarkAppearance() const
{
    return RenderBlockFlow::useDarkAppearance();
}

void RenderListBox::paintScrollbar(PaintInfo& paintInfo, const LayoutPoint& paintOffset, Scrollbar& scrollbar)
{
    auto scrollRect = rectForScrollbar(scrollbar);
    scrollRect.moveBy(paintOffset);
    scrollbar.setFrameRect(snappedIntRect(scrollRect));
    scrollbar.paint(paintInfo.context(), snappedIntRect(paintInfo.rect));
}

static LayoutSize itemOffsetForAlignment(TextRun textRun, const RenderStyle& elementStyle, const RenderStyle* itemStyle, FontCascade itemFont, LayoutRect itemBoundingBox)
{
    TextAlignMode actualAlignment = itemStyle->textAlign();
    // FIXME: Firefox doesn't respect TextAlignMode::Justify. Should we?
    // FIXME: Handle TextAlignMode::End here
    if (actualAlignment == TextAlignMode::Start || actualAlignment == TextAlignMode::Justify)
        actualAlignment = itemStyle->writingMode().isLogicalLeftInlineStart() ? TextAlignMode::Left : TextAlignMode::Right;

    bool isHorizontalWritingMode = elementStyle.writingMode().isHorizontal();

    auto itemBoundingBoxLogicalWidth = isHorizontalWritingMode ? itemBoundingBox.width() : itemBoundingBox.height();
    auto itemBoundingBoxLogicalHeight = isHorizontalWritingMode ? itemBoundingBox.height() : itemBoundingBox.width();
    auto offset = LayoutSize(0, itemFont.metricsOfPrimaryFont().intAscent());
    if (actualAlignment == TextAlignMode::Right || actualAlignment == TextAlignMode::WebKitRight) {
        float textWidth = itemFont.width(textRun);
        offset.setWidth(itemBoundingBoxLogicalWidth - textWidth - optionsSpacingInlineStart);
    } else if (actualAlignment == TextAlignMode::Center || actualAlignment == TextAlignMode::WebKitCenter) {
        float textWidth = itemFont.width(textRun);
        offset.setWidth((itemBoundingBoxLogicalWidth - textWidth) / 2);
    } else
        offset.setWidth(optionsSpacingInlineStart);

    if (elementStyle.writingMode().isLineOverLeft()) {
        offset.setWidth(offset.width() + itemFont.width(textRun));
        offset.setHeight(itemBoundingBoxLogicalHeight - offset.height());
    }

    if (!isHorizontalWritingMode)
        return LayoutSize { -offset.height(), offset.width() };

    return offset;
}

void RenderListBox::paintItemForeground(PaintInfo& paintInfo, const LayoutPoint& paintOffset, int listIndex)
{
    const auto& listItems = selectElement().listItems();
    RefPtr listItemElement = listItems[listIndex].get();

    auto itemStyle = listItemElement->computedStyleForEditability();
    if (!itemStyle)
        return;

    if (itemStyle->usedVisibility() == Visibility::Hidden)
        return;

    String itemText;
    RefPtr optionElement = dynamicDowncast<HTMLOptionElement>(*listItemElement);
    RefPtr optGroupElement = dynamicDowncast<HTMLOptGroupElement>(*listItemElement);
    if (optionElement)
        itemText = optionElement->textIndentedToRespectGroupLabel();
    else if (optGroupElement)
        itemText = optGroupElement->groupLabelText();
    itemText = applyTextTransform(style(), itemText);

    if (itemText.isNull())
        return;

    Color textColor = itemStyle->visitedDependentColorWithColorFilter(CSSPropertyColor);
    if (optionElement && optionElement->selected()) {
        if (frame().selection().isFocusedAndActive() && document().focusedElement() == &selectElement())
            textColor = theme().activeListBoxSelectionForegroundColor(styleColorOptions());
        // Honor the foreground color for disabled items
        else if (!listItemElement->isDisabledFormControl() && !selectElement().isDisabledFormControl())
            textColor = theme().inactiveListBoxSelectionForegroundColor(styleColorOptions());
    }

    GraphicsContextStateSaver stateSaver(paintInfo.context());

    paintInfo.context().setFillColor(textColor);

    TextRun textRun(itemText, 0, 0, ExpansionBehavior::allowRightOnly(), itemStyle->writingMode().bidiDirection(), isOverride(itemStyle->unicodeBidi()), true);
    FontCascade itemFont = style().fontCascade();
    LayoutRect r = itemBoundingBoxRect(paintOffset, listIndex);
    r.move(itemOffsetForAlignment(textRun, style(), itemStyle, itemFont, r));

    bool isHorizontalWritingMode = writingMode().isHorizontal();
    if (!isHorizontalWritingMode) {
        auto rotationOrigin = roundedIntPoint(r.maxXMinYCorner());
        paintInfo.context().translate(rotationOrigin);
        if (writingMode().isLineOverLeft())
            paintInfo.context().rotate(-piOverTwoFloat);
        else
            paintInfo.context().rotate(piOverTwoFloat);
        paintInfo.context().translate(-rotationOrigin);
    }

    if (optGroupElement) {
        auto description = itemFont.fontDescription();
        description.setWeight(description.bolderWeight());
        itemFont = FontCascade(WTFMove(description), itemFont);
        itemFont.update(&document().fontSelector());
    }

    // Draw the item text
    paintInfo.context().drawBidiText(itemFont, textRun, roundedIntPoint(isHorizontalWritingMode ? r.location() : r.maxXMinYCorner()));
}

void RenderListBox::paintItemBackground(PaintInfo& paintInfo, const LayoutPoint& paintOffset, int listIndex)
{
    const auto& listItems = selectElement().listItems();
    RefPtr listItemElement = listItems[listIndex].get();
    auto itemStyle = listItemElement->computedStyleForEditability();
    if (!itemStyle)
        return;

    Color backColor;
    if (auto* option = dynamicDowncast<HTMLOptionElement>(*listItemElement); option && option->selected()) {
        if (frame().selection().isFocusedAndActive() && document().focusedElement() == &selectElement())
            backColor = theme().activeListBoxSelectionBackgroundColor(styleColorOptions());
        else
            backColor = theme().inactiveListBoxSelectionBackgroundColor(styleColorOptions());
    } else
        backColor = itemStyle->visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);

    // Draw the background for this list box item
    if (itemStyle->usedVisibility() == Visibility::Hidden)
        return;

    LayoutRect itemRect = itemBoundingBoxRect(paintOffset, listIndex);
    itemRect.intersect(controlClipRect(paintOffset));
    paintInfo.context().fillRect(snappedIntRect(itemRect), backColor);
}

bool RenderListBox::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
{
    auto* activeScrollbar = verticalScrollbar();
    if (!activeScrollbar)
        activeScrollbar = horizontalScrollbar();

    if (!activeScrollbar || !activeScrollbar->shouldParticipateInHitTesting())
        return false;

    auto scrollbarRect = rectForScrollbar(*activeScrollbar);
    scrollbarRect.moveBy(accumulatedOffset);

    if (!scrollbarRect.contains(locationInContainer))
        return false;

    result.setScrollbar(activeScrollbar);
    return true;
}

int RenderListBox::listIndexAtOffset(const LayoutSize& offset) const
{
    if (!numItems())
        return -1;

    int scrollbarHeight = 0;
    if (auto* hBar = horizontalScrollbar())
        scrollbarHeight = hBar->height();

    if (offset.height() < borderTop() || offset.height() > height() - borderBottom() - scrollbarHeight)
        return -1;

    int scrollbarWidth = 0;
    if (auto* vBar = verticalScrollbar())
        scrollbarWidth = vBar->width();

    if (shouldPlaceVerticalScrollbarOnLeft() && (offset.width() < borderLeft() + paddingLeft() + scrollbarWidth || offset.width() > width() - borderRight() - paddingRight()))
        return -1;
    if (!shouldPlaceVerticalScrollbarOnLeft() && (offset.width() < borderLeft() + paddingLeft() || offset.width() > width() - borderRight() - paddingRight() - scrollbarWidth))
        return -1;

    auto offsetLogicalHeight = writingMode().isHorizontal() ? offset.height() : offset.width();

    int newOffset;
    if (writingMode().isBlockFlipped())
        newOffset = (logicalHeight() - borderAndPaddingBefore() - offsetLogicalHeight) / itemLogicalHeight() + indexOffset();
    else
        newOffset = (offsetLogicalHeight - borderAndPaddingBefore()) / itemLogicalHeight() + indexOffset();

    return newOffset < numItems() ? newOffset : -1;
}

void RenderListBox::panScroll(const IntPoint& panStartMousePosition)
{
    // FIXME: This does not support vertical writing mode or flipped block directions.

    const int maxSpeed = 20;
    const int iconRadius = 7;
    const int speedReducer = 4;

    // FIXME: This doesn't work correctly with transforms.
    FloatPoint absOffset = localToAbsolute();

    IntPoint lastKnownMousePosition = frame().eventHandler().lastKnownMousePosition();
    // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
    static IntPoint previousMousePosition;
    if (lastKnownMousePosition.y() < 0)
        lastKnownMousePosition = previousMousePosition;
    else
        previousMousePosition = lastKnownMousePosition;

    int yDelta = lastKnownMousePosition.y() - panStartMousePosition.y();

    // If the point is too far from the center we limit the speed
    yDelta = std::max<int>(std::min<int>(yDelta, maxSpeed), -maxSpeed);
    
    if (std::abs(yDelta) < iconRadius) // at the center we let the space for the icon
        return;

    if (yDelta > 0)
        absOffset.move(0, listLogicalHeight());
    else if (yDelta < 0)
        yDelta--;

    // Let's attenuate the speed
    yDelta /= speedReducer;

    IntPoint scrollPoint(0, 0);
    scrollPoint.setY(absOffset.y() + yDelta);
    int newOffset = scrollToward(scrollPoint);
    if (newOffset < 0) 
        return;

    m_inAutoscroll = true;
    selectElement().updateListBoxSelection(!selectElement().multiple());
    m_inAutoscroll = false;
}

int RenderListBox::scrollToward(const IntPoint& destination)
{
    // FIXME: This doesn't work correctly with transforms.
    FloatPoint absPos = localToAbsolute();
    IntSize positionOffset = roundedIntSize(destination - absPos);
    int positionOffsetLogicalHeight = writingMode().isHorizontal() ? positionOffset.height() : positionOffset.width();

    int rows = numVisibleItems();
    int offset = indexOffset();

    if (writingMode().isBlockFlipped()) {
        if (positionOffsetLogicalHeight < borderAndPaddingAfter() && scrollToRevealElementAtListIndex(offset + rows))
            return offset + rows - 1;

        if (positionOffsetLogicalHeight > logicalHeight() - borderAndPaddingBefore() && scrollToRevealElementAtListIndex(offset - 1))
            return offset - 1;
    } else {
        if (positionOffsetLogicalHeight < borderAndPaddingBefore() && scrollToRevealElementAtListIndex(offset - 1))
            return offset - 1;

        if (positionOffsetLogicalHeight > logicalHeight() - borderAndPaddingAfter() && scrollToRevealElementAtListIndex(offset + rows))
            return offset + rows - 1;
    }

    return listIndexAtOffset(positionOffset);
}

void RenderListBox::autoscroll(const IntPoint&)
{
    IntPoint pos = frame().view()->windowToContents(frame().eventHandler().lastKnownMousePosition());

    int endIndex = scrollToward(pos);
    if (selectElement().isDisabledFormControl())
        return;

    if (endIndex >= 0) {
        m_inAutoscroll = true;

        if (!selectElement().multiple())
            selectElement().setActiveSelectionAnchorIndex(endIndex);

        selectElement().setActiveSelectionEndIndex(endIndex);
        selectElement().updateListBoxSelection(!selectElement().multiple());
        m_inAutoscroll = false;
    }
}

void RenderListBox::stopAutoscroll()
{
    if (selectElement().isDisabledFormControl())
        return;

    selectElement().listBoxOnChange();
}

bool RenderListBox::scrollToRevealElementAtListIndex(int index)
{
    if (index < 0 || index >= numItems() || listIndexIsVisible(index))
        return false;

    int newOffset;
    if (index < indexOffset())
        newOffset = index;
    else
        newOffset = index - numVisibleItems() + 1;

    if (writingMode().isBlockFlipped())
        newOffset *= -1;

    scrollToPosition(newOffset);
    return true;
}

bool RenderListBox::listIndexIsVisible(int index)
{
    int firstIndex = m_indexOfFirstVisibleItemInsidePaddingBeforeArea.value_or(indexOffset());
    int endIndex = m_indexOfFirstVisibleItemInsidePaddingAfterArea
        ? m_indexOfFirstVisibleItemInsidePaddingAfterArea.value() + numberOfVisibleItemsInPaddingAfter()
        : indexOffset() + numVisibleItems();

    return index >= firstIndex && index < endIndex;
}

bool RenderListBox::scroll(ScrollDirection direction, ScrollGranularity granularity, unsigned stepCount, Element**, RenderBox*, const IntPoint&)
{
    return ScrollableArea::scroll(direction, granularity, stepCount);
}

bool RenderListBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, unsigned stepCount, Element**)
{
    return ScrollableArea::scroll(logicalToPhysical(direction, writingMode().isHorizontal(), writingMode().isBlockFlipped()), granularity, stepCount);
}

int RenderListBox::indexOffset() const
{
    auto scrollPosition = this->scrollPosition();
    if (!writingMode().isHorizontal())
        scrollPosition = scrollPosition.transposedPoint();
    return std::abs(scrollPosition.y());
}

ScrollPosition RenderListBox::scrollPosition() const
{
    return m_scrollPosition;
}

ScrollPosition RenderListBox::minimumScrollPosition() const
{
    return scrollPositionFromOffset(ScrollOffset());
}

ScrollPosition RenderListBox::maximumScrollPosition() const
{
    auto maximumScrollOffset = ScrollOffset(0, numItems() - numVisibleItems());
    if (!writingMode().isHorizontal())
        maximumScrollOffset = maximumScrollOffset.transposedPoint();
    return scrollPositionFromOffset(maximumScrollOffset);
}

void RenderListBox::setScrollOffset(const ScrollOffset& offset)
{
    scrollTo(scrollPositionFromOffset(offset));
}

int RenderListBox::maximumNumberOfItemsThatFitInPaddingAfterArea() const
{
    return paddingAfter() / itemLogicalHeight();
}

int RenderListBox::numberOfVisibleItemsInPaddingBefore() const
{
    if (!m_indexOfFirstVisibleItemInsidePaddingBeforeArea)
        return 0;

    return indexOffset() - m_indexOfFirstVisibleItemInsidePaddingBeforeArea.value();
}

int RenderListBox::numberOfVisibleItemsInPaddingAfter() const
{
    if (!m_indexOfFirstVisibleItemInsidePaddingAfterArea)
        return 0;

    return std::min(maximumNumberOfItemsThatFitInPaddingAfterArea(), numItems() - indexOffset() - numVisibleItems());
}

void RenderListBox::computeFirstIndexesVisibleInPaddingBeforeAfterAreas()
{
    m_indexOfFirstVisibleItemInsidePaddingBeforeArea = std::nullopt;
    m_indexOfFirstVisibleItemInsidePaddingAfterArea = std::nullopt;

    int maximumNumberOfItemsThatFitInPaddingBeforeArea = paddingBefore() / itemLogicalHeight();
    if (maximumNumberOfItemsThatFitInPaddingBeforeArea) {
        if (indexOffset())
            m_indexOfFirstVisibleItemInsidePaddingBeforeArea = std::max(0, indexOffset() - maximumNumberOfItemsThatFitInPaddingBeforeArea);
    }

    if (maximumNumberOfItemsThatFitInPaddingAfterArea()) {
        if (numItems() > (indexOffset() + numVisibleItems()))
            m_indexOfFirstVisibleItemInsidePaddingAfterArea = indexOffset() + numVisibleItems();
    }
}

void RenderListBox::scrollTo(const ScrollPosition& position)
{
    if (position == m_scrollPosition)
        return;

    m_scrollPosition = position;

    computeFirstIndexesVisibleInPaddingBeforeAfterAreas();

    repaint();
    document().addPendingScrollEventTarget(selectElement());
}

LayoutUnit RenderListBox::itemLogicalHeight() const
{
    return style().metricsOfPrimaryFont().intHeight() + itemBlockSpacing;
}

int RenderListBox::verticalScrollbarWidth() const
{
    if (auto* vBar = verticalScrollbar())
        return vBar->occupiedWidth();

    return 0;
}

int RenderListBox::horizontalScrollbarHeight() const
{
    if (auto* hBar = horizontalScrollbar())
        return hBar->occupiedHeight();

    return 0;
}

Scrollbar* RenderListBox::verticalScrollbar() const
{
    if (m_scrollbar && m_scrollbar->orientation() == ScrollbarOrientation::Vertical)
        return m_scrollbar.get();

    return nullptr;
}

Scrollbar* RenderListBox::horizontalScrollbar() const
{
    if (m_scrollbar && m_scrollbar->orientation() == ScrollbarOrientation::Horizontal)
        return m_scrollbar.get();

    return nullptr;
}

ScrollbarOrientation RenderListBox::scrollbarOrientationForWritingMode() const
{
    if (writingMode().isHorizontal())
        return ScrollbarOrientation::Vertical;
    return ScrollbarOrientation::Horizontal;
}

// FIXME: We ignore padding in the vertical direction as far as these values are concerned, since that's
// how the control currently paints.
int RenderListBox::scrollWidth() const
{
    if (writingMode().isHorizontal())
        return roundToInt(clientWidth());

    return roundToInt(std::max(clientWidth(), listLogicalHeight()));
}

int RenderListBox::scrollHeight() const
{
    if (writingMode().isHorizontal())
        return roundToInt(std::max(clientHeight(), listLogicalHeight()));

    return roundToInt(clientHeight());
}

int RenderListBox::scrollLeft() const
{
    if (writingMode().isHorizontal())
        return 0;
    return logicalScrollTop();
}

void RenderListBox::setScrollLeft(int newLeft, const ScrollPositionChangeOptions&)
{
    if (writingMode().isHorizontal())
        return;

    setLogicalScrollTop(newLeft);
}

int RenderListBox::scrollTop() const
{
    if (writingMode().isHorizontal())
        return logicalScrollTop();
    return 0;
}

static void setupWheelEventTestMonitor(RenderListBox& renderer)
{
    if (!renderer.page().isMonitoringWheelEvents())
        return;

    renderer.scrollAnimator().setWheelEventTestMonitor(renderer.page().wheelEventTestMonitor());
}

void RenderListBox::setScrollTop(int newTop, const ScrollPositionChangeOptions&)
{
    if (!writingMode().isHorizontal())
        return;

    setLogicalScrollTop(newTop);
}

int RenderListBox::logicalScrollTop() const
{
    int logicalTop = indexOffset() * itemLogicalHeight();
    if (writingMode().isBlockFlipped())
        logicalTop *= -1;
    return logicalTop;
}

void RenderListBox::scrollToPosition(int positionIndex)
{
    auto orientation = scrollbarOrientationForWritingMode();
    auto scrollOrigin = this->scrollOrigin();

    int offsetIndex = positionIndex;

    switch (orientation) {
    case ScrollbarOrientation::Vertical:
        offsetIndex = positionIndex + scrollOrigin.y();
        break;
    case ScrollbarOrientation::Horizontal:
        offsetIndex = positionIndex + scrollOrigin.x();
        break;
    }

    scrollToOffsetWithoutAnimation(orientation, offsetIndex);
}

void RenderListBox::setLogicalScrollTop(int newLogicalScrollTop)
{
    bool isFlipped = writingMode().isBlockFlipped();

    int newTop = newLogicalScrollTop;
    if (isFlipped)
        newTop *= -1;

    int index = newTop / itemLogicalHeight();
    index = std::clamp(index, 0, std::max(0, numItems() - 1));
    if (index == indexOffset())
        return;

    if (isFlipped)
        index *= -1;

    setupWheelEventTestMonitor(*this);
    scrollToPosition(index);
}

bool RenderListBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
    if (!RenderBlockFlow::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
        return false;
    const auto& listItems = selectElement().listItems();
    int size = numItems();
    LayoutPoint adjustedLocation = accumulatedOffset + location();

    for (int i = 0; i < size; ++i) {
        if (!itemBoundingBoxRect(adjustedLocation, i).contains(locationInContainer.point()))
            continue;
        if (RefPtr node = listItems[i].get()) {
            result.setInnerNode(node.get());
            if (!result.innerNonSharedNode())
                result.setInnerNonSharedNode(node.get());
            result.setLocalPoint(locationInContainer.point() - toLayoutSize(adjustedLocation));
            break;
        }
    }

    return true;
}

LayoutRect RenderListBox::controlClipRect(const LayoutPoint& additionalOffset) const
{
    // Clip against the padding box, to give <option>s and overlay scrollbar some extra space
    // to get painted.
    LayoutRect clipRect = paddingBoxRect();
    clipRect.moveBy(additionalOffset);
    return clipRect;
}

bool RenderListBox::isActive() const
{
    return page().focusController().isActive();
}

LayoutRect RenderListBox::rectForScrollbar(const Scrollbar& scrollbar) const
{
    LayoutUnit left, top, width, height;

    if (scrollbar.orientation() == ScrollbarOrientation::Vertical) {
        left = shouldPlaceVerticalScrollbarOnLeft() ? borderLeft() : this->width() - borderRight() - scrollbar.width();
        top = borderTop();
        width = scrollbar.width();
        height = this->height() - verticalBorderExtent();
    } else {
        left = borderLeft();
        top = this->height() - borderBottom() - scrollbar.height();
        width = this->width() - horizontalBorderExtent();
        height = scrollbar.height();
    }

    return LayoutRect { left, top, width, height };
}

void RenderListBox::invalidateScrollbarRect(Scrollbar& scrollbar, const IntRect& rect)
{
    auto scrollRect = rect;
    auto scrollbarLocation = rectForScrollbar(scrollbar).location();
    scrollRect.move(scrollbarLocation.x(), scrollbarLocation.y());
    repaintRectangle(scrollRect);
}

IntRect RenderListBox::convertFromScrollbarToContainingView(const Scrollbar& scrollbar, const IntRect& scrollbarRect) const
{
    auto rect = scrollbarRect;
    auto scrollbarLocation = rectForScrollbar(scrollbar).location();
    rect.move(scrollbarLocation.x(), scrollbarLocation.y());
    return view().frameView().convertFromRendererToContainingView(this, rect);
}

IntRect RenderListBox::convertFromContainingViewToScrollbar(const Scrollbar& scrollbar, const IntRect& parentRect) const
{
    IntRect rect = view().frameView().convertFromContainingViewToRenderer(this, parentRect);
    auto scrollbarLocation = rectForScrollbar(scrollbar).location();
    rect.move(-scrollbarLocation.x(), -scrollbarLocation.y());
    return rect;
}

IntPoint RenderListBox::convertFromScrollbarToContainingView(const Scrollbar& scrollbar, const IntPoint& scrollbarPoint) const
{
    auto point = scrollbarPoint;
    auto scrollbarLocation = rectForScrollbar(scrollbar).location();
    point.move(scrollbarLocation.x(), scrollbarLocation.y());
    return view().frameView().convertFromRendererToContainingView(this, point);
}

IntPoint RenderListBox::convertFromContainingViewToScrollbar(const Scrollbar& scrollbar, const IntPoint& parentPoint) const
{
    IntPoint point = view().frameView().convertFromContainingViewToRenderer(this, parentPoint);
    auto scrollbarLocation = rectForScrollbar(scrollbar).location();
    point.move(-scrollbarLocation.x(), -scrollbarLocation.y());
    return point;
}

IntSize RenderListBox::contentsSize() const
{
    return IntSize(scrollWidth(), scrollHeight());
}

IntPoint RenderListBox::lastKnownMousePositionInView() const
{
    return view().frameView().lastKnownMousePositionInView();
}

bool RenderListBox::isHandlingWheelEvent() const
{
    return view().frameView().isHandlingWheelEvent();
}

bool RenderListBox::shouldSuspendScrollAnimations() const
{
    return view().frameView().shouldSuspendScrollAnimations();
}

bool RenderListBox::forceUpdateScrollbarsOnMainThreadForPerformanceTesting() const
{
    return settings().scrollingPerformanceTestingEnabled();
}

ScrollableArea* RenderListBox::enclosingScrollableArea() const
{
    auto* layer = enclosingLayer();
    if (!layer)
        return nullptr;

    auto* enclosingScrollableLayer = layer->enclosingScrollableLayer(IncludeSelfOrNot::ExcludeSelf, CrossFrameBoundaries::No);
    if (!enclosingScrollableLayer)
        return nullptr;

    return enclosingScrollableLayer->scrollableArea();
}

bool RenderListBox::isScrollableOrRubberbandable()
{
    return !!m_scrollbar;
}

bool RenderListBox::hasScrollableOrRubberbandableAncestor()
{
    if (auto* scrollableArea = enclosingLayer() ? enclosingLayer()->scrollableArea() : nullptr)
        return scrollableArea->hasScrollableOrRubberbandableAncestor();
    return false;
}

IntRect RenderListBox::scrollableAreaBoundingBox(bool*) const
{
    return absoluteBoundingBoxRect();
}

bool RenderListBox::mockScrollbarsControllerEnabled() const
{
    return settings().mockScrollbarsControllerEnabled();
}

void RenderListBox::logMockScrollbarsControllerMessage(const String& message) const
{
    document().addConsoleMessage(MessageSource::Other, MessageLevel::Debug, makeString("RenderListBox: "_s, message));
}

String RenderListBox::debugDescription() const
{
    return RenderObject::debugDescription();
}

void RenderListBox::didStartScrollAnimation()
{
    page().scheduleRenderingUpdate({ RenderingUpdateStep::Scroll });
}

Ref<Scrollbar> RenderListBox::createScrollbar(ScrollbarOrientation orientation)
{
    RefPtr<Scrollbar> widget;
    bool usesLegacyScrollbarStyle = style().usesLegacyScrollbarStyle();
    if (usesLegacyScrollbarStyle)
        widget = RenderScrollbar::createCustomScrollbar(*this, orientation, &selectElement());
    else {
        widget = Scrollbar::createNativeScrollbar(*this, orientation, theme().scrollbarWidthStyleForPart(StyleAppearance::Listbox));
        didAddScrollbar(widget.get(), orientation);
        if (page().isMonitoringWheelEvents())
            scrollAnimator().setWheelEventTestMonitor(page().wheelEventTestMonitor());
    }
    view().frameView().addChild(*widget);
    return widget.releaseNonNull();
}

void RenderListBox::destroyScrollbar()
{
    if (!m_scrollbar)
        return;

    if (!m_scrollbar->isCustomScrollbar())
        ScrollableArea::willRemoveScrollbar(m_scrollbar.get(), m_scrollbar->orientation());
    m_scrollbar->removeFromParent();
    m_scrollbar = nullptr;
}

void RenderListBox::setHasScrollbar(ScrollbarOrientation orientation)
{
    if (verticalScrollbar() && orientation == ScrollbarOrientation::Vertical)
        return;

    if (horizontalScrollbar() && orientation == ScrollbarOrientation::Horizontal)
        return;

    destroyScrollbar();
    m_scrollbar = createScrollbar(orientation);
    m_scrollbar->styleChanged();
}

float RenderListBox::deviceScaleFactor() const
{
    return page().deviceScaleFactor();
}
    
bool RenderListBox::isVisibleToHitTesting() const
{
    return visibleToHitTesting();
}

std::optional<FrameIdentifier> RenderListBox::rootFrameID() const
{
    return view().frameView().frame().rootFrame().frameID();
}

} // namespace WebCore