summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/layout/layout_box.h
blob: 5921913da3aef0525c3829a1e33f3b3b656fd112 (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
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_BOX_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_BOX_H_

#include <memory>

#include "base/macros.h"
#include "third_party/blink/public/mojom/scroll/scroll_into_view_params.mojom-blink-forward.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/min_max_sizes.h"
#include "third_party/blink/renderer/core/layout/overflow_model.h"
#include "third_party/blink/renderer/platform/graphics/scroll_types.h"

namespace blink {

class CustomLayoutChild;
class LayoutBlockFlow;
class LayoutMultiColumnSpannerPlaceholder;
class NGBoxFragmentBuilder;
class NGConstraintSpace;
class ShapeOutsideInfo;
struct BoxLayoutExtraInput;
class NGEarlyBreak;
class NGBreakToken;
struct NGFragmentGeometry;
enum class NGLayoutCacheStatus;
class NGLayoutResult;
struct NGPhysicalBoxStrut;
struct PaintInfo;

enum SizeType { kMainOrPreferredSize, kMinSize, kMaxSize };
enum AvailableLogicalHeightType {
  kExcludeMarginBorderPadding,
  kIncludeMarginBorderPadding
};
// When painting, overlay scrollbars do not take up space and should not affect
// clipping behavior. During hit testing, overlay scrollbars behave like regular
// scrollbars and should change how hit testing is clipped.
enum MarginDirection { kBlockDirection, kInlineDirection };
enum BackgroundRectType { kBackgroundClipRect, kBackgroundKnownOpaqueRect };

enum ShouldComputePreferred { kComputeActual, kComputePreferred };

using SnapAreaSet = HashSet<LayoutBox*>;

struct LayoutBoxRareData final : public GarbageCollected<LayoutBoxRareData> {
 public:
  LayoutBoxRareData();

  void Trace(Visitor* visitor) const;

  // For spanners, the spanner placeholder that lays us out within the multicol
  // container.
  LayoutMultiColumnSpannerPlaceholder* spanner_placeholder_;

  LayoutUnit override_logical_width_;
  LayoutUnit override_logical_height_;

  bool has_override_containing_block_content_logical_width_ : 1;
  bool has_override_containing_block_content_logical_height_ : 1;
  bool has_override_percentage_resolution_block_size_ : 1;
  bool has_previous_content_box_rect_and_layout_overflow_rect_ : 1;

  LayoutUnit override_containing_block_content_logical_width_;
  LayoutUnit override_containing_block_content_logical_height_;
  LayoutUnit override_percentage_resolution_block_size_;

  LayoutUnit offset_to_next_page_;

  LayoutUnit pagination_strut_;

  LayoutBlock* percent_height_container_;
  // For snap area, the owning snap container.
  LayoutBox* snap_container_;
  // For snap container, the descendant snap areas that contribute snap
  // points.
  std::unique_ptr<SnapAreaSet> snap_areas_;

  SnapAreaSet& EnsureSnapAreas() {
    if (!snap_areas_)
      snap_areas_ = std::make_unique<SnapAreaSet>();

    return *snap_areas_;
  }

  // Used by BoxPaintInvalidator. Stores the previous content box size and
  // layout overflow rect after the last paint invalidation. They are valid if
  // has_previous_content_box_rect_and_layout_overflow_rect_ is true.
  PhysicalRect previous_physical_content_box_rect_;
  PhysicalRect previous_physical_layout_overflow_rect_;

  // Used by CSSLayoutDefinition::Instance::Layout. Represents the script
  // object for this box that web developers can query style, and perform
  // layout upon. Only created if IsCustomItem() is true.
  Member<CustomLayoutChild> layout_child_;

  DISALLOW_COPY_AND_ASSIGN(LayoutBoxRareData);
};

// LayoutBox implements the full CSS box model.
//
// LayoutBoxModelObject only introduces some abstractions for LayoutInline and
// LayoutBox. The logic for the model is in LayoutBox, e.g. the storage for the
// rectangle and offset forming the CSS box (frame_rect_) and the getters for
// the different boxes.
//
// LayoutBox is also the uppermost class to support scrollbars, however the
// logic is delegated to PaintLayerScrollableArea.
// Per the CSS specification, scrollbars should "be inserted between the inner
// border edge and the outer padding edge".
// (see http://www.w3.org/TR/CSS21/visufx.html#overflow)
// Also the scrollbar width / height are removed from the content box. Taking
// the following example:
//
// <!DOCTYPE html>
// <style>
// ::-webkit-scrollbar {
//     /* Force non-overlay scrollbars */
//     width: 10px;
//     height: 20px;
// }
// </style>
// <div style="overflow:scroll; width: 100px; height: 100px">
//
// The <div>'s content box is not 100x100 as specified in the style but 90x80 as
// we remove the scrollbars from the box.
//
// The presence of scrollbars is determined by the 'overflow' property and can
// be conditioned on having layout overflow (see OverflowModel for more details
// on how we track overflow).
//
// There are 2 types of scrollbars:
// - non-overlay scrollbars take space from the content box.
// - overlay scrollbars don't and just overlay hang off from the border box,
//   potentially overlapping with the padding box's content.
// For more details on scrollbars, see PaintLayerScrollableArea.
//
//
// ***** THE BOX MODEL *****
// The CSS box model is based on a series of nested boxes:
// http://www.w3.org/TR/CSS21/box.html
//
//       |----------------------------------------------------|
//       |                                                    |
//       |                   margin-top                       |
//       |                                                    |
//       |     |-----------------------------------------|    |
//       |     |                                         |    |
//       |     |             border-top                  |    |
//       |     |                                         |    |
//       |     |    |--------------------------|----|    |    |
//       |     |    |                          |    |    |    |
//       |     |    |       padding-top        |####|    |    |
//       |     |    |                          |####|    |    |
//       |     |    |    |----------------|    |####|    |    |
//       |     |    |    |                |    |    |    |    |
//       | ML  | BL | PL |  content box   | PR | SW | BR | MR |
//       |     |    |    |                |    |    |    |    |
//       |     |    |    |----------------|    |    |    |    |
//       |     |    |                          |    |    |    |
//       |     |    |      padding-bottom      |    |    |    |
//       |     |    |--------------------------|----|    |    |
//       |     |    |                      ####|    |    |    |
//       |     |    |     scrollbar height ####| SC |    |    |
//       |     |    |                      ####|    |    |    |
//       |     |    |-------------------------------|    |    |
//       |     |                                         |    |
//       |     |           border-bottom                 |    |
//       |     |                                         |    |
//       |     |-----------------------------------------|    |
//       |                                                    |
//       |                 margin-bottom                      |
//       |                                                    |
//       |----------------------------------------------------|
//
// BL = border-left
// BR = border-right
// ML = margin-left
// MR = margin-right
// PL = padding-left
// PR = padding-right
// SC = scroll corner (contains UI for resizing (see the 'resize' property)
// SW = scrollbar width
//
// Note that the vertical scrollbar (if existing) will be on the left in
// right-to-left direction and horizontal writing-mode. The horizontal scrollbar
// (if existing) is always at the bottom.
//
// Those are just the boxes from the CSS model. Extra boxes are tracked by Blink
// (e.g. the overflows). Thus it is paramount to know which box a function is
// manipulating. Also of critical importance is the coordinate system used (see
// the COORDINATE SYSTEMS section in LayoutBoxModelObject).
class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
 public:
  explicit LayoutBox(ContainerNode*);

  PaintLayerType LayerTypeRequired() const override;

  bool BackgroundIsKnownToBeOpaqueInRect(
      const PhysicalRect& local_rect) const override;
  bool TextIsKnownToBeOnOpaqueBackground() const override;

  virtual bool BackgroundShouldAlwaysBeClipped() const { return false; }

  // Returns whether this object needs a scroll paint property tree node. These
  // are a requirement for composited scrolling but are also created for
  // non-composited scrollers.
  bool NeedsScrollNode(CompositingReasons direct_compositing_reasons) const;

  // Use this with caution! No type checking is done!
  LayoutBox* FirstChildBox() const;
  LayoutBox* FirstInFlowChildBox() const;
  LayoutBox* LastChildBox() const;

  // TODO(crbug.com/962299): This is incorrect in some cases.
  int PixelSnappedWidth() const { return frame_rect_.PixelSnappedWidth(); }
  int PixelSnappedHeight() const { return frame_rect_.PixelSnappedHeight(); }

  void SetX(LayoutUnit x) {
    if (x == frame_rect_.X())
      return;
    frame_rect_.SetX(x);
    LocationChanged();
  }
  void SetY(LayoutUnit y) {
    if (y == frame_rect_.Y())
      return;
    frame_rect_.SetY(y);
    LocationChanged();
  }
  void SetWidth(LayoutUnit width) {
    if (width == frame_rect_.Width())
      return;
    frame_rect_.SetWidth(width);
    SizeChanged();
  }
  void SetHeight(LayoutUnit height) {
    if (height == frame_rect_.Height())
      return;
    frame_rect_.SetHeight(height);
    SizeChanged();
  }

  LayoutUnit LogicalLeft() const {
    return StyleRef().IsHorizontalWritingMode() ? frame_rect_.X()
                                                : frame_rect_.Y();
  }
  LayoutUnit LogicalRight() const { return LogicalLeft() + LogicalWidth(); }
  LayoutUnit LogicalTop() const {
    return StyleRef().IsHorizontalWritingMode() ? frame_rect_.Y()
                                                : frame_rect_.X();
  }
  LayoutUnit LogicalBottom() const { return LogicalTop() + LogicalHeight(); }
  LayoutUnit LogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode() ? frame_rect_.Width()
                                                : frame_rect_.Height();
  }
  LayoutUnit LogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode() ? frame_rect_.Height()
                                                : frame_rect_.Width();
  }

  // Logical height of the object, including content overflowing the
  // border-after edge.
  virtual LayoutUnit LogicalHeightWithVisibleOverflow() const;

  LayoutUnit ConstrainLogicalWidthByMinMax(LayoutUnit,
                                           LayoutUnit,
                                           const LayoutBlock*) const;
  LayoutUnit ConstrainLogicalHeightByMinMax(
      LayoutUnit logical_height,
      LayoutUnit intrinsic_content_height) const;
  LayoutUnit ConstrainContentBoxLogicalHeightByMinMax(
      LayoutUnit logical_height,
      LayoutUnit intrinsic_content_height) const;

  // TODO(crbug.com/962299): This is incorrect in some cases.
  int PixelSnappedLogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode() ? PixelSnappedHeight()
                                                : PixelSnappedWidth();
  }
  int PixelSnappedLogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode() ? PixelSnappedWidth()
                                                : PixelSnappedHeight();
  }

  LayoutUnit MinimumLogicalHeightForEmptyLine() const {
    return BorderAndPaddingLogicalHeight() + ScrollbarLogicalHeight() +
           LogicalHeightForEmptyLine();
  }
  LayoutUnit LogicalHeightForEmptyLine() const {
    return LineHeight(
        true, IsHorizontalWritingMode() ? kHorizontalLine : kVerticalLine,
        kPositionOfInteriorLineBoxes);
  }

  void SetLogicalLeft(LayoutUnit left) {
    if (StyleRef().IsHorizontalWritingMode())
      SetX(left);
    else
      SetY(left);
  }
  void SetLogicalTop(LayoutUnit top) {
    if (StyleRef().IsHorizontalWritingMode())
      SetY(top);
    else
      SetX(top);
  }
  void SetLogicalLocation(const LayoutPoint& location) {
    if (StyleRef().IsHorizontalWritingMode())
      SetLocation(location);
    else
      SetLocation(location.TransposedPoint());
  }
  void SetLogicalWidth(LayoutUnit size) {
    if (StyleRef().IsHorizontalWritingMode())
      SetWidth(size);
    else
      SetHeight(size);
  }
  void SetLogicalHeight(LayoutUnit size) {
    if (StyleRef().IsHorizontalWritingMode())
      SetHeight(size);
    else
      SetWidth(size);
  }

  // See frame_rect_.
  LayoutPoint Location() const { return frame_rect_.Location(); }
  LayoutSize LocationOffset() const {
    return LayoutSize(frame_rect_.X(), frame_rect_.Y());
  }
  LayoutSize Size() const { return frame_rect_.Size(); }
  // TODO(crbug.com/962299): This is incorrect in some cases.
  IntSize PixelSnappedSize() const { return frame_rect_.PixelSnappedSize(); }

  void SetLocation(const LayoutPoint& location) {
    if (location == frame_rect_.Location())
      return;
    frame_rect_.SetLocation(location);
    LocationChanged();
  }

  // The ancestor box that this object's Location and PhysicalLocation are
  // relative to.
  virtual LayoutBox* LocationContainer() const;

  // FIXME: Currently scrollbars are using int geometry and positioned based on
  // pixelSnappedBorderBoxRect whose size may change when location changes
  // because of pixel snapping. This function is used to change location of the
  // LayoutBox outside of LayoutBox::layout(). Will remove when we use
  // LayoutUnits for scrollbars.
  void SetLocationAndUpdateOverflowControlsIfNeeded(const LayoutPoint&);

  void SetSize(const LayoutSize& size) {
    if (size == frame_rect_.Size())
      return;
    frame_rect_.SetSize(size);
    SizeChanged();
  }
  void Move(LayoutUnit dx, LayoutUnit dy) {
    if (!dx && !dy)
      return;
    frame_rect_.Move(dx, dy);
    LocationChanged();
  }

  // See frame_rect_.
  LayoutRect FrameRect() const { return frame_rect_; }
  void SetFrameRect(const LayoutRect& rect) {
    SetLocation(rect.Location());
    SetSize(rect.Size());
  }

  // Note that those functions have their origin at this box's CSS border box.
  // As such their location doesn't account for 'top'/'left'. About its
  // coordinate space, it can be treated as in either physical coordinates
  // or "physical coordinates in flipped block-flow direction", and
  // FlipForWritingMode() will do nothing on it.
  LayoutRect BorderBoxRect() const { return LayoutRect(LayoutPoint(), Size()); }
  PhysicalRect PhysicalBorderBoxRect() const {
    // This doesn't need flipping because the result would be the same.
    DCHECK_EQ(PhysicalRect(BorderBoxRect()),
              FlipForWritingMode(BorderBoxRect()));
    return PhysicalRect(BorderBoxRect());
  }

  // Client rect and padding box rect are the same concept.
  // TODO(crbug.com/877518): Some callers of this method may actually want
  // "physical coordinates in flipped block-flow direction".
  DISABLE_CFI_PERF PhysicalRect PhysicalPaddingBoxRect() const {
    return PhysicalRect(ClientLeft(), ClientTop(), ClientWidth(),
                        ClientHeight());
  }

  // TODO(crbug.com/962299): This method snaps to pixels incorrectly because
  // Location() is not the correct paint offset. It's also incorrect in flipped
  // blocks writing mode.
  IntRect PixelSnappedBorderBoxRect() const {
    return IntRect(IntPoint(),
                   PixelSnappedBorderBoxSize(PhysicalOffset(Location())));
  }
  // TODO(crbug.com/962299): This method is only correct when |offset| is the
  // correct paint offset.
  IntSize PixelSnappedBorderBoxSize(const PhysicalOffset& offset) const {
    return PixelSnappedIntSize(Size(), offset.ToLayoutPoint());
  }
  IntRect BorderBoundingBox() const final {
    return PixelSnappedBorderBoxRect();
  }

  // The content area of the box (excludes padding - and intrinsic padding for
  // table cells, etc... - and scrollbars and border).
  // TODO(crbug.com/877518): Some callers of this method may actually want
  // "physical coordinates in flipped block-flow direction".
  DISABLE_CFI_PERF PhysicalRect PhysicalContentBoxRect() const {
    return PhysicalRect(ContentLeft(), ContentTop(), ContentWidth(),
                        ContentHeight());
  }
  // TODO(crbug.com/877518): Some callers of this method may actually want
  // "physical coordinates in flipped block-flow direction".
  PhysicalOffset PhysicalContentBoxOffset() const {
    return PhysicalOffset(ContentLeft(), ContentTop());
  }
  // The content box converted to absolute coords (taking transforms into
  // account).
  FloatQuad AbsoluteContentQuad(MapCoordinatesFlags = 0) const;

  // The enclosing rectangle of the background with given opacity requirement.
  // TODO(crbug.com/877518): Some callers of this method may actually want
  // "physical coordinates in flipped block-flow direction".
  PhysicalRect PhysicalBackgroundRect(BackgroundRectType) const;

  // This returns the content area of the box (excluding padding and border).
  // The only difference with contentBoxRect is that computedCSSContentBoxRect
  // does include the intrinsic padding in the content box as this is what some
  // callers expect (like getComputedStyle).
  LayoutRect ComputedCSSContentBoxRect() const {
    return LayoutRect(
        BorderLeft() + ComputedCSSPaddingLeft(),
        BorderTop() + ComputedCSSPaddingTop(),
        ClientWidth() - ComputedCSSPaddingLeft() - ComputedCSSPaddingRight(),
        ClientHeight() - ComputedCSSPaddingTop() - ComputedCSSPaddingBottom());
  }

  void AddOutlineRects(Vector<PhysicalRect>&,
                       const PhysicalOffset& additional_offset,
                       NGOutlineType) const override;

  // Use this with caution! No type checking is done!
  LayoutBox* PreviousSiblingBox() const;
  LayoutBox* PreviousInFlowSiblingBox() const;
  LayoutBox* NextSiblingBox() const;
  LayoutBox* NextInFlowSiblingBox() const;
  LayoutBox* ParentBox() const;

  // Return the previous sibling column set or spanner placeholder. Only to be
  // used on multicol container children.
  LayoutBox* PreviousSiblingMultiColumnBox() const;
  // Return the next sibling column set or spanner placeholder. Only to be used
  // on multicol container children.
  LayoutBox* NextSiblingMultiColumnBox() const;

  bool CanResize() const;

  // Like most of the other box geometries, visual and layout overflow are also
  // in the "physical coordinates in flipped block-flow direction" of the box.
  LayoutRect NoOverflowRect() const;
  LayoutRect LayoutOverflowRect() const {
    return LayoutOverflowIsSet()
               ? overflow_->layout_overflow->LayoutOverflowRect()
               : NoOverflowRect();
  }
  PhysicalRect PhysicalLayoutOverflowRect() const {
    return FlipForWritingMode(LayoutOverflowRect());
  }
  // TODO(crbug.com/962299): This is incorrect in some cases.
  IntRect PixelSnappedLayoutOverflowRect() const {
    return PixelSnappedIntRect(LayoutOverflowRect());
  }
  LayoutSize MaxLayoutOverflow() const {
    return LayoutSize(LayoutOverflowRect().MaxX(), LayoutOverflowRect().MaxY());
  }

  LayoutRect VisualOverflowRect() const;
  PhysicalRect PhysicalVisualOverflowRect() const final {
    return FlipForWritingMode(VisualOverflowRect());
  }
  LayoutUnit LogicalLeftVisualOverflow() const {
    return StyleRef().IsHorizontalWritingMode() ? VisualOverflowRect().X()
                                                : VisualOverflowRect().Y();
  }
  LayoutUnit LogicalRightVisualOverflow() const {
    return StyleRef().IsHorizontalWritingMode() ? VisualOverflowRect().MaxX()
                                                : VisualOverflowRect().MaxY();
  }

  LayoutRect SelfVisualOverflowRect() const {
    return VisualOverflowIsSet()
               ? overflow_->visual_overflow->SelfVisualOverflowRect()
               : BorderBoxRect();
  }
  PhysicalRect PhysicalSelfVisualOverflowRect() const {
    return FlipForWritingMode(SelfVisualOverflowRect());
  }
  LayoutRect ContentsVisualOverflowRect() const {
    return VisualOverflowIsSet()
               ? overflow_->visual_overflow->ContentsVisualOverflowRect()
               : LayoutRect();
  }
  PhysicalRect PhysicalContentsVisualOverflowRect() const {
    return FlipForWritingMode(ContentsVisualOverflowRect());
  }

  // Returns the visual overflow rect, expanded to the area affected by any
  // filters that paint outside of the box, in physical coordinates.
  PhysicalRect PhysicalVisualOverflowRectIncludingFilters() const;

  // These methods don't mean the box *actually* has top/left overflow. They
  // mean that *if* the box overflows, it will overflow to the top/left rather
  // than the bottom/right. This happens when child content is laid out
  // right-to-left (e.g. direction:rtl) or or bottom-to-top (e.g. direction:rtl
  // writing-mode:vertical-rl).
  virtual bool HasTopOverflow() const;
  virtual bool HasLeftOverflow() const;

  void AddLayoutOverflow(const LayoutRect&);
  void AddSelfVisualOverflow(const PhysicalRect& r) {
    AddSelfVisualOverflow(FlipForWritingMode(r));
  }
  void AddSelfVisualOverflow(const LayoutRect&);
  void AddContentsVisualOverflow(const PhysicalRect& r) {
    AddContentsVisualOverflow(FlipForWritingMode(r));
  }
  void AddContentsVisualOverflow(const LayoutRect&);

  void AddVisualEffectOverflow();
  LayoutRectOutsets ComputeVisualEffectOverflowOutsets();
  void AddVisualOverflowFromChild(const LayoutBox& child) {
    AddVisualOverflowFromChild(child, child.LocationOffset());
  }
  void AddLayoutOverflowFromChild(const LayoutBox& child) {
    AddLayoutOverflowFromChild(child, child.LocationOffset());
  }
  void AddVisualOverflowFromChild(const LayoutBox& child,
                                  const LayoutSize& delta);
  void AddLayoutOverflowFromChild(const LayoutBox& child,
                                  const LayoutSize& delta);
  void SetLayoutClientAfterEdge(LayoutUnit client_after_edge);
  LayoutUnit LayoutClientAfterEdge() const;

  void ClearLayoutOverflow();
  void ClearVisualOverflow();

  virtual void UpdateAfterLayout();

  DISABLE_CFI_PERF LayoutUnit ContentLeft() const {
    return ClientLeft() + PaddingLeft();
  }
  DISABLE_CFI_PERF LayoutUnit ContentTop() const {
    return ClientTop() + PaddingTop();
  }
  DISABLE_CFI_PERF LayoutUnit ContentWidth() const {
    // We're dealing with LayoutUnit and saturated arithmetic here, so we need
    // to guard against negative results. The value returned from clientWidth()
    // may in itself be a victim of saturated arithmetic; e.g. if both border
    // sides were sufficiently wide (close to LayoutUnit::max()).  Here we
    // subtract two padding values from that result, which is another source of
    // saturated arithmetic.
    return (ClientWidth() - PaddingLeft() - PaddingRight())
        .ClampNegativeToZero();
  }
  DISABLE_CFI_PERF LayoutUnit ContentHeight() const {
    // We're dealing with LayoutUnit and saturated arithmetic here, so we need
    // to guard against negative results. The value returned from clientHeight()
    // may in itself be a victim of saturated arithmetic; e.g. if both border
    // sides were sufficiently wide (close to LayoutUnit::max()).  Here we
    // subtract two padding values from that result, which is another source of
    // saturated arithmetic.
    return (ClientHeight() - PaddingTop() - PaddingBottom())
        .ClampNegativeToZero();
  }
  LayoutSize ContentSize() const {
    return LayoutSize(ContentWidth(), ContentHeight());
  }
  LayoutUnit ContentLogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode() ? ContentWidth()
                                                : ContentHeight();
  }
  LayoutUnit ContentLogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode() ? ContentHeight()
                                                : ContentWidth();
  }

  // CSS intrinsic sizing getters.
  // https://drafts.csswg.org/css-sizing-4/#intrinsic-size-override
  // Physical:
  bool HasOverrideIntrinsicContentWidth() const;
  bool HasOverrideIntrinsicContentHeight() const;
  LayoutUnit OverrideIntrinsicContentWidth() const;
  LayoutUnit OverrideIntrinsicContentHeight() const;
  // Logical:
  bool HasOverrideIntrinsicContentLogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode()
               ? HasOverrideIntrinsicContentWidth()
               : HasOverrideIntrinsicContentHeight();
  }
  bool HasOverrideIntrinsicContentLogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode()
               ? HasOverrideIntrinsicContentHeight()
               : HasOverrideIntrinsicContentWidth();
  }
  LayoutUnit OverrideIntrinsicContentLogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode()
               ? OverrideIntrinsicContentWidth()
               : OverrideIntrinsicContentHeight();
  }
  LayoutUnit OverrideIntrinsicContentLogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode()
               ? OverrideIntrinsicContentHeight()
               : OverrideIntrinsicContentWidth();
  }

  // Returns element-native intrinsic size. Returns kIndefiniteSize if no such
  // size.
  LayoutUnit DefaultIntrinsicContentInlineSize() const;
  LayoutUnit DefaultIntrinsicContentBlockSize() const;

  // IE extensions. Used to calculate offsetWidth/Height. Overridden by inlines
  // (LayoutFlow) to return the remaining width on a given line (and the height
  // of a single line).
  LayoutUnit OffsetWidth() const final { return frame_rect_.Width(); }
  LayoutUnit OffsetHeight() const final { return frame_rect_.Height(); }

  // TODO(crbug.com/962299): This is incorrect in some cases.
  int PixelSnappedOffsetWidth(const Element*) const final;
  int PixelSnappedOffsetHeight(const Element*) const final;

  DISABLE_CFI_PERF LayoutUnit LeftScrollbarWidth() const {
    return ShouldPlaceVerticalScrollbarOnLeft()
               // See the function for the reason of using it here.
               ? VerticalScrollbarWidthClampedToContentBox()
               : LayoutUnit();
  }
  DISABLE_CFI_PERF LayoutUnit RightScrollbarWidth() const {
    return ShouldPlaceVerticalScrollbarOnLeft()
               ? LayoutUnit()
               // See VerticalScrollbarWidthClampedToContentBox for the reason
               // of not using it here.
               : LayoutUnit(VerticalScrollbarWidth());
  }
  // The horizontal scrollbar is always at the bottom.
  DISABLE_CFI_PERF LayoutUnit BottomScrollbarHeight() const {
    return LayoutUnit(HorizontalScrollbarHeight());
  }

  // This could be
  //   IsHorizontalWritingMode() ? LeftScrollbarWidth() : TopScrollbarWidth(),
  // but LeftScrollbarWidth() is non-zero only in horizontal rtl mode, and we
  // never have scrollbar on the top, so it's just LeftScrollbarWidth().
  DISABLE_CFI_PERF LayoutUnit LogicalLeftScrollbarWidth() const {
    return LeftScrollbarWidth();
  }
  DISABLE_CFI_PERF LayoutUnit LogicalTopScrollbarHeight() const {
    return UNLIKELY(HasFlippedBlocksWritingMode()) ? RightScrollbarWidth()
                                                   : LayoutUnit();
  }

  // Physical client rect (a.k.a. PhysicalPaddingBoxRect(), defined by
  // ClientLeft, ClientTop, ClientWidth and ClientHeight) represents the
  // interior of an object excluding borders and scrollbars.
  DISABLE_CFI_PERF LayoutUnit ClientLeft() const {
    return BorderLeft() + LeftScrollbarWidth();
  }
  DISABLE_CFI_PERF LayoutUnit ClientTop() const { return BorderTop(); }
  LayoutUnit ClientWidth() const;
  LayoutUnit ClientHeight() const;
  DISABLE_CFI_PERF LayoutUnit ClientLogicalWidth() const {
    return IsHorizontalWritingMode() ? ClientWidth() : ClientHeight();
  }
  DISABLE_CFI_PERF LayoutUnit ClientLogicalHeight() const {
    return IsHorizontalWritingMode() ? ClientHeight() : ClientWidth();
  }
  DISABLE_CFI_PERF LayoutUnit ClientLogicalBottom() const {
    return BorderBefore() + LogicalTopScrollbarHeight() + ClientLogicalHeight();
  }

  // TODO(crbug.com/962299): This is incorrect in some cases.
  int PixelSnappedClientWidth() const;
  int PixelSnappedClientHeight() const;
  int PixelSnappedClientWidthWithTableSpecialBehavior() const;
  int PixelSnappedClientHeightWithTableSpecialBehavior() const;

  // scrollWidth/scrollHeight will be the same as clientWidth/clientHeight
  // unless the object has overflow:hidden/scroll/auto specified and also has
  // overflow. These methods are virtual so that objects like textareas can
  // scroll shadow content (but pretend that they are the objects that are
  // scrolling).

  // Replaced ScrollLeft/Top by using Element::GetScrollableArea to return the
  // correct ScrollableArea.
  // TODO(cathiechen): We should do the same with ScrollWidth|Height .
  virtual LayoutUnit ScrollWidth() const;
  virtual LayoutUnit ScrollHeight() const;
  // TODO(crbug.com/962299): This is incorrect in some cases.
  int PixelSnappedScrollWidth() const;
  int PixelSnappedScrollHeight() const;

  void ScrollByRecursively(const ScrollOffset& delta);
  // If makeVisibleInVisualViewport is set, the visual viewport will be scrolled
  // if required to make the rect visible.
  PhysicalRect ScrollRectToVisibleRecursive(
      const PhysicalRect&,
      mojom::blink::ScrollIntoViewParamsPtr);

  LayoutRectOutsets MarginBoxOutsets() const { return margin_box_outsets_; }
  LayoutUnit MarginTop() const override { return margin_box_outsets_.Top(); }
  LayoutUnit MarginBottom() const override {
    return margin_box_outsets_.Bottom();
  }
  LayoutUnit MarginLeft() const override { return margin_box_outsets_.Left(); }
  LayoutUnit MarginRight() const override {
    return margin_box_outsets_.Right();
  }
  void SetMargin(const NGPhysicalBoxStrut&);
  void SetMarginTop(LayoutUnit margin) { margin_box_outsets_.SetTop(margin); }
  void SetMarginBottom(LayoutUnit margin) {
    margin_box_outsets_.SetBottom(margin);
  }
  void SetMarginLeft(LayoutUnit margin) { margin_box_outsets_.SetLeft(margin); }
  void SetMarginRight(LayoutUnit margin) {
    margin_box_outsets_.SetRight(margin);
  }

  void SetMarginBefore(LayoutUnit value,
                       const ComputedStyle* override_style = nullptr) {
    LogicalMarginToPhysicalSetter(override_style).SetBefore(value);
  }
  void SetMarginAfter(LayoutUnit value,
                      const ComputedStyle* override_style = nullptr) {
    LogicalMarginToPhysicalSetter(override_style).SetAfter(value);
  }
  void SetMarginStart(LayoutUnit value,
                      const ComputedStyle* override_style = nullptr) {
    LogicalMarginToPhysicalSetter(override_style).SetStart(value);
  }
  void SetMarginEnd(LayoutUnit value,
                    const ComputedStyle* override_style = nullptr) {
    LogicalMarginToPhysicalSetter(override_style).SetEnd(value);
  }

  // The following functions are used to implement collapsing margins.
  // All objects know their maximal positive and negative margins. The formula
  // for computing a collapsed margin is |maxPosMargin| - |maxNegmargin|.
  // For a non-collapsing box, such as a leaf element, this formula will simply
  // return the margin of the element.  Blocks override the maxMarginBefore and
  // maxMarginAfter methods.
  virtual bool IsSelfCollapsingBlock() const { return false; }
  virtual LayoutUnit CollapsedMarginBefore() const { return MarginBefore(); }
  virtual LayoutUnit CollapsedMarginAfter() const { return MarginAfter(); }
  LayoutRectOutsets CollapsedMarginBoxLogicalOutsets() const {
    return LayoutRectOutsets(CollapsedMarginBefore(), LayoutUnit(),
                             CollapsedMarginAfter(), LayoutUnit());
  }

  void AbsoluteQuads(Vector<FloatQuad>&,
                     MapCoordinatesFlags mode = 0) const override;
  FloatRect LocalBoundingBoxRectForAccessibility() const final;

  void SetBoxLayoutExtraInput(const BoxLayoutExtraInput* input) {
    extra_input_ = input;
  }
  const BoxLayoutExtraInput* GetBoxLayoutExtraInput() const {
    return extra_input_;
  }

  void UpdateLayout() override;
  void Paint(const PaintInfo&) const override;

  virtual bool IsInSelfHitTestingPhase(HitTestAction hit_test_action) const {
    return hit_test_action == kHitTestForeground;
  }

  bool HitTestAllPhases(HitTestResult&,
                        const HitTestLocation&,
                        const PhysicalOffset& accumulated_offset,
                        HitTestFilter = kHitTestAll) final;
  bool NodeAtPoint(HitTestResult&,
                   const HitTestLocation&,
                   const PhysicalOffset& accumulated_offset,
                   HitTestAction) override;

  // This function calculates the preferred widths for an object.
  //
  // See INTRINSIC SIZES / PREFERRED LOGICAL WIDTHS in layout_object.h for more
  // details about those widths.
  MinMaxSizes PreferredLogicalWidths() const override;

  LayoutUnit OverrideLogicalHeight() const;
  LayoutUnit OverrideLogicalWidth() const;
  bool IsOverrideLogicalHeightDefinite() const;
  bool HasOverrideLogicalHeight() const;
  bool HasOverrideLogicalWidth() const;
  void SetOverrideLogicalHeight(LayoutUnit);
  void SetOverrideLogicalWidth(LayoutUnit);
  void ClearOverrideLogicalHeight();
  void ClearOverrideLogicalWidth();
  void ClearOverrideSize();

  LayoutUnit OverrideContentLogicalWidth() const;
  LayoutUnit OverrideContentLogicalHeight() const;

  LayoutUnit OverrideContainingBlockContentWidth() const override;
  LayoutUnit OverrideContainingBlockContentHeight() const override;
  bool HasOverrideContainingBlockContentWidth() const override;
  bool HasOverrideContainingBlockContentHeight() const override;
  LayoutUnit OverrideContainingBlockContentLogicalWidth() const;
  LayoutUnit OverrideContainingBlockContentLogicalHeight() const;
  bool HasOverrideContainingBlockContentLogicalWidth() const;
  bool HasOverrideContainingBlockContentLogicalHeight() const;
  void SetOverrideContainingBlockContentLogicalWidth(LayoutUnit);
  void SetOverrideContainingBlockContentLogicalHeight(LayoutUnit);
  void ClearOverrideContainingBlockContentSize();

  // When a percentage resolution block size override has been set, we'll use
  // that size to resolve block-size percentages on this box, rather than
  // deducing it from the containing block.
  LayoutUnit OverridePercentageResolutionBlockSize() const;
  bool HasOverridePercentageResolutionBlockSize() const;
  void SetOverridePercentageResolutionBlockSize(LayoutUnit);
  void ClearOverridePercentageResolutionBlockSize();

  // When an available inline size override has been set, we'll use that to fill
  // available inline size, rather than deducing it from the containing block
  // (and then subtract space taken up by adjacent floats).
  LayoutUnit OverrideAvailableInlineSize() const;
  bool HasOverrideAvailableInlineSize() const { return extra_input_; }

  LayoutUnit AdjustBorderBoxLogicalWidthForBoxSizing(float width) const;
  LayoutUnit AdjustBorderBoxLogicalHeightForBoxSizing(float height) const;
  LayoutUnit AdjustContentBoxLogicalWidthForBoxSizing(float width) const;
  LayoutUnit AdjustContentBoxLogicalHeightForBoxSizing(float height) const;

  // ComputedMarginValues holds the actual values for margins. It ignores
  // margin collapsing as they are handled in LayoutBlockFlow.
  // The margins are stored in logical coordinates (see COORDINATE
  // SYSTEMS in LayoutBoxModel) for use during layout.
  struct ComputedMarginValues {
    DISALLOW_NEW();
    ComputedMarginValues() = default;

    LayoutUnit before_;
    LayoutUnit after_;
    LayoutUnit start_;
    LayoutUnit end_;
  };

  // LogicalExtentComputedValues is used both for the
  // block-flow and inline-direction axis.
  struct LogicalExtentComputedValues {
    STACK_ALLOCATED();

   public:
    LogicalExtentComputedValues() = default;

    // This is the dimension in the measured direction
    // (logical height or logical width).
    LayoutUnit extent_;

    // This is the offset in the measured direction
    // (logical top or logical left).
    LayoutUnit position_;

    // |margins_| represents the margins in the measured direction.
    // Note that ComputedMarginValues has also the margins in
    // the orthogonal direction to have clearer names but they are
    // ignored in the code.
    ComputedMarginValues margins_;
  };

  // Resolve auto margins in the chosen direction of the containing block so
  // that objects can be pushed to the start, middle or end of the containing
  // block.
  void ComputeMarginsForDirection(MarginDirection for_direction,
                                  const LayoutBlock* containing_block,
                                  LayoutUnit container_width,
                                  LayoutUnit child_width,
                                  LayoutUnit& margin_start,
                                  LayoutUnit& margin_end,
                                  Length margin_start_length,
                                  Length margin_start_end) const;

  // Used to resolve margins in the containing block's block-flow direction.
  void ComputeAndSetBlockDirectionMargins(const LayoutBlock* containing_block);

  LayoutUnit OffsetFromLogicalTopOfFirstPage() const;

  // The block offset from the logical top of this object to the end of the
  // first fragmentainer it lives in. If it only lives in one fragmentainer, 0
  // is returned.
  LayoutUnit OffsetToNextPage() const {
    return rare_data_ ? rare_data_->offset_to_next_page_ : LayoutUnit();
  }
  void SetOffsetToNextPage(LayoutUnit);

  // Specify which page or column to associate with an offset, if said offset is
  // exactly at a page or column boundary.
  enum PageBoundaryRule { kAssociateWithFormerPage, kAssociateWithLatterPage };
  LayoutUnit PageLogicalHeightForOffset(LayoutUnit) const;
  bool IsPageLogicalHeightKnown() const;
  LayoutUnit PageRemainingLogicalHeightForOffset(LayoutUnit,
                                                 PageBoundaryRule) const;

  int CurrentPageNumber(LayoutUnit child_logical_top) const;

  bool CrossesPageBoundary(LayoutUnit offset, LayoutUnit logical_height) const;

  // Calculate the strut to insert in order fit content of size
  // |content_logical_height|. Usually this will merely return the distance to
  // the next fragmentainer. However, in cases where the next fragmentainer
  // isn't tall enough to fit the content, and there's a likelihood of taller
  // fragmentainers further ahead, we'll search for one and return the distance
  // to the first fragmentainer that can fit this piece of content.
  LayoutUnit CalculatePaginationStrutToFitContent(
      LayoutUnit offset,
      LayoutUnit content_logical_height) const;

  void PositionLineBox(InlineBox*);
  void MoveWithEdgeOfInlineContainerIfNecessary(bool is_horizontal);

  virtual InlineBox* CreateInlineBox();
  void DirtyLineBoxes(bool full_layout);

  // For atomic inline elements, this function returns the inline box that
  // contains us. Enables the atomic inline LayoutObject to quickly determine
  // what line it is contained on and to easily iterate over structures on the
  // line.
  //
  // InlineBoxWrapper() and FirstInlineFragment() are mutually exclusive,
  // depends on IsInLayoutNGInlineFormattingContext().
  InlineBox* InlineBoxWrapper() const;
  void SetInlineBoxWrapper(InlineBox*);
  void DeleteLineBoxWrapper();

  bool HasInlineFragments() const final;
  NGPaintFragment* FirstInlineFragment() const final;
  void SetFirstInlineFragment(NGPaintFragment*) final;
  wtf_size_t FirstInlineFragmentItemIndex() const final;
  void ClearFirstInlineFragmentItemIndex() final;
  void SetFirstInlineFragmentItemIndex(wtf_size_t) final;

  void InvalidateItems(const NGLayoutResult&);

  void SetCachedLayoutResult(scoped_refptr<const NGLayoutResult>);

  // Store one layout result (with its physical fragment) at the specified
  // index, and delete all entries following it.
  void AddLayoutResult(scoped_refptr<const NGLayoutResult>, wtf_size_t index);
  void ReplaceLayoutResult(scoped_refptr<const NGLayoutResult>,
                           wtf_size_t index);

  void ShrinkLayoutResults(wtf_size_t results_to_keep);
  void ClearLayoutResults();

  const NGLayoutResult* GetCachedLayoutResult() const;
  const NGLayoutResult* GetCachedMeasureResult() const;

  // Returns the last layout result for this block flow with the given
  // constraint space and break token, or null if it is not up-to-date or
  // otherwise unavailable.
  //
  // This method (while determining if the layout result can be reused), *may*
  // calculate the |initial_fragment_geometry| of the node.
  //
  // |out_cache_status| indicates what type of layout pass is required.
  //
  // TODO(ikilpatrick): Move this function into NGBlockNode.
  scoped_refptr<const NGLayoutResult> CachedLayoutResult(
      const NGConstraintSpace&,
      const NGBreakToken*,
      const NGEarlyBreak*,
      base::Optional<NGFragmentGeometry>* initial_fragment_geometry,
      NGLayoutCacheStatus* out_cache_status);

  const NGPhysicalBoxFragment* GetPhysicalFragment(wtf_size_t i) const;
  const FragmentData* FragmentDataFromPhysicalFragment(
      const NGPhysicalBoxFragment&) const;
  wtf_size_t PhysicalFragmentCount() const { return layout_results_.size(); }

  void SetSpannerPlaceholder(LayoutMultiColumnSpannerPlaceholder&);
  void ClearSpannerPlaceholder();
  LayoutMultiColumnSpannerPlaceholder* SpannerPlaceholder() const final {
    return rare_data_ ? rare_data_->spanner_placeholder_ : nullptr;
  }

  // A pagination strut is the amount of space needed to push an in-flow block-
  // level object (or float) to the logical top of the next page or column. It
  // will be set both for forced breaks (e.g. page-break-before:always) and soft
  // breaks (when there's not enough space in the current page / column for the
  // object). The strut is baked into the logicalTop() of the object, so that
  // logicalTop() - paginationStrut() == the original position in the previous
  // column before deciding to break.
  //
  // Pagination struts are either set in front of a block-level box (here) or
  // before a line (RootInlineBox::paginationStrut()).
  LayoutUnit PaginationStrut() const {
    return rare_data_ ? rare_data_->pagination_strut_ : LayoutUnit();
  }
  void SetPaginationStrut(LayoutUnit);
  void ResetPaginationStrut() {
    if (rare_data_)
      rare_data_->pagination_strut_ = LayoutUnit();
  }

  // Is the specified break-before or break-after value supported on this
  // object? It needs to be in-flow all the way up to a fragmentation context
  // that supports the specified value.
  bool IsBreakBetweenControllable(EBreakBetween) const;

  // Is the specified break-inside value supported on this object? It needs to
  // be contained by a fragmentation context that supports the specified value.
  bool IsBreakInsideControllable(EBreakInside) const;

  virtual EBreakBetween BreakAfter() const;
  virtual EBreakBetween BreakBefore() const;
  EBreakInside BreakInside() const;

  static bool IsForcedFragmentainerBreakValue(EBreakBetween);

  EBreakBetween ClassABreakPointValue(
      EBreakBetween previous_break_after_value) const;

  // Return true if we should insert a break in front of this box. The box needs
  // to start at a valid class A break point in order to allow a forced break.
  // To determine whether or not to break, we also need to know the break-after
  // value of the previous in-flow sibling.
  bool NeedsForcedBreakBefore(EBreakBetween previous_break_after_value) const;

  // Get the name of the start page name for this object; see
  // https://drafts.csswg.org/css-page-3/#start-page-value
  virtual const AtomicString StartPageName() const;

  // Get the name of the end page name for this object; see
  // https://drafts.csswg.org/css-page-3/#end-page-value
  virtual const AtomicString EndPageName() const;

  bool MapToVisualRectInAncestorSpaceInternal(
      const LayoutBoxModelObject* ancestor,
      TransformState&,
      VisualRectFlags = kDefaultVisualRectFlags) const override;

  LayoutUnit ContainingBlockLogicalHeightForGetComputedStyle() const;

  LayoutUnit ContainingBlockLogicalWidthForContent() const override;
  LayoutUnit ContainingBlockLogicalHeightForContent(
      AvailableLogicalHeightType) const;

  LayoutUnit ContainingBlockAvailableLineWidth() const;
  LayoutUnit PerpendicularContainingBlockLogicalHeight() const;

  virtual void UpdateLogicalWidth();
  void UpdateLogicalHeight();
  void ComputeLogicalHeight(LogicalExtentComputedValues&) const;
  virtual void ComputeLogicalHeight(LayoutUnit logical_height,
                                    LayoutUnit logical_top,
                                    LogicalExtentComputedValues&) const;
  // This function will compute the logical border-box height, without laying
  // out the box. This means that the result is only "correct" when the height
  // is explicitly specified. This function exists so that intrinsic width
  // calculations have a way to deal with children that have orthogonal flows.
  // When there is no explicit height, this function assumes a content height of
  // zero (and returns just border+padding).
  LayoutUnit ComputeLogicalHeightWithoutLayout() const;

  void ComputeLogicalWidth(LogicalExtentComputedValues&) const;

  bool StretchesToViewport() const {
    return GetDocument().InQuirksMode() && StretchesToViewportInQuirksMode();
  }

  virtual LayoutSize IntrinsicSize() const { return LayoutSize(); }
  LayoutUnit IntrinsicLogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode() ? IntrinsicSize().Width()
                                                : IntrinsicSize().Height();
  }
  LayoutUnit IntrinsicLogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode() ? IntrinsicSize().Height()
                                                : IntrinsicSize().Width();
  }
  virtual LayoutUnit IntrinsicContentLogicalHeight() const {
    return HasOverrideIntrinsicContentLogicalHeight()
               ? OverrideIntrinsicContentLogicalHeight()
               : intrinsic_content_logical_height_;
  }

  // Whether or not the element shrinks to its intrinsic width (rather than
  // filling the width of a containing block). HTML4 buttons, <select>s,
  // <input>s, legends, and floating/compact elements do this.
  bool SizesLogicalWidthToFitContent(const Length& logical_width) const;

  LayoutUnit ShrinkLogicalWidthToAvoidFloats(LayoutUnit child_margin_start,
                                             LayoutUnit child_margin_end,
                                             const LayoutBlockFlow* cb) const;
  bool AutoWidthShouldFitContent() const;

  LayoutUnit ComputeLogicalWidthUsing(
      SizeType,
      const Length& logical_width,
      LayoutUnit available_logical_width,
      const LayoutBlock* containing_block) const;
  LayoutUnit ComputeLogicalHeightUsing(
      SizeType,
      const Length& height,
      LayoutUnit intrinsic_content_height) const;
  LayoutUnit ComputeContentLogicalHeight(
      SizeType,
      const Length& height,
      LayoutUnit intrinsic_content_height) const;
  LayoutUnit ComputeContentAndScrollbarLogicalHeightUsing(
      SizeType,
      const Length& height,
      LayoutUnit intrinsic_content_height) const;
  LayoutUnit ComputeReplacedLogicalWidthUsing(SizeType,
                                              const Length& width) const;
  LayoutUnit ComputeReplacedLogicalWidthRespectingMinMaxWidth(
      LayoutUnit logical_width,
      ShouldComputePreferred = kComputeActual) const;
  LayoutUnit ComputeReplacedLogicalHeightUsing(SizeType,
                                               const Length& height) const;
  LayoutUnit ComputeReplacedLogicalHeightRespectingMinMaxHeight(
      LayoutUnit logical_height) const;

  virtual LayoutUnit ComputeReplacedLogicalWidth(
      ShouldComputePreferred = kComputeActual) const;
  virtual LayoutUnit ComputeReplacedLogicalHeight(
      LayoutUnit estimated_used_width = LayoutUnit()) const;

  virtual bool ShouldComputeSizeAsReplaced() const {
    return IsAtomicInlineLevel() && !IsInlineBlockOrInlineTable();
  }

  // Returns the size that percentage logical heights of this box should be
  // resolved against. This function will walk the ancestor chain of this
  // object to determine this size.
  //  - out_cb returns the LayoutBlock which provided the size.
  //  - out_skipped_auto_height_containing_block returns if any auto height
  //    blocks were skipped to obtain out_cb.
  LayoutUnit ContainingBlockLogicalHeightForPercentageResolution(
      LayoutBlock** out_cb = nullptr,
      bool* out_skipped_auto_height_containing_block = nullptr) const;

  bool PercentageLogicalHeightIsResolvable() const;
  LayoutUnit ComputePercentageLogicalHeight(const Length& height) const;

  // Block flows subclass availableWidth/Height to handle multi column layout
  // (shrinking the width/height available to children when laying out.)
  LayoutUnit AvailableLogicalWidth() const { return ContentLogicalWidth(); }
  LayoutUnit AvailableLogicalHeight(AvailableLogicalHeightType) const;
  LayoutUnit AvailableLogicalHeightUsing(const Length&,
                                         AvailableLogicalHeightType) const;

  // There are a few cases where we need to refer specifically to the available
  // physical width and available physical height. Relative positioning is one
  // of those cases, since left/top offsets are physical.
  LayoutUnit AvailableWidth() const {
    return StyleRef().IsHorizontalWritingMode()
               ? AvailableLogicalWidth()
               : AvailableLogicalHeight(kIncludeMarginBorderPadding);
  }
  LayoutUnit AvailableHeight() const {
    return StyleRef().IsHorizontalWritingMode()
               ? AvailableLogicalHeight(kIncludeMarginBorderPadding)
               : AvailableLogicalWidth();
  }

  int VerticalScrollbarWidth() const;
  int HorizontalScrollbarHeight() const;
  int ScrollbarLogicalWidth() const {
    return StyleRef().IsHorizontalWritingMode() ? VerticalScrollbarWidth()
                                                : HorizontalScrollbarHeight();
  }
  int ScrollbarLogicalHeight() const {
    return StyleRef().IsHorizontalWritingMode() ? HorizontalScrollbarHeight()
                                                : VerticalScrollbarWidth();
  }

  bool CanBeScrolledAndHasScrollableArea() const;
  virtual bool CanBeProgramaticallyScrolled() const;
  virtual void Autoscroll(const PhysicalOffset&);
  bool CanAutoscroll() const;
  PhysicalOffset CalculateAutoscrollDirection(
      const FloatPoint& point_in_root_frame) const;
  static LayoutBox* FindAutoscrollable(LayoutObject*,
                                       bool is_middle_click_autoscroll);

  DISABLE_CFI_PERF bool HasAutoVerticalScrollbar() const {
    return HasOverflowClip() && StyleRef().HasAutoVerticalScroll();
  }
  DISABLE_CFI_PERF bool HasAutoHorizontalScrollbar() const {
    return HasOverflowClip() && StyleRef().HasAutoHorizontalScroll();
  }
  DISABLE_CFI_PERF bool ScrollsOverflow() const {
    return HasOverflowClip() && StyleRef().ScrollsOverflow();
  }
  // We place block-direction scrollbar on the left only if the writing-mode
  // is horizontal, so ShouldPlaceVerticalScrollbarOnLeft() is the same as
  // ShouldPlaceBlockDirectionScrollbarOnLogicalLeft(). The two forms can be
  // used in different contexts, e.g. the former for physical coordinate
  // contexts, and the later for logical coordinate contexts.
  bool ShouldPlaceVerticalScrollbarOnLeft() const {
    return ShouldPlaceBlockDirectionScrollbarOnLogicalLeft();
  }
  virtual bool ShouldPlaceBlockDirectionScrollbarOnLogicalLeft() const {
    return StyleRef().ShouldPlaceBlockDirectionScrollbarOnLogicalLeft();
  }

  bool HasScrollableOverflowX() const {
    return ScrollsOverflowX() &&
           PixelSnappedScrollWidth() != PixelSnappedClientWidth();
  }
  bool HasScrollableOverflowY() const {
    return ScrollsOverflowY() &&
           PixelSnappedScrollHeight() != PixelSnappedClientHeight();
  }
  virtual bool ScrollsOverflowX() const {
    return HasOverflowClip() && StyleRef().ScrollsOverflowX();
  }
  virtual bool ScrollsOverflowY() const {
    return HasOverflowClip() && StyleRef().ScrollsOverflowY();
  }

  // Elements such as the <input> field override this to specify that they are
  // scrollable outside the context of the CSS overflow style
  virtual bool IsIntrinsicallyScrollable(
      ScrollbarOrientation orientation) const {
    return false;
  }

  bool HasUnsplittableScrollingOverflow() const;

  // Page / column breakability inside block-level objects.
  enum PaginationBreakability {
    kAllowAnyBreaks,  // No restrictions on breaking. May examine children to
                      // find possible break points.
    kForbidBreaks,  // Forbid breaks inside this object. Content cannot be split
                    // nicely into smaller pieces.
    kAvoidBreaks  // Preferably avoid breaks. If not possible, examine children
                  // to find possible break points.
  };
  virtual PaginationBreakability GetPaginationBreakability() const;

  LayoutRect LocalCaretRect(
      const InlineBox*,
      int caret_offset,
      LayoutUnit* extra_width_to_end_of_line = nullptr) const override;

  // Returns the intersection of all overflow clips which apply.
  virtual PhysicalRect OverflowClipRect(
      const PhysicalOffset& location,
      OverlayScrollbarClipBehavior = kIgnorePlatformOverlayScrollbarSize) const;
  PhysicalRect ClipRect(const PhysicalOffset& location) const;

  // This version is for legacy code that has not switched to the new physical
  // geometry yet.
  LayoutRect OverflowClipRect(const LayoutPoint& location,
                              OverlayScrollbarClipBehavior behavior =
                                  kIgnorePlatformOverlayScrollbarSize) const {
    return OverflowClipRect(PhysicalOffset(location), behavior).ToLayoutRect();
  }

  // Returns the combination of overflow clip, contain: paint clip and CSS clip
  // for this object.
  PhysicalRect ClippingRect(const PhysicalOffset& location) const;

  virtual void PaintBoxDecorationBackground(
      const PaintInfo&,
      const PhysicalOffset& paint_offset) const;
  virtual void PaintMask(const PaintInfo&,
                         const PhysicalOffset& paint_offset) const;
  void ImageChanged(WrappedImagePtr, CanDeferInvalidation) override;
  ResourcePriority ComputeResourcePriority() const final;

  void LogicalExtentAfterUpdatingLogicalWidth(const LayoutUnit& logical_top,
                                              LogicalExtentComputedValues&);

  PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;

  void RemoveFloatingOrPositionedChildFromBlockLists();

  PaintLayer* EnclosingFloatPaintingLayer() const;

  const LayoutBlock& EnclosingScrollportBox() const;

  virtual LayoutUnit FirstLineBoxBaseline() const { return LayoutUnit(-1); }
  virtual LayoutUnit InlineBlockBaseline(LineDirectionMode) const {
    return LayoutUnit(-1);
  }  // Returns -1 if we should skip this box when computing the baseline of an
     // inline-block.

  bool ShrinkToAvoidFloats() const;
  virtual bool CreatesNewFormattingContext() const { return true; }
  bool ShouldBeConsideredAsReplaced() const;

  void UpdateFragmentationInfoForChild(LayoutBox&);
  bool ChildNeedsRelayoutForPagination(const LayoutBox&) const;
  void MarkChildForPaginationRelayoutIfNeeded(LayoutBox&, SubtreeLayoutScope&);

  bool IsWritingModeRoot() const {
    return !Parent() ||
           Parent()->StyleRef().GetWritingMode() != StyleRef().GetWritingMode();
  }
  bool IsOrthogonalWritingModeRoot() const {
    return Parent() &&
           Parent()->IsHorizontalWritingMode() != IsHorizontalWritingMode();
  }
  void MarkOrthogonalWritingModeRoot();
  void UnmarkOrthogonalWritingModeRoot();

  bool IsCustomItem() const;
  bool IsCustomItemShrinkToFit() const;

  bool IsFlexItemIncludingDeprecatedAndNG() const {
    return IsFlexItemCommon() &&
           Parent()->IsFlexibleBoxIncludingDeprecatedAndNG();
  }

  // TODO(dgrogan): Replace the rest of the calls to IsFlexItem with
  // IsFlexItemIncludingNG when all the callsites can handle an item with an NG
  // parent.
  bool IsFlexItem() const {
    return IsFlexItemCommon() && Parent()->IsFlexibleBox();
  }
  bool IsFlexItemIncludingNG() const {
    return IsFlexItemCommon() && Parent()->IsFlexibleBoxIncludingNG();
  }
  bool IsFlexItemCommon() const {
    return !IsInline() && !IsFloatingOrOutOfFlowPositioned() && Parent();
  }

  bool IsGridItem() const { return Parent() && Parent()->IsLayoutGrid(); }

  bool IsMathItem() const { return Parent() && Parent()->IsMathML(); }

  LayoutUnit LineHeight(
      bool first_line,
      LineDirectionMode,
      LinePositionMode = kPositionOnContainingLine) const override;
  LayoutUnit BaselinePosition(
      FontBaseline,
      bool first_line,
      LineDirectionMode,
      LinePositionMode = kPositionOnContainingLine) const override;

  PhysicalOffset OffsetPoint(const Element* parent) const;
  LayoutUnit OffsetLeft(const Element*) const final;
  LayoutUnit OffsetTop(const Element*) const final;

  WARN_UNUSED_RESULT LayoutUnit
  FlipForWritingMode(LayoutUnit position,
                     LayoutUnit width = LayoutUnit()) const {
    // The offset is in the block direction (y for horizontal writing modes, x
    // for vertical writing modes).
    if (LIKELY(!HasFlippedBlocksWritingMode()))
      return position;
    DCHECK(!IsHorizontalWritingMode());
    return frame_rect_.Width() - (position + width);
  }
  // Inherit other flipping methods from LayoutObject.
  using LayoutObject::FlipForWritingMode;

  WARN_UNUSED_RESULT LayoutPoint
  DeprecatedFlipForWritingMode(const LayoutPoint& position) const {
    return LayoutPoint(FlipForWritingMode(position.X()), position.Y());
  }
  void DeprecatedFlipForWritingMode(LayoutRect& rect) const {
    if (LIKELY(!HasFlippedBlocksWritingMode()))
      return;
    rect = FlipForWritingMode(rect).ToLayoutRect();
  }

  // Passing |flipped_blocks_container| causes flipped-block flipping w.r.t.
  // that container, or LocationContainer() otherwise.
  PhysicalOffset PhysicalLocation(
      const LayoutBox* flipped_blocks_container = nullptr) const {
    return PhysicalLocationInternal(flipped_blocks_container
                                        ? flipped_blocks_container
                                        : LocationContainer());
  }

  // Convert a local rect in this box's blocks direction into parent's blocks
  // direction, for parent to accumulate layout or visual overflow.
  LayoutRect RectForOverflowPropagation(const LayoutRect&) const;

  LayoutRect LogicalVisualOverflowRectForPropagation() const;
  LayoutRect VisualOverflowRectForPropagation() const {
    return RectForOverflowPropagation(VisualOverflowRect());
  }
  LayoutRect LogicalLayoutOverflowRectForPropagation(
      LayoutObject* container) const;
  LayoutRect LayoutOverflowRectForPropagation(LayoutObject* container) const;

  bool HasSelfVisualOverflow() const {
    return VisualOverflowIsSet() &&
           !BorderBoxRect().Contains(
               overflow_->visual_overflow->SelfVisualOverflowRect());
  }

  bool HasVisualOverflow() const { return VisualOverflowIsSet(); }
  bool HasLayoutOverflow() const { return LayoutOverflowIsSet(); }

  // Return true if re-laying out the containing block of this object means that
  // we need to recalculate the preferred min/max logical widths of this object.
  //
  // Calculating min/max widths for an object should ideally only take itself
  // and its children as input. However, some objects don't adhere strictly to
  // this rule, and also take input from their containing block to figure out
  // their min/max widths. This is the case for e.g. shrink-to-fit containers
  // with percentage inline-axis padding. This isn't good practise, but that's
  // how it is and how it's going to stay, unless we want to undertake a
  // substantial maintenance task of the min/max preferred widths machinery.
  virtual bool NeedsPreferredWidthsRecalculation() const;

  // See README.md for an explanation of scroll origin.
  IntSize OriginAdjustmentForScrollbars() const;
  IntPoint ScrollOrigin() const;
  LayoutSize ScrolledContentOffset() const;

  // Scroll offset as snapped to physical pixels. This value should be used in
  // any values used after layout and inside "layout code" that cares about
  // where the content is displayed, rather than what the ideal offset is. For
  // most other cases ScrolledContentOffset is probably more appropriate. This
  // is the offset that's actually drawn to the screen.
  LayoutSize PixelSnappedScrolledContentOffset() const;

  // Maps from scrolling contents space to box space and apply overflow
  // clip if needed. Returns true if no clipping applied or the flattened quad
  // bounds actually intersects the clipping region. If edgeInclusive is true,
  // then this method may return true even if the resulting rect has zero area.
  //
  // When applying offsets and not clips, the TransformAccumulation is
  // respected. If there is a clip, the TransformState is flattened first.
  bool MapContentsRectToBoxSpace(
      TransformState&,
      TransformState::TransformAccumulation,
      const LayoutObject& contents,
      VisualRectFlags = kDefaultVisualRectFlags) const;

  // True if the contents scroll relative to this object. |this| must be a
  // containing block for |contents|.
  bool ContainedContentsScroll(const LayoutObject& contents) const;

  // Applies the box clip. This is like mapScrollingContentsRectToBoxSpace,
  // except it does not apply scroll.
  bool ApplyBoxClips(TransformState&,
                     TransformState::TransformAccumulation,
                     VisualRectFlags) const;

  // Maps the visual rect state |transform_state| from this box into its
  // container, applying adjustments for the given container offset,
  // scrolling, container clipping, and transform (including container
  // perspective).
  bool MapVisualRectToContainer(const LayoutObject* container_object,
                                const PhysicalOffset& container_offset,
                                const LayoutObject* ancestor,
                                VisualRectFlags,
                                TransformState&) const;

  bool HasRelativeLogicalWidth() const;
  bool HasRelativeLogicalHeight() const;

  virtual LayoutBox* CreateAnonymousBoxWithSameTypeAs(
      const LayoutObject*) const {
    NOTREACHED();
    return nullptr;
  }

  bool HasSameDirectionAs(const LayoutBox* object) const {
    return StyleRef().Direction() == object->StyleRef().Direction();
  }

  ShapeOutsideInfo* GetShapeOutsideInfo() const;

  void MarkShapeOutsideDependentsForLayout() {
    if (IsFloating())
      RemoveFloatingOrPositionedChildFromBlockLists();
  }

  void SetIntrinsicContentLogicalHeight(
      LayoutUnit intrinsic_content_logical_height) const {
    intrinsic_content_logical_height_ = intrinsic_content_logical_height;
  }

  bool CanRenderBorderImage() const;

  void MapLocalToAncestor(const LayoutBoxModelObject* ancestor,
                          TransformState&,
                          MapCoordinatesFlags) const override;
  void MapAncestorToLocal(const LayoutBoxModelObject*,
                          TransformState&,
                          MapCoordinatesFlags) const override;

  void ClearPreviousVisualRects() override;

  LayoutBlock* PercentHeightContainer() const {
    return rare_data_ ? rare_data_->percent_height_container_ : nullptr;
  }
  void SetPercentHeightContainer(LayoutBlock*);
  void RemoveFromPercentHeightContainer();
  void ClearPercentHeightDescendants();
  // For snap areas, returns the snap container that owns us.
  LayoutBox* SnapContainer() const;
  void SetSnapContainer(LayoutBox*);
  // For snap containers, returns all associated snap areas.
  SnapAreaSet* SnapAreas() const;
  void ClearSnapAreas();
  // Moves all snap areas to the new container.
  void ReassignSnapAreas(LayoutBox& new_container);

  // CustomLayoutChild only exists if this LayoutBox is a IsCustomItem (aka. a
  // child of a LayoutCustom). This is created/destroyed when this LayoutBox is
  // inserted/removed from the layout tree.
  CustomLayoutChild* GetCustomLayoutChild() const;
  void AddCustomLayoutChildIfNeeded();
  void ClearCustomLayoutChild();

  bool HitTestClippedOutByBorder(
      const HitTestLocation&,
      const PhysicalOffset& border_box_location) const;

  virtual bool HitTestOverflowControl(HitTestResult&,
                                      const HitTestLocation&,
                                      const PhysicalOffset&) const {
    return false;
  }

  // Returns true if the box intersects the viewport visible to the user.
  bool IntersectsVisibleViewport() const;

  void EnsureIsReadyForPaintInvalidation() override;
  void ClearPaintFlags() override;

  bool HasControlClip() const;

  class MutableForPainting : public LayoutObject::MutableForPainting {
   public:
    void SavePreviousSize() {
      GetLayoutBox().previous_size_ = GetLayoutBox().Size();
    }
    void SavePreviousContentBoxRectAndLayoutOverflowRect();
    void ClearPreviousContentBoxRectAndLayoutOverflowRect() {
      if (!GetLayoutBox().rare_data_)
        return;
      GetLayoutBox()
          .rare_data_->has_previous_content_box_rect_and_layout_overflow_rect_ =
          false;
    }

   protected:
    friend class LayoutBox;
    MutableForPainting(const LayoutBox& box)
        : LayoutObject::MutableForPainting(box) {}
    LayoutBox& GetLayoutBox() {
      return static_cast<LayoutBox&>(layout_object_);
    }
  };

  MutableForPainting GetMutableForPainting() const {
    return MutableForPainting(*this);
  }

  LayoutSize PreviousSize() const { return previous_size_; }
  PhysicalRect PreviousPhysicalContentBoxRect() const {
    return rare_data_ &&
                   rare_data_
                       ->has_previous_content_box_rect_and_layout_overflow_rect_
               ? rare_data_->previous_physical_content_box_rect_
               : PhysicalRect(PhysicalOffset(), PreviousSize());
  }
  PhysicalRect PreviousPhysicalLayoutOverflowRect() const {
    return rare_data_ &&
                   rare_data_
                       ->has_previous_content_box_rect_and_layout_overflow_rect_
               ? rare_data_->previous_physical_layout_overflow_rect_
               : PhysicalRect(PhysicalOffset(), PreviousSize());
  }

  // Calculates the intrinsic logical widths for this layout box.
  // https://drafts.csswg.org/css-sizing-3/#intrinsic
  //
  // intrinsicWidth is defined as:
  //     intrinsic size of content (with our border and padding) +
  //     scrollbarWidth.
  //
  // preferredWidth is defined as:
  //     fixedWidth OR (intrinsicWidth plus border and padding).
  //     Note: fixedWidth includes border and padding and scrollbarWidth.
  //
  // This is public only for use by LayoutNG. Do not call this elsewhere.
  virtual MinMaxSizes ComputeIntrinsicLogicalWidths() const = 0;

  // Returns the (maybe cached) intrinsic logical widths for this layout box.
  MinMaxSizes IntrinsicLogicalWidths() const {
    const_cast<LayoutBox*>(this)->UpdateCachedIntrinsicLogicalWidthsIfNeeded();
    return intrinsic_logical_widths_;
  }

  // If |IntrinsicLogicalWidthsDirty()| is true, recalculates the intrinsic
  // logical widths.
  void UpdateCachedIntrinsicLogicalWidthsIfNeeded();

  // LayoutNG can use this function to update our cache of intrinsic logical
  // widths when the layout object is managed by NG. Should not be called by
  // regular code.
  //
  // Also clears the "dirty" flag for the intrinsic logical widths.
  void SetIntrinsicLogicalWidthsFromNG(
      LayoutUnit intrinsic_logical_widths_percentage_resolution_block_size,
      bool depends_on_percentage_block_size,
      bool child_depends_on_percentage_block_size,
      const MinMaxSizes* sizes) {
    intrinsic_logical_widths_percentage_resolution_block_size_ =
        intrinsic_logical_widths_percentage_resolution_block_size;
    SetIntrinsicLogicalWidthsDependsOnPercentageBlockSize(
        depends_on_percentage_block_size);
    SetIntrinsicLogicalWidthsChildDependsOnPercentageBlockSize(
        child_depends_on_percentage_block_size);
    if (sizes)
      intrinsic_logical_widths_ = *sizes;
    ClearIntrinsicLogicalWidthsDirty();
  }

  // Returns what %-resolution-block-size was used in the intrinsic logical
  // widths phase.
  //
  // For non-LayoutNG code this is always LayoutUnit::Min(), and should not be
  // used for caching purposes.
  LayoutUnit IntrinsicLogicalWidthsPercentageResolutionBlockSize() const {
    return intrinsic_logical_widths_percentage_resolution_block_size_;
  }

  // Make it public.
  using LayoutObject::BackgroundIsKnownToBeObscured;

 protected:
  ~LayoutBox() override;

  virtual bool ComputeShouldClipOverflow() const;

  void WillBeDestroyed() override;

  void InsertedIntoTree() override;
  void WillBeRemovedFromTree() override;

  void StyleWillChange(StyleDifference,
                       const ComputedStyle& new_style) override;
  void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
  void UpdateFromStyle() override;

  void InLayoutNGInlineFormattingContextWillChange(bool) final;

  virtual ItemPosition SelfAlignmentNormalBehavior(
      const LayoutBox* child = nullptr) const {
    DCHECK(!child);
    return ItemPosition::kStretch;
  }

  // Returns false if it could not cheaply compute the extent (e.g. fixed
  // background), in which case the returned rect may be incorrect.
  bool GetBackgroundPaintedExtent(PhysicalRect&) const;
  virtual bool ForegroundIsKnownToBeOpaqueInRect(
      const PhysicalRect& local_rect,
      unsigned max_depth_to_test) const;
  virtual bool ComputeBackgroundIsKnownToBeObscured() const;

  virtual void ComputePositionedLogicalWidth(
      LogicalExtentComputedValues&) const;

  LayoutUnit ComputeIntrinsicLogicalWidthUsing(
      const Length& logical_width_length,
      LayoutUnit available_logical_width) const;
  LayoutUnit ComputeIntrinsicLogicalContentHeightUsing(
      const Length& logical_height_length,
      LayoutUnit intrinsic_content_height,
      LayoutUnit border_and_padding) const;

  LayoutObject* SplitAnonymousBoxesAroundChild(LayoutObject* before_child);

  virtual bool HitTestChildren(HitTestResult&,
                               const HitTestLocation&,
                               const PhysicalOffset& accumulated_offset,
                               HitTestAction);

  void InvalidatePaint(const PaintInvalidatorContext&) const override;

  bool ColumnFlexItemHasStretchAlignment() const;
  bool IsStretchingColumnFlexItem() const;
  bool HasStretchedLogicalWidth() const;

  void ExcludeScrollbars(
      PhysicalRect&,
      OverlayScrollbarClipBehavior = kIgnorePlatformOverlayScrollbarSize) const;

  LayoutUnit ContainingBlockLogicalWidthForPositioned(
      const LayoutBoxModelObject* containing_block,
      bool check_for_perpendicular_writing_mode = true) const;
  LayoutUnit ContainingBlockLogicalHeightForPositioned(
      const LayoutBoxModelObject* containing_block,
      bool check_for_perpendicular_writing_mode = true) const;

  static void ComputeBlockStaticDistance(
      Length& logical_top,
      Length& logical_bottom,
      const LayoutBox* child,
      const LayoutBoxModelObject* container_block,
      const NGBoxFragmentBuilder* = nullptr);
  static void ComputeInlineStaticDistance(
      Length& logical_left,
      Length& logical_right,
      const LayoutBox* child,
      const LayoutBoxModelObject* container_block,
      LayoutUnit container_logical_width,
      const NGBoxFragmentBuilder* = nullptr);
  static void ComputeLogicalLeftPositionedOffset(
      LayoutUnit& logical_left_pos,
      const LayoutBox* child,
      LayoutUnit logical_width_value,
      const LayoutBoxModelObject* container_block,
      LayoutUnit container_logical_width);
  static void ComputeLogicalTopPositionedOffset(
      LayoutUnit& logical_top_pos,
      const LayoutBox* child,
      LayoutUnit logical_height_value,
      const LayoutBoxModelObject* container_block,
      LayoutUnit container_logical_height);
  static bool SkipContainingBlockForPercentHeightCalculation(
      const LayoutBox* containing_block);

  PhysicalRect LocalVisualRectIgnoringVisibility() const override;

  PhysicalOffset OffsetFromContainerInternal(
      const LayoutObject*,
      bool ignore_scroll_offset) const override;

  // For atomic inlines, returns its resolved direction in text flow. Not to be
  // confused with the CSS property 'direction'.
  // Returns the CSS 'direction' property value when it is not atomic inline.
  TextDirection ResolvedDirection() const;

 private:
  inline bool LayoutOverflowIsSet() const {
    return overflow_ && overflow_->layout_overflow;
  }
  inline bool VisualOverflowIsSet() const {
    return overflow_ && overflow_->visual_overflow;
  }

  void UpdateShapeOutsideInfoAfterStyleChange(const ComputedStyle&,
                                              const ComputedStyle* old_style);
  void UpdateGridPositionAfterStyleChange(const ComputedStyle*);
  void UpdateScrollSnapMappingAfterStyleChange(const ComputedStyle& old_style);
  void ClearScrollSnapMapping();
  void AddScrollSnapMapping();

  LayoutUnit ShrinkToFitLogicalWidth(LayoutUnit available_logical_width,
                                     LayoutUnit borders_plus_padding) const;

  bool StretchesToViewportInQuirksMode() const;

  virtual void ComputePositionedLogicalHeight(
      LogicalExtentComputedValues&) const;
  void ComputePositionedLogicalWidthUsing(
      SizeType,
      const Length& logical_width,
      const LayoutBoxModelObject* container_block,
      TextDirection container_direction,
      LayoutUnit container_logical_width,
      LayoutUnit borders_plus_padding,
      const Length& logical_left,
      const Length& logical_right,
      const Length& margin_logical_left,
      const Length& margin_logical_right,
      LogicalExtentComputedValues&) const;
  void ComputePositionedLogicalHeightUsing(
      SizeType,
      Length logical_height_length,
      const LayoutBoxModelObject* container_block,
      LayoutUnit container_logical_height,
      LayoutUnit borders_plus_padding,
      LayoutUnit logical_height,
      const Length& logical_top,
      const Length& logical_bottom,
      const Length& margin_logical_top,
      const Length& margin_logical_bottom,
      LogicalExtentComputedValues&) const;

  LayoutUnit FillAvailableMeasure(LayoutUnit available_logical_width) const;
  LayoutUnit FillAvailableMeasure(LayoutUnit available_logical_width,
                                  LayoutUnit& margin_start,
                                  LayoutUnit& margin_end) const;

  LayoutBoxRareData& EnsureRareData() {
    if (!rare_data_)
      rare_data_ = MakeGarbageCollected<LayoutBoxRareData>();
    return *rare_data_.Get();
  }

  bool LogicalHeightComputesAsNone(SizeType) const;

  bool IsBox() const =
      delete;  // This will catch anyone doing an unnecessary check.

  void LocationChanged();
  void SizeChanged();

  void UpdateBackgroundAttachmentFixedStatusAfterStyleChange();

  void InflateVisualRectForFilter(TransformState&) const;
  void InflateVisualRectForFilterUnderContainer(
      TransformState&,
      const LayoutObject& container,
      const LayoutBoxModelObject* ancestor_to_stop_at) const;

  LayoutRectOutsets margin_box_outsets_;

  void AddSnapArea(LayoutBox&);
  void RemoveSnapArea(const LayoutBox&);

  // Returns true when the current recursive scroll into visible could propagate
  // to parent frame.
  bool AllowedToPropagateRecursiveScrollToParentFrame(
      const mojom::blink::ScrollIntoViewParamsPtr&);

  PhysicalRect DebugRect() const override;

  float VisualRectOutsetForRasterEffects() const override;

  // Return the width of the vertical scrollbar, unless it's larger than the
  // logical width of the content box, in which case we'll return that instead.
  // Scrollbar handling is quite bad in such situations, and this method here
  // is just to make sure that left-hand scrollbars don't mess up
  // scrollWidth. For the full story, visit http://crbug.com/724255.
  LayoutUnit VerticalScrollbarWidthClampedToContentBox() const;

  LayoutUnit FlipForWritingModeInternal(
      LayoutUnit position,
      LayoutUnit width,
      const LayoutBox* box_for_flipping) const final {
    DCHECK(!box_for_flipping || box_for_flipping == this);
    return FlipForWritingMode(position, width);
  }

  PhysicalOffset PhysicalLocationInternal(
      const LayoutBox* container_box) const {
    DCHECK_EQ(container_box, LocationContainer());
    if (LIKELY(!container_box || !container_box->HasFlippedBlocksWritingMode()))
      return PhysicalOffset(Location());

    return PhysicalOffset(
        container_box->Size().Width() - Size().Width() - Location().X(),
        Location().Y());
  }

  // The CSS border box rect for this box.
  //
  // The rectangle is in LocationContainer's physical coordinates in flipped
  // block-flow direction of LocationContainer (see the COORDINATE SYSTEMS
  // section in LayoutBoxModelObject). The location is the distance from this
  // object's border edge to the LocationContainer's border edge. Thus it
  // includes any logical top/left along with this box's margins. It doesn't
  // include transforms, relative position offsets etc.
  LayoutRect frame_rect_;

  // Previous size of frame_rect_, updated after paint invalidation.
  LayoutSize previous_size_;

  // Our intrinsic height, used for min-height: min-content etc. Maintained by
  // updateLogicalHeight. This is logicalHeight() before it is clamped to
  // min/max.
  mutable LayoutUnit intrinsic_content_logical_height_;

 protected:
  MinMaxSizes intrinsic_logical_widths_;
  LayoutUnit intrinsic_logical_widths_percentage_resolution_block_size_;

  // LayoutBoxUtils is used for the LayoutNG code querying protected methods on
  // this class, e.g. determining the static-position of OOF elements.
  friend class LayoutBoxUtils;
  friend class LayoutBoxTest;

 private:
  LogicalToPhysicalSetter<LayoutUnit, LayoutBox> LogicalMarginToPhysicalSetter(
      const ComputedStyle* override_style) {
    const auto& style = override_style ? *override_style : StyleRef();
    return LogicalToPhysicalSetter<LayoutUnit, LayoutBox>(
        style.GetWritingMode(), style.Direction(), *this,
        &LayoutBox::SetMarginTop, &LayoutBox::SetMarginRight,
        &LayoutBox::SetMarginBottom, &LayoutBox::SetMarginLeft);
  }

  std::unique_ptr<BoxOverflowModel> overflow_;

  // Extra layout input data. This one may be set during layout, and cleared
  // afterwards. Always nullptr when this object isn't in the process of being
  // laid out.
  const BoxLayoutExtraInput* extra_input_ = nullptr;

  union {
    // The inline box containing this LayoutBox, for atomic inline elements.
    // Valid only when !IsInLayoutNGInlineFormattingContext().
    InlineBox* inline_box_wrapper_;
    // The first fragment of the inline box containing this LayoutBox, for
    // atomic inline elements. Valid only when
    // IsInLayoutNGInlineFormattingContext().
    NGPaintFragment* first_paint_fragment_;
    // The index of the first fragment item associated with this object in
    // |NGFragmentItems::Items()|. Zero means there are no such item.
    // Valid only when IsInLayoutNGInlineFormattingContext().
    wtf_size_t first_fragment_item_index_;
  };

  Persistent<LayoutBoxRareData> rare_data_;
  scoped_refptr<const NGLayoutResult> measure_result_;
  Vector<scoped_refptr<const NGLayoutResult>, 1> layout_results_;
};

DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutBox, IsBox());

inline LayoutBox* LayoutBox::PreviousSiblingBox() const {
  return ToLayoutBox(PreviousSibling());
}

inline LayoutBox* LayoutBox::PreviousInFlowSiblingBox() const {
  LayoutBox* previous = PreviousSiblingBox();
  while (previous && previous->IsOutOfFlowPositioned())
    previous = previous->PreviousSiblingBox();
  return previous;
}

inline LayoutBox* LayoutBox::NextSiblingBox() const {
  return ToLayoutBox(NextSibling());
}

inline LayoutBox* LayoutBox::NextInFlowSiblingBox() const {
  LayoutBox* next = NextSiblingBox();
  while (next && next->IsOutOfFlowPositioned())
    next = next->NextSiblingBox();
  return next;
}

inline LayoutBox* LayoutBox::ParentBox() const {
  return ToLayoutBox(Parent());
}

inline LayoutBox* LayoutBox::FirstInFlowChildBox() const {
  LayoutBox* first = FirstChildBox();
  return (first && first->IsOutOfFlowPositioned())
             ? first->NextInFlowSiblingBox()
             : first;
}

inline LayoutBox* LayoutBox::FirstChildBox() const {
  return ToLayoutBox(SlowFirstChild());
}

inline LayoutBox* LayoutBox::LastChildBox() const {
  return ToLayoutBox(SlowLastChild());
}

inline LayoutBox* LayoutBox::PreviousSiblingMultiColumnBox() const {
  DCHECK(IsLayoutMultiColumnSpannerPlaceholder() || IsLayoutMultiColumnSet());
  LayoutBox* previous_box = PreviousSiblingBox();
  if (previous_box->IsLayoutFlowThread())
    return nullptr;
  return previous_box;
}

inline LayoutBox* LayoutBox::NextSiblingMultiColumnBox() const {
  DCHECK(IsLayoutMultiColumnSpannerPlaceholder() || IsLayoutMultiColumnSet());
  return NextSiblingBox();
}

inline InlineBox* LayoutBox::InlineBoxWrapper() const {
  return IsInLayoutNGInlineFormattingContext() ? nullptr : inline_box_wrapper_;
}

inline void LayoutBox::SetInlineBoxWrapper(InlineBox* box_wrapper) {
  CHECK(!IsInLayoutNGInlineFormattingContext());

  if (box_wrapper) {
    DCHECK(!inline_box_wrapper_);
    // inline_box_wrapper_ should already be nullptr. Deleting it is a safeguard
    // against security issues. Otherwise, there will two line box wrappers
    // keeping the reference to this layoutObject, and only one will be notified
    // when the layoutObject is getting destroyed. The second line box wrapper
    // will keep a stale reference.
    if (UNLIKELY(inline_box_wrapper_ != nullptr))
      DeleteLineBoxWrapper();
  }

  inline_box_wrapper_ = box_wrapper;
}

inline NGPaintFragment* LayoutBox::FirstInlineFragment() const {
  if (!IsInLayoutNGInlineFormattingContext())
    return nullptr;
  if (!RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled())
    return first_paint_fragment_;
  NOTREACHED();
  return nullptr;
}

inline wtf_size_t LayoutBox::FirstInlineFragmentItemIndex() const {
  if (!IsInLayoutNGInlineFormattingContext())
    return 0u;
  DCHECK(RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled());
  return first_fragment_item_index_;
}

inline bool LayoutBox::IsForcedFragmentainerBreakValue(
    EBreakBetween break_value) {
  return break_value == EBreakBetween::kColumn ||
         break_value == EBreakBetween::kLeft ||
         break_value == EBreakBetween::kPage ||
         break_value == EBreakBetween::kRecto ||
         break_value == EBreakBetween::kRight ||
         break_value == EBreakBetween::kVerso;
}

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_BOX_H_