summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
blob: 79b20d51a320abd6671c2514314a88822e08485a (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
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"

#include "build/chromeos_buildflags.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/editing/text_affinity.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/core/layout/geometry/writing_mode_converter.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_object_inlines.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_combine.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_disable_side_effects_scope.h"
#include "third_party/blink/renderer/core/layout/ng/ng_outline_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h"
#include "third_party/blink/renderer/core/layout/ng/table/layout_ng_table_cell.h"
#include "third_party/blink/renderer/core/paint/ng/ng_inline_paint_context.h"
#include "third_party/blink/renderer/core/paint/outline_painter.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect_outsets.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"

namespace blink {

#if DCHECK_IS_ON()
unsigned NGPhysicalBoxFragment::AllowPostLayoutScope::allow_count_ = 0;
#endif

namespace {

struct SameSizeAsNGPhysicalBoxFragment : NGPhysicalFragment {
  unsigned flags;
  wtf_size_t const_num_children;
  LayoutUnit baseline;
  LayoutUnit last_baseline;
  NGInkOverflow ink_overflow;
  NGLink children[];
};

ASSERT_SIZE(NGPhysicalBoxFragment, SameSizeAsNGPhysicalBoxFragment);

bool HasControlClip(const NGPhysicalBoxFragment& self) {
  const LayoutBox* box = DynamicTo<LayoutBox>(self.GetLayoutObject());
  return box && box->HasControlClip();
}

bool ShouldUsePositionForPointInBlockFlowDirection(
    const LayoutObject& layout_object) {
  const LayoutBlockFlow* const layout_block_flow =
      DynamicTo<LayoutBlockFlow>(layout_object);
  if (!layout_block_flow) {
    // For <tr>, see editing/selection/click-before-and-after-table.html
    return false;
  }
  if (layout_block_flow->StyleRef().SpecifiesColumns()) {
    // Columns are laid out in inline direction.
    return false;
  }
  return true;
}

inline bool IsHitTestCandidate(const NGPhysicalBoxFragment& fragment) {
  return fragment.Size().height &&
         fragment.Style().Visibility() == EVisibility::kVisible &&
         !fragment.IsFloatingOrOutOfFlowPositioned();
}

// Applies the overflow clip to |result|. For any axis that is clipped, |result|
// is reset to |no_overflow_rect|. If neither axis is clipped, nothing is
// changed.
void ApplyOverflowClip(OverflowClipAxes overflow_clip_axes,
                       const PhysicalRect& no_overflow_rect,
                       PhysicalRect* result) {
  if (overflow_clip_axes & kOverflowClipX) {
    result->SetX(no_overflow_rect.X());
    result->SetWidth(no_overflow_rect.Width());
  }
  if (overflow_clip_axes & kOverflowClipY) {
    result->SetY(no_overflow_rect.Y());
    result->SetHeight(no_overflow_rect.Height());
  }
}

NGContainingBlock<PhysicalOffset> PhysicalContainingBlock(
    NGContainerFragmentBuilder* builder,
    PhysicalSize outer_size,
    PhysicalSize inner_size,
    const NGContainingBlock<LogicalOffset>& containing_block) {
  return NGContainingBlock<PhysicalOffset>(
      containing_block.Offset().ConvertToPhysical(
          builder->Style().GetWritingDirection(), outer_size, inner_size),
      RelativeInsetToPhysical(containing_block.RelativeOffset(),
                              builder->Style().GetWritingDirection()),
      containing_block.Fragment(), containing_block.IsInsideColumnSpanner(),
      containing_block.RequiresContentBeforeBreaking());
}

NGContainingBlock<PhysicalOffset> PhysicalContainingBlock(
    NGContainerFragmentBuilder* builder,
    PhysicalSize size,
    const NGContainingBlock<LogicalOffset>& containing_block) {
  PhysicalSize containing_block_size =
      containing_block.Fragment() ? containing_block.Fragment()->Size() : size;
  return PhysicalContainingBlock(builder, size, containing_block_size,
                                 containing_block);
}

}  // namespace

// static
const NGPhysicalBoxFragment* NGPhysicalBoxFragment::Create(
    NGBoxFragmentBuilder* builder,
    WritingMode block_or_line_writing_mode) {
  const auto writing_direction = builder->GetWritingDirection();
  const NGPhysicalBoxStrut borders =
      builder->initial_fragment_geometry_->border.ConvertToPhysical(
          writing_direction);
  bool has_borders = !borders.IsZero();
  const NGPhysicalBoxStrut padding =
      builder->initial_fragment_geometry_->padding.ConvertToPhysical(
          writing_direction);
  bool has_padding = !padding.IsZero();

  const PhysicalSize physical_size =
      ToPhysicalSize(builder->Size(), builder->GetWritingMode());
  WritingModeConverter converter(writing_direction, physical_size);

  absl::optional<PhysicalRect> inflow_bounds;
  if (builder->inflow_bounds_)
    inflow_bounds = converter.ToPhysical(*builder->inflow_bounds_);

#if DCHECK_IS_ON()
  if (builder->needs_inflow_bounds_explicitly_set_ && builder->node_ &&
      builder->node_.IsScrollContainer() && !builder->IsFragmentainerBoxType())
    DCHECK(builder->is_inflow_bounds_explicitly_set_);
  if (builder->needs_may_have_descendant_above_block_start_explicitly_set_)
    DCHECK(builder->is_may_have_descendant_above_block_start_explicitly_set_);
#endif

  PhysicalRect layout_overflow = {PhysicalOffset(), physical_size};
  if (builder->node_ && !builder->is_legacy_layout_root_) {
    const NGPhysicalBoxStrut scrollbar =
        builder->initial_fragment_geometry_->scrollbar.ConvertToPhysical(
            writing_direction);
    NGLayoutOverflowCalculator calculator(
        To<NGBlockNode>(builder->node_),
        /* is_css_box */ !builder->IsFragmentainerBoxType(), borders, scrollbar,
        padding, physical_size, writing_direction);

    if (NGFragmentItemsBuilder* items_builder = builder->ItemsBuilder()) {
      calculator.AddItems(builder->GetLayoutObject(),
                          items_builder->Items(physical_size));
    }

    for (auto& child : builder->children_) {
      const auto* box_fragment =
          DynamicTo<NGPhysicalBoxFragment>(*child.fragment);
      if (!box_fragment)
        continue;

      calculator.AddChild(*box_fragment, child.offset.ConvertToPhysical(
                                             writing_direction, physical_size,
                                             box_fragment->Size()));
    }

    if (builder->table_collapsed_borders_)
      calculator.AddTableSelfRect();

    layout_overflow = calculator.Result(inflow_bounds);
  }

  // For the purposes of object allocation we have layout-overflow if it
  // differs from the fragment size.
  bool has_layout_overflow = layout_overflow != PhysicalRect({}, physical_size);

  // Omit |NGFragmentItems| if there were no items; e.g., display-lock.
  bool has_fragment_items = false;
  if (NGFragmentItemsBuilder* items_builder = builder->ItemsBuilder()) {
    if (items_builder->Size())
      has_fragment_items = true;
  }

  bool has_rare_data =
      builder->frame_set_layout_data_ || builder->mathml_paint_info_ ||
      builder->table_grid_rect_ || !builder->table_column_geometries_.empty() ||
      builder->table_collapsed_borders_ ||
      builder->table_collapsed_borders_geometry_ ||
      builder->table_cell_column_index_ ||
      !builder->table_section_row_offsets_.empty() || builder->page_name_;

  wtf_size_t num_fragment_items =
      builder->ItemsBuilder() ? builder->ItemsBuilder()->Size() : 0;
  size_t byte_size = AdditionalByteSize(
      num_fragment_items, builder->children_.size(), has_layout_overflow,
      has_borders, has_padding, inflow_bounds.has_value(), has_rare_data);

  // We store the children list inline in the fragment as a flexible
  // array. Therefore, we need to make sure to allocate enough space for
  // that array here, which requires a manual allocation + placement new.
  // The initialization of the array is done by NGPhysicalFragment;
  // we pass the buffer as a constructor argument.
  return MakeGarbageCollected<NGPhysicalBoxFragment>(
      AdditionalBytes(byte_size), PassKey(), builder, has_layout_overflow,
      layout_overflow, has_borders, borders, has_padding, padding,
      inflow_bounds, has_fragment_items, has_rare_data,
      block_or_line_writing_mode);
}

// static
const NGPhysicalBoxFragment* NGPhysicalBoxFragment::Clone(
    const NGPhysicalBoxFragment& other) {
  // The size of the new fragment shouldn't differ from the old one.
  wtf_size_t num_fragment_items = other.Items() ? other.Items()->Size() : 0;
  size_t byte_size = AdditionalByteSize(
      num_fragment_items, other.const_num_children_, other.HasLayoutOverflow(),
      other.HasBorders(), other.HasPadding(), other.HasInflowBounds(),
      other.ConstHasRareData());

  return MakeGarbageCollected<NGPhysicalBoxFragment>(
      AdditionalBytes(byte_size), PassKey(), other, other.HasLayoutOverflow(),
      other.LayoutOverflow());
}

// static
const NGPhysicalBoxFragment*
NGPhysicalBoxFragment::CloneWithPostLayoutFragments(
    const NGPhysicalBoxFragment& other,
    const absl::optional<PhysicalRect> updated_layout_overflow) {
  PhysicalRect layout_overflow = other.LayoutOverflow();
  bool has_layout_overflow = other.HasLayoutOverflow();

  if (updated_layout_overflow) {
    layout_overflow = *updated_layout_overflow;
    has_layout_overflow = layout_overflow != PhysicalRect({}, other.Size());
  }

  // The size of the new fragment shouldn't differ from the old one.
  wtf_size_t num_fragment_items = other.Items() ? other.Items()->Size() : 0;
  size_t byte_size = AdditionalByteSize(
      num_fragment_items, other.const_num_children_, has_layout_overflow,
      other.HasBorders(), other.HasPadding(), other.HasInflowBounds(),
      other.ConstHasRareData());

  const auto* cloned_fragment = MakeGarbageCollected<NGPhysicalBoxFragment>(
      AdditionalBytes(byte_size), PassKey(), other, has_layout_overflow,
      layout_overflow);

  // To ensure the fragment tree is consistent, use the post-layout fragment.
#if DCHECK_IS_ON()
  AllowPostLayoutScope allow_post_layout_scope;
#endif

  for (NGLink& child : cloned_fragment->GetMutableForCloning().Children()) {
    child.fragment = child->PostLayout();
    DCHECK(child.fragment);

    if (!child->IsFragmentainerBox())
      continue;

    // Fragmentainers don't have the concept of post-layout fragments, so if
    // this is a fragmentation context root (such as a multicol container), we
    // need to not only update its children, but also the children of the
    // children that are fragmentainers.
    auto& fragmentainer = *To<NGPhysicalBoxFragment>(child.fragment.Get());
    for (NGLink& fragmentainer_child :
         fragmentainer.GetMutableForCloning().Children()) {
      auto& old_child =
          *To<NGPhysicalBoxFragment>(fragmentainer_child.fragment.Get());
      fragmentainer_child.fragment = old_child.PostLayout();
    }
  }

  if (cloned_fragment->HasItems()) {
    // Replace box fragment items with post layout fragments.
    for (const auto& cloned_item : cloned_fragment->Items()->Items()) {
      const NGPhysicalBoxFragment* box = cloned_item.BoxFragment();
      if (!box)
        continue;
      box = box->PostLayout();
      DCHECK(box);
      cloned_item.GetMutableForCloning().ReplaceBoxFragment(*box);
    }
  }

  return cloned_fragment;
}

namespace {
template <typename T>
constexpr void AccountSizeAndPadding(size_t& current_size) {
  const size_t current_size_with_padding =
      base::bits::AlignUp(current_size, alignof(T));
  current_size = current_size_with_padding + sizeof(T);
}
}  // namespace

// static
size_t NGPhysicalBoxFragment::AdditionalByteSize(wtf_size_t num_fragment_items,
                                                 wtf_size_t num_children,
                                                 bool has_layout_overflow,
                                                 bool has_borders,
                                                 bool has_padding,
                                                 bool has_inflow_bounds,
                                                 bool has_rare_data) {
  // Padding must be 0 for flexible array members.
  static_assert(0 == (sizeof(NGPhysicalBoxFragment) % alignof(NGLink)));

  size_t additional_size = sizeof(NGLink) * num_children;
  additional_size =
      base::bits::AlignUp(additional_size, alignof(NGFragmentItems)) +
      NGFragmentItems::ByteSizeFor(num_fragment_items);

  if (has_layout_overflow)
    AccountSizeAndPadding<PhysicalRect>(additional_size);
  if (has_borders)
    AccountSizeAndPadding<NGPhysicalBoxStrut>(additional_size);
  if (has_padding)
    AccountSizeAndPadding<NGPhysicalBoxStrut>(additional_size);
  if (has_inflow_bounds)
    AccountSizeAndPadding<PhysicalRect>(additional_size);
  if (has_rare_data)
    AccountSizeAndPadding<NGPhysicalBoxFragment::RareData>(additional_size);

  return additional_size;
}

NGPhysicalBoxFragment::NGPhysicalBoxFragment(
    PassKey key,
    NGBoxFragmentBuilder* builder,
    bool has_layout_overflow,
    const PhysicalRect& layout_overflow,
    bool has_borders,
    const NGPhysicalBoxStrut& borders,
    bool has_padding,
    const NGPhysicalBoxStrut& padding,
    const absl::optional<PhysicalRect>& inflow_bounds,
    bool has_fragment_items,
    bool has_rare_data,
    WritingMode block_or_line_writing_mode)
    : NGPhysicalFragment(builder,
                         block_or_line_writing_mode,
                         kFragmentBox,
                         builder->BoxType()),
      bit_field_(ConstHasFragmentItemsFlag::encode(has_fragment_items) |
                 ConstHasRareDataFlag::encode(has_rare_data) |
                 HasDescendantsForTablePartFlag::encode(false) |
                 IsFragmentationContextRootFlag::encode(
                     builder->is_fragmentation_context_root_) |
                 IsMonolithicFlag::encode(builder->is_monolithic_)),
      const_num_children_(builder->children_.size()) {
  DCHECK(layout_object_);
  DCHECK(layout_object_->IsBoxModelObject());
  DCHECK(!builder->break_token_ || builder->break_token_->IsBlockType());

  PhysicalSize size = Size();
  const WritingModeConverter converter(
      {block_or_line_writing_mode, builder->Direction()}, size);
  wtf_size_t i = 0;
  for (auto& child : builder->children_) {
    children_[i].offset =
        converter.ToPhysical(child.offset, child.fragment->Size());
    // Fragments in |builder| are not used after |this| was constructed.
    children_[i].fragment = child.fragment.Release();
    ++i;
  }

  if (HasItems()) {
    NGFragmentItemsBuilder* items_builder = builder->ItemsBuilder();
    NGFragmentItems* items =
        const_cast<NGFragmentItems*>(ComputeItemsAddress());
    DCHECK_EQ(items_builder->GetWritingMode(), block_or_line_writing_mode);
    DCHECK_EQ(items_builder->Direction(), builder->Direction());
    absl::optional<PhysicalSize> new_size =
        items_builder->ToFragmentItems(Size(), items);
    if (new_size)
      size_ = *new_size;
  }

  bit_field_.set<HasLayoutOverflowFlag>(has_layout_overflow);
  if (has_layout_overflow) {
    *const_cast<PhysicalRect*>(ComputeLayoutOverflowAddress()) =
        layout_overflow;
  }
  SetInkOverflowType(NGInkOverflow::Type::kNotSet);
  bit_field_.set<HasBordersFlag>(has_borders);
  if (has_borders)
    *const_cast<NGPhysicalBoxStrut*>(ComputeBordersAddress()) = borders;
  bit_field_.set<HasPaddingFlag>(has_padding);
  if (has_padding)
    *const_cast<NGPhysicalBoxStrut*>(ComputePaddingAddress()) = padding;
  bit_field_.set<HasInflowBoundsFlag>(inflow_bounds.has_value());
  if (HasInflowBounds())
    *const_cast<PhysicalRect*>(ComputeInflowBoundsAddress()) = *inflow_bounds;
  if (ConstHasRareData()) {
    new (const_cast<RareData*>(ComputeRareDataAddress())) RareData(builder);
  }

  bit_field_.set<IsFirstForNodeFlag>(builder->is_first_for_node_);
  is_fieldset_container_ = builder->is_fieldset_container_;
  is_table_ng_part_ = builder->is_table_ng_part_;
  is_legacy_layout_root_ = builder->is_legacy_layout_root_;
  is_painted_atomically_ = builder->space_.IsPaintedAtomically();
  PhysicalBoxSides sides_to_include(builder->sides_to_include_,
                                    builder->GetWritingMode());
  bit_field_.set<IncludeBorderTopFlag>(sides_to_include.top);
  bit_field_.set<IncludeBorderRightFlag>(sides_to_include.right);
  bit_field_.set<IncludeBorderBottomFlag>(sides_to_include.bottom);
  bit_field_.set<IncludeBorderLeftFlag>(sides_to_include.left);
  bit_field_.set<IsInlineFormattingContextFlag>(
      builder->is_inline_formatting_context_);
  is_math_fraction_ = builder->is_math_fraction_;
  is_math_operator_ = builder->is_math_operator_;

  const bool allow_baseline = !layout_object_->ShouldApplyLayoutContainment() ||
                              layout_object_->IsTableCell();
  if (allow_baseline && builder->first_baseline_.has_value()) {
    has_first_baseline_ = true;
    first_baseline_ = *builder->first_baseline_;
  } else {
    has_first_baseline_ = false;
    first_baseline_ = LayoutUnit::Min();
  }
  if (allow_baseline && builder->last_baseline_.has_value()) {
    has_last_baseline_ = true;
    last_baseline_ = *builder->last_baseline_;
  } else {
    has_last_baseline_ = false;
    last_baseline_ = LayoutUnit::Min();
  }
  use_last_baseline_for_inline_baseline_ =
      builder->use_last_baseline_for_inline_baseline_;

  bit_field_.set<HasDescendantsForTablePartFlag>(
      const_num_children_ || NeedsOOFPositionedInfoPropagation());

#if DCHECK_IS_ON()
  CheckIntegrity();
#endif
}

NGPhysicalBoxFragment::NGPhysicalBoxFragment(
    PassKey key,
    const NGPhysicalBoxFragment& other,
    bool has_layout_overflow,
    const PhysicalRect& layout_overflow)
    : NGPhysicalFragment(other),
      bit_field_(other.bit_field_),
      const_num_children_(other.const_num_children_),
      first_baseline_(other.first_baseline_),
      last_baseline_(other.last_baseline_),
      ink_overflow_(other.InkOverflowType(), other.ink_overflow_) {
  // Shallow-clone the children.
  for (wtf_size_t i = 0; i < const_num_children_; ++i)
    children_[i] = other.children_[i];

  SetInkOverflowType(other.InkOverflowType());
  if (HasItems()) {
    NGFragmentItems* items =
        const_cast<NGFragmentItems*>(ComputeItemsAddress());
    new (items) NGFragmentItems(*other.ComputeItemsAddress());
  }
  bit_field_.set<HasLayoutOverflowFlag>(has_layout_overflow);
  if (has_layout_overflow) {
    *const_cast<PhysicalRect*>(ComputeLayoutOverflowAddress()) =
        layout_overflow;
  }
  if (HasBorders()) {
    *const_cast<NGPhysicalBoxStrut*>(ComputeBordersAddress()) =
        *other.ComputeBordersAddress();
  }
  if (HasPadding()) {
    *const_cast<NGPhysicalBoxStrut*>(ComputePaddingAddress()) =
        *other.ComputePaddingAddress();
  }
  if (HasInflowBounds()) {
    *const_cast<PhysicalRect*>(ComputeInflowBoundsAddress()) =
        *other.ComputeInflowBoundsAddress();
  }
  if (ConstHasRareData()) {
    new (const_cast<RareData*>(ComputeRareDataAddress()))
        RareData(*other.ComputeRareDataAddress());
  }
}

NGPhysicalBoxFragment::~NGPhysicalBoxFragment() {
  // Note: This function may not always be called because the dtor of
  // NGPhysicalFragment is made non-virtual for memory efficiency.
  SetInkOverflowType(ink_overflow_.Reset(InkOverflowType()));
}

void NGPhysicalBoxFragment::Dispose() {
  if (HasInkOverflow())
    SetInkOverflowType(ink_overflow_.Reset(InkOverflowType()));
  if (HasItems())
    ComputeItemsAddress()->~NGFragmentItems();
  if (ConstHasRareData())
    ComputeRareDataAddress()->~RareData();
}

// TODO(kojii): Move to ng_physical_fragment.cc
NGPhysicalFragment::OutOfFlowData*
NGPhysicalFragment::FragmentedOutOfFlowDataFromBuilder(
    NGContainerFragmentBuilder* builder) {
  DCHECK(has_fragmented_out_of_flow_data_);
  DCHECK_EQ(has_fragmented_out_of_flow_data_,
            !builder->oof_positioned_fragmentainer_descendants_.empty() ||
                !builder->multicols_with_pending_oofs_.empty());
  NGFragmentedOutOfFlowData* fragmented_data =
      MakeGarbageCollected<NGFragmentedOutOfFlowData>();
  fragmented_data->oof_positioned_fragmentainer_descendants.reserve(
      builder->oof_positioned_fragmentainer_descendants_.size());
  const PhysicalSize& size = Size();
  WritingDirectionMode writing_direction = builder->GetWritingDirection();
  const WritingModeConverter converter(writing_direction, size);
  for (const auto& descendant :
       builder->oof_positioned_fragmentainer_descendants_) {
    NGInlineContainer<PhysicalOffset> inline_container(
        descendant.inline_container.container,
        converter.ToPhysical(descendant.inline_container.relative_offset,
                             PhysicalSize()));
    NGInlineContainer<PhysicalOffset> fixedpos_inline_container(
        descendant.fixedpos_inline_container.container,
        converter.ToPhysical(
            descendant.fixedpos_inline_container.relative_offset,
            PhysicalSize()));

    // The static position should remain relative to the containing block.
    PhysicalSize containing_block_size =
        descendant.containing_block.Fragment()
            ? descendant.containing_block.Fragment()->Size()
            : size;
    const WritingModeConverter containing_block_converter(
        writing_direction, containing_block_size);

    fragmented_data->oof_positioned_fragmentainer_descendants.emplace_back(
        descendant.Node(),
        descendant.static_position.ConvertToPhysical(
            containing_block_converter),
        inline_container,
        PhysicalContainingBlock(builder, size, containing_block_size,
                                descendant.containing_block),
        PhysicalContainingBlock(builder, size,
                                descendant.fixedpos_containing_block),
        fixedpos_inline_container);
  }
  for (const auto& multicol : builder->multicols_with_pending_oofs_) {
    auto& value = multicol.value;
    NGInlineContainer<PhysicalOffset> fixedpos_inline_container(
        value->fixedpos_inline_container.container,
        converter.ToPhysical(value->fixedpos_inline_container.relative_offset,
                             PhysicalSize()));
    fragmented_data->multicols_with_pending_oofs.insert(
        multicol.key,
        MakeGarbageCollected<NGMulticolWithPendingOOFs<PhysicalOffset>>(
            value->multicol_offset.ConvertToPhysical(
                builder->Style().GetWritingDirection(), size, PhysicalSize()),
            PhysicalContainingBlock(builder, size,
                                    value->fixedpos_containing_block),
            fixedpos_inline_container));
  }
  return fragmented_data;
}

NGPhysicalBoxFragment::RareData::RareData(NGBoxFragmentBuilder* builder)
    : frame_set_layout_data(std::move(builder->frame_set_layout_data_)),
      mathml_paint_info(std::move(builder->mathml_paint_info_)) {
  if (builder->table_grid_rect_)
    table_grid_rect = *builder->table_grid_rect_;
  if (!builder->table_column_geometries_.empty())
    table_column_geometries = builder->table_column_geometries_;
  if (builder->table_collapsed_borders_)
    table_collapsed_borders = std::move(builder->table_collapsed_borders_);
  if (builder->table_collapsed_borders_geometry_) {
    table_collapsed_borders_geometry =
        std::move(builder->table_collapsed_borders_geometry_);
  }
  if (builder->table_cell_column_index_)
    table_cell_column_index = *builder->table_cell_column_index_;
  if (!builder->table_section_row_offsets_.empty()) {
    table_section_start_row_index = builder->table_section_start_row_index_;
    table_section_row_offsets = std::move(builder->table_section_row_offsets_);
  }
  page_name = builder->page_name_;
}

NGPhysicalBoxFragment::RareData::RareData(const RareData& other)
    : frame_set_layout_data(
          other.frame_set_layout_data
              ? new FrameSetLayoutData(*other.frame_set_layout_data)
              : nullptr),
      mathml_paint_info(other.mathml_paint_info
                            ? new NGMathMLPaintInfo(*other.mathml_paint_info)
                            : nullptr),
      table_grid_rect(other.table_grid_rect),
      table_column_geometries(other.table_column_geometries),
      table_collapsed_borders(other.table_collapsed_borders),
      table_collapsed_borders_geometry(
          other.table_collapsed_borders_geometry
              ? new NGTableFragmentData::CollapsedBordersGeometry(
                    *other.table_collapsed_borders_geometry)
              : nullptr),
      table_cell_column_index(other.table_cell_column_index),
      table_section_start_row_index(other.table_section_start_row_index),
      table_section_row_offsets(other.table_section_row_offsets),
      page_name(other.page_name) {}

const LayoutBox* NGPhysicalBoxFragment::OwnerLayoutBox() const {
  // TODO(layout-dev): We should probably get rid of this method, now that it
  // does nothing, apart from some checking. The checks are useful, but could be
  // moved elsewhere.
  const LayoutBox* owner_box =
      DynamicTo<LayoutBox>(GetSelfOrContainerLayoutObject());

#if DCHECK_IS_ON()
  DCHECK(owner_box);
  if (UNLIKELY(IsFragmentainerBox())) {
    if (owner_box->IsLayoutView()) {
      DCHECK(IsPageBox());
      DCHECK(To<LayoutView>(owner_box)->ShouldUsePrintingLayout());
    } else {
      DCHECK(IsColumnBox());
    }
  } else {
    // Check |this| and the |LayoutBox| that produced it are in sync.
    DCHECK(owner_box->PhysicalFragments().Contains(*this));
    DCHECK_EQ(IsFirstForNode(), this == owner_box->GetPhysicalFragment(0));
  }
#endif

  return owner_box;
}

LayoutBox* NGPhysicalBoxFragment::MutableOwnerLayoutBox() const {
  return const_cast<LayoutBox*>(OwnerLayoutBox());
}

PhysicalOffset NGPhysicalBoxFragment::OffsetFromOwnerLayoutBox() const {
  DCHECK(IsCSSBox());

  // This function uses |FragmentData|, so must be |kPrePaintClean|.
  DCHECK_GE(GetDocument().Lifecycle().GetState(),
            DocumentLifecycle::kPrePaintClean);

  const LayoutBox* owner_box = OwnerLayoutBox();
  DCHECK(owner_box);
  DCHECK(owner_box->PhysicalFragments().Contains(*this));
  if (owner_box->PhysicalFragmentCount() <= 1)
    return PhysicalOffset();

  // When LTR, compute the offset from the first fragment. The first fragment is
  // at the left top of the |LayoutBox| regardless of the writing mode.
  const auto* containing_block = owner_box->ContainingBlock();
  const ComputedStyle& containing_block_style = containing_block->StyleRef();
  if (IsLtr(containing_block_style.Direction())) {
    DCHECK_EQ(IsFirstForNode(), this == owner_box->GetPhysicalFragment(0));
    if (IsFirstForNode())
      return PhysicalOffset();

    const FragmentData* fragment_data =
        owner_box->FragmentDataFromPhysicalFragment(*this);
    DCHECK(fragment_data);
    const FragmentData& first_fragment_data = owner_box->FirstFragment();
    // All |FragmentData| for an NG block fragmented |LayoutObject| should be in
    // the same transform node that their |PaintOffset()| are in the same
    // coordinate system.
    return fragment_data->PaintOffset() - first_fragment_data.PaintOffset();
  }

  // When RTL, compute the offset from the last fragment.
  const FragmentData* fragment_data =
      owner_box->FragmentDataFromPhysicalFragment(*this);
  DCHECK(fragment_data);
  const FragmentData& last_fragment_data = fragment_data->LastFragment();
  return fragment_data->PaintOffset() - last_fragment_data.PaintOffset();
}

const NGPhysicalBoxFragment* NGPhysicalBoxFragment::PostLayout() const {
  // While side effects are disabled, new fragments are not copied to
  // |LayoutBox|. Just return the given fragment.
  if (NGDisableSideEffectsScope::IsDisabled())
    return this;

  const auto* layout_object = GetSelfOrContainerLayoutObject();
  if (UNLIKELY(!layout_object)) {
    NOTREACHED();
    return nullptr;
  }
  const auto* box = DynamicTo<LayoutBox>(layout_object);
  if (UNLIKELY(!box)) {
    DCHECK(IsInlineBox());
    return this;
  }
  if (UNLIKELY(!IsCSSBox())) {
    // We don't need to do anything special for fragments that don't correspond
    // to entries in the CSS box tree (such as fragmentainers). Any post-layout
    // fragmentainers should be found as children of the post-layout fragments
    // of the containing block.
    //
    // TODO(mstensho): Clean up this method. Rather than calling
    // GetSelfOrContainerLayoutObject() above, we first bail on !IsCSSBox(), and
    // then simply use GetLayoutObject().
    return this;
  }

  const wtf_size_t fragment_count = box->PhysicalFragmentCount();
  if (UNLIKELY(fragment_count == 0)) {
#if DCHECK_IS_ON()
    DCHECK(AllowPostLayoutScope::IsAllowed());
#endif
    return nullptr;
  }

  const NGPhysicalBoxFragment* post_layout = nullptr;
  if (fragment_count == 1) {
    post_layout = box->GetPhysicalFragment(0);
    DCHECK(post_layout);
  } else if (const auto* break_token = BreakToken()) {
    const unsigned index = break_token->SequenceNumber();
    if (index < fragment_count) {
      post_layout = box->GetPhysicalFragment(index);
      DCHECK(post_layout);
      DCHECK(!post_layout->BreakToken() ||
             post_layout->BreakToken()->SequenceNumber() == index);
    }
  } else {
    post_layout = &box->PhysicalFragments().back();
  }

  if (post_layout == this)
    return this;

// TODO(crbug.com/1241721): Revert https://crrev.com/c/3108806 to re-enable this
// DCHECK on CrOS.
#if DCHECK_IS_ON() && !BUILDFLAG(IS_CHROMEOS_ASH)
  DCHECK(AllowPostLayoutScope::IsAllowed());
#endif
  return post_layout;
}

PhysicalRect NGPhysicalBoxFragment::SelfInkOverflow() const {
  if (UNLIKELY(!CanUseFragmentsForInkOverflow())) {
    const auto* owner_box = DynamicTo<LayoutBox>(GetLayoutObject());
    return owner_box->PhysicalSelfVisualOverflowRect();
  }
  if (!HasInkOverflow())
    return LocalRect();
  return ink_overflow_.Self(InkOverflowType(), Size());
}

PhysicalRect NGPhysicalBoxFragment::ContentsInkOverflow() const {
  if (UNLIKELY(!CanUseFragmentsForInkOverflow())) {
    const auto* owner_box = DynamicTo<LayoutBox>(GetLayoutObject());
    return owner_box->PhysicalContentsVisualOverflowRect();
  }
  if (!HasInkOverflow())
    return LocalRect();
  return ink_overflow_.Contents(InkOverflowType(), Size());
}

PhysicalRect NGPhysicalBoxFragment::InkOverflow() const {
  if (UNLIKELY(!CanUseFragmentsForInkOverflow())) {
    const auto* owner_box = DynamicTo<LayoutBox>(GetLayoutObject());
    return owner_box->PhysicalVisualOverflowRect();
  }

  if (!HasInkOverflow())
    return LocalRect();

  const PhysicalRect self_rect = ink_overflow_.Self(InkOverflowType(), Size());
  const ComputedStyle& style = Style();
  if (style.HasMask())
    return self_rect;

  const OverflowClipAxes overflow_clip_axes = GetOverflowClipAxes();
  if (overflow_clip_axes == kNoOverflowClip) {
    return UnionRect(self_rect,
                     ink_overflow_.Contents(InkOverflowType(), Size()));
  }

  if (overflow_clip_axes == kOverflowClipBothAxis) {
    if (ShouldApplyOverflowClipMargin()) {
      const PhysicalRect& contents_rect =
          ink_overflow_.Contents(InkOverflowType(), Size());
      if (!contents_rect.IsEmpty()) {
        PhysicalRect result = LocalRect();
        result.Expand(OverflowClipMarginOutsets());
        result.Intersect(contents_rect);
        result.Unite(self_rect);
        return result;
      }
    }
    return self_rect;
  }

  PhysicalRect result = ink_overflow_.Contents(InkOverflowType(), Size());
  result.Unite(self_rect);
  ApplyOverflowClip(overflow_clip_axes, self_rect, &result);
  return result;
}

PhysicalRect NGPhysicalBoxFragment::OverflowClipRect(
    const PhysicalOffset& location,
    OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior) const {
  DCHECK(GetLayoutObject() && GetLayoutObject()->IsBox());
  const LayoutBox* box = To<LayoutBox>(GetLayoutObject());
  return box->OverflowClipRect(location, overlay_scrollbar_clip_behavior);
}

PhysicalRect NGPhysicalBoxFragment::OverflowClipRect(
    const PhysicalOffset& location,
    const NGBlockBreakToken* incoming_break_token,
    OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior) const {
  PhysicalRect clip_rect =
      OverflowClipRect(location, overlay_scrollbar_clip_behavior);
  if (!incoming_break_token && !BreakToken())
    return clip_rect;

  // Clip the stitched box clip rectangle against the bounds of the fragment.
  //
  // TODO(layout-dev): It's most likely better to actually store the clip
  // rectangle in each fragment, rather than post-processing the stitched clip
  // rectangle like this.
  auto writing_direction = Style().GetWritingDirection();
  const LayoutBox* box = To<LayoutBox>(GetLayoutObject());
  WritingModeConverter converter(writing_direction, PhysicalSize(box->Size()));
  // Make the clip rectangle relative to the layout box.
  clip_rect.offset -= location;
  LogicalOffset stitched_offset;
  if (incoming_break_token)
    stitched_offset.block_offset = incoming_break_token->ConsumedBlockSize();
  LogicalRect logical_fragment_rect(
      stitched_offset,
      Size().ConvertToLogical(writing_direction.GetWritingMode()));
  PhysicalRect physical_fragment_rect =
      converter.ToPhysical(logical_fragment_rect);

  // For monolithic descendants that get sliced (for certain values of "sliced";
  // keep on reading) when printing, we will keep the stitched box clip
  // rectangle, and just translate it so that it becomes relative to this
  // fragment. The problem this addresses is the fact that monolithic
  // descendants only get sliced visually and overflow nicely into the next
  // pages, whereas, internally, a monolithic element always generates only one
  // fragment. If we clip it strictly against the originating fragment, we risk
  // losing content.
  //
  // This is a work-around for the fact that we never break monolithic content
  // into fragments (which the spec actually suggests that we do in such cases).
  //
  // This work-around only makes sense when printing, since pages are simply
  // stacked in the writing direction internally when printing, so that
  // overflowing content from one page "accidentally" ends up at the right place
  // on the next page. This isn't the case for multicol for instance (where this
  // problem is "unfixable" unless we implement support for breaking monolithic
  // content into fragments), so if we're not printing, clip it against the
  // bounds of the fragment now.
  if (!GetDocument().Printing()) {
    const auto overflow_clip = box->GetOverflowClipAxes();
    PhysicalRect overflow_physical_fragment_rect = physical_fragment_rect;
    if (overflow_clip != kOverflowClipBothAxis) {
      ApplyVisibleOverflowToClipRect(overflow_clip,
                                     overflow_physical_fragment_rect);
    } else if (box->ShouldApplyOverflowClipMargin()) {
      overflow_physical_fragment_rect.Expand(OverflowClipMarginOutsets());
    }

    // Clip against the fragment's bounds.
    clip_rect.Intersect(overflow_physical_fragment_rect);
  }

  // Make the clip rectangle relative to the fragment.
  clip_rect.offset -= physical_fragment_rect.offset;
  // Make the clip rectangle relative to whatever the caller wants.
  clip_rect.offset += location;
  return clip_rect;
}

bool NGPhysicalBoxFragment::MayIntersect(
    const HitTestResult& result,
    const HitTestLocation& hit_test_location,
    const PhysicalOffset& accumulated_offset) const {
  if (const auto* box = DynamicTo<LayoutBox>(GetLayoutObject()))
    return box->MayIntersect(result, hit_test_location, accumulated_offset);
  // TODO(kojii): (!IsCSSBox() || IsInlineBox()) is not supported yet. Implement
  // if needed. For now, just return |true| not to do early return.
  return true;
}

PhysicalRect NGPhysicalBoxFragment::ScrollableOverflow(
    TextHeightType height_type) const {
  DCHECK(GetLayoutObject());
  // TODO(kojii): Scrollable overflow is computed after layout, and that the
  // tree needs to be consistent, except for Ruby where it is computed during
  // layout. It might be that |ComputeAnnotationOverflow| should move to layout
  // overflow recalc, but it is to be thought out.
  DCHECK(height_type == TextHeightType::kEmHeight || PostLayout() == this);
  if (UNLIKELY(IsLayoutObjectDestroyedOrMoved())) {
    NOTREACHED();
    return PhysicalRect();
  }
  const LayoutObject* layout_object = GetLayoutObject();
  if (height_type == TextHeightType::kEmHeight && IsRubyBox()) {
    return ScrollableOverflowFromChildren(height_type);
  }
  if (layout_object->IsBox()) {
    if (HasNonVisibleOverflow())
      return PhysicalRect({}, Size());
    // Legacy is the source of truth for overflow
    return PhysicalRect(To<LayoutBox>(layout_object)->LayoutOverflowRect());
  } else if (layout_object->IsLayoutInline()) {
    // Inline overflow is a union of child overflows.
    PhysicalRect overflow;
    if (height_type == TextHeightType::kNormalHeight || BoxType() != kInlineBox)
      overflow = PhysicalRect({}, Size());
    for (const auto& child_fragment : PostLayoutChildren()) {
      PhysicalRect child_overflow =
          child_fragment->ScrollableOverflowForPropagation(*this, height_type);
      child_overflow.offset += child_fragment.Offset();
      overflow.Unite(child_overflow);
    }
    return overflow;
  } else {
    NOTREACHED();
  }
  return PhysicalRect({}, Size());
}

PhysicalRect NGPhysicalBoxFragment::ScrollableOverflowFromChildren(
    TextHeightType height_type) const {
  // TODO(kojii): See |ScrollableOverflow|.
  DCHECK(height_type == TextHeightType::kEmHeight || PostLayout() == this);
  const NGFragmentItems* items = Items();
  if (Children().empty() && !items)
    return PhysicalRect();

  // Internal struct to share logic between child fragments and child items.
  // - Inline children's overflow expands by padding end/after.
  // - Float / OOF overflow is added as is.
  // - Children not reachable by scroll overflow do not contribute to it.
  struct ComputeOverflowContext {
    STACK_ALLOCATED();

   public:
    ComputeOverflowContext(const NGPhysicalBoxFragment& container,
                           TextHeightType height_type)
        : container(container),
          style(container.Style()),
          writing_direction(style.GetWritingDirection()),
          border_inline_start(LayoutUnit(style.BorderStartWidth())),
          border_block_start(LayoutUnit(style.BorderBeforeWidth())),
          height_type(height_type) {
      DCHECK_EQ(&style, container.GetLayoutObject()->Style(
                            container.UsesFirstLineStyle()));

      // End and under padding are added to scroll overflow of inline children.
      // https://github.com/w3c/csswg-drafts/issues/129
      DCHECK_EQ(container.HasNonVisibleOverflow(),
                container.GetLayoutObject()->HasNonVisibleOverflow());
      if (container.HasNonVisibleOverflow()) {
        const auto* layout_object = To<LayoutBox>(container.GetLayoutObject());
        padding_strut = NGBoxStrut(LayoutUnit(), layout_object->PaddingEnd(),
                                   LayoutUnit(), layout_object->PaddingAfter())
                            .ConvertToPhysical(writing_direction);
      }
    }

    // Rectangles not reachable by scroll should not be added to overflow.
    bool IsRectReachableByScroll(const PhysicalRect& rect) {
      LogicalOffset rect_logical_end =
          rect.offset.ConvertToLogical(writing_direction, container.Size(),
                                       rect.size) +
          rect.size.ConvertToLogical(writing_direction.GetWritingMode());
      return rect_logical_end.inline_offset > border_inline_start ||
             rect_logical_end.block_offset > border_block_start;
    }

    void AddChild(const PhysicalRect& child_scrollable_overflow) {
      // Do not add overflow if fragment is not reachable by scrolling.
      if (height_type == kEmHeight ||
          IsRectReachableByScroll(child_scrollable_overflow))
        children_overflow.Unite(child_scrollable_overflow);
    }

    void AddFloatingOrOutOfFlowPositionedChild(
        const NGPhysicalFragment& child,
        const PhysicalOffset& child_offset) {
      DCHECK(child.IsFloatingOrOutOfFlowPositioned());
      PhysicalRect child_scrollable_overflow =
          child.ScrollableOverflowForPropagation(container, height_type);
      child_scrollable_overflow.offset += child_offset;
      AddChild(child_scrollable_overflow);
    }

    void AddLineBoxChild(const NGPhysicalLineBoxFragment& child,
                         const PhysicalOffset& child_offset) {
      if (padding_strut)
        AddLineBoxRect({child_offset, child.Size()});
      PhysicalRect child_scrollable_overflow =
          child.ScrollableOverflow(container, style, height_type);
      child_scrollable_overflow.offset += child_offset;
      AddChild(child_scrollable_overflow);
    }

    void AddLineBoxChild(const NGFragmentItem& child,
                         const NGInlineCursor& cursor) {
      DCHECK_EQ(&child, cursor.CurrentItem());
      DCHECK_EQ(child.Type(), NGFragmentItem::kLine);
      if (padding_strut)
        AddLineBoxRect(child.RectInContainerFragment());
      const NGPhysicalLineBoxFragment* line_box = child.LineBoxFragment();
      DCHECK(line_box);
      PhysicalRect child_scrollable_overflow =
          line_box->ScrollableOverflowForLine(container, style, child, cursor,
                                              height_type);
      AddChild(child_scrollable_overflow);
    }

    void AddLineBoxRect(const PhysicalRect& linebox_rect) {
      DCHECK(padding_strut);
      if (lineboxes_enclosing_rect)
        lineboxes_enclosing_rect->Unite(linebox_rect);
      else
        lineboxes_enclosing_rect = linebox_rect;
    }

    void AddPaddingToLineBoxChildren() {
      if (lineboxes_enclosing_rect) {
        DCHECK(padding_strut);
        lineboxes_enclosing_rect->Expand(*padding_strut);
        AddChild(*lineboxes_enclosing_rect);
      }
    }

    const NGPhysicalBoxFragment& container;
    const ComputedStyle& style;
    const WritingDirectionMode writing_direction;
    const LayoutUnit border_inline_start;
    const LayoutUnit border_block_start;
    absl::optional<NGPhysicalBoxStrut> padding_strut;
    absl::optional<PhysicalRect> lineboxes_enclosing_rect;
    PhysicalRect children_overflow;
    TextHeightType height_type;
  } context(*this, height_type);

  // Traverse child items.
  if (items) {
    for (NGInlineCursor cursor(*this, *items); cursor;
         cursor.MoveToNextSkippingChildren()) {
      const NGFragmentItem* item = cursor.CurrentItem();
      if (item->Type() == NGFragmentItem::kLine) {
        context.AddLineBoxChild(*item, cursor);
        continue;
      }

      if (const NGPhysicalBoxFragment* child_box =
              item->PostLayoutBoxFragment()) {
        if (child_box->IsFloatingOrOutOfFlowPositioned()) {
          context.AddFloatingOrOutOfFlowPositionedChild(
              *child_box, item->OffsetInContainerFragment());
        }
      }
    }
  }

  // Traverse child fragments.
  const bool add_inline_children = !items && IsInlineFormattingContext();
  // Only add overflow for fragments NG has not reflected into Legacy.
  // These fragments are:
  // - inline fragments,
  // - out of flow fragments whose css container is inline box.
  // TODO(layout-dev) Transforms also need to be applied to compute overflow
  // correctly. NG is not yet transform-aware. crbug.com/855965
  for (const auto& child : PostLayoutChildren()) {
    if (child->IsFloatingOrOutOfFlowPositioned()) {
      context.AddFloatingOrOutOfFlowPositionedChild(*child, child.Offset());
    } else if (add_inline_children && child->IsLineBox()) {
      context.AddLineBoxChild(To<NGPhysicalLineBoxFragment>(*child),
                              child.Offset());
    } else if (height_type == TextHeightType::kEmHeight && IsRubyRun()) {
      PhysicalRect r = child->ScrollableOverflow(*this, height_type);
      r.offset += child.offset;
      context.AddChild(r);
    }
  }

  context.AddPaddingToLineBoxChildren();

  return context.children_overflow;
}

gfx::Vector2d NGPhysicalBoxFragment::PixelSnappedScrolledContentOffset() const {
  DCHECK(GetLayoutObject());
  return To<LayoutBox>(*GetLayoutObject()).PixelSnappedScrolledContentOffset();
}

PhysicalSize NGPhysicalBoxFragment::ScrollSize() const {
  DCHECK(GetLayoutObject());
  const LayoutBox* box = To<LayoutBox>(GetLayoutObject());
  return {box->ScrollWidth(), box->ScrollHeight()};
}

const NGPhysicalBoxFragment*
NGPhysicalBoxFragment::InlineContainerFragmentIfOutlineOwner() const {
  DCHECK(IsInlineBox());
  // In order to compute united outlines, collect all rectangles of inline
  // fragments for |LayoutInline| if |this| is the first inline fragment.
  // Otherwise return none.
  const LayoutObject* layout_object = GetLayoutObject();
  DCHECK(layout_object);
  DCHECK(layout_object->IsLayoutInline());
  NGInlineCursor cursor;
  cursor.MoveTo(*layout_object);
  DCHECK(cursor);
  if (cursor.Current().BoxFragment() == this)
    return &cursor.ContainerFragment();
  if (!cursor.IsBlockFragmented())
    return nullptr;

  // When |LayoutInline| is block fragmented, unite rectangles for each block
  // fragment. To do this, return |true| if |this| is the first inline fragment
  // of a block fragment.
  for (wtf_size_t previous_fragment_index = cursor.ContainerFragmentIndex();;) {
    cursor.MoveToNextForSameLayoutObject();
    DCHECK(cursor);
    const wtf_size_t fragment_index = cursor.ContainerFragmentIndex();
    if (cursor.Current().BoxFragment() == this) {
      if (fragment_index != previous_fragment_index)
        return &cursor.ContainerFragment();
      return nullptr;
    }
    previous_fragment_index = fragment_index;
  }
}

void NGPhysicalBoxFragment::SetInkOverflow(const PhysicalRect& self,
                                           const PhysicalRect& contents) {
  SetInkOverflowType(
      ink_overflow_.Set(InkOverflowType(), self, contents, Size()));
}

void NGPhysicalBoxFragment::RecalcInkOverflow(const PhysicalRect& contents) {
  const PhysicalRect self_rect = ComputeSelfInkOverflow();
  SetInkOverflow(self_rect, contents);
}

void NGPhysicalBoxFragment::RecalcInkOverflow() {
  DCHECK(CanUseFragmentsForInkOverflow());
  const LayoutObject* layout_object = GetSelfOrContainerLayoutObject();
  DCHECK(layout_object);
  DCHECK(
      !DisplayLockUtilities::LockedAncestorPreventingPrePaint(*layout_object));

  PhysicalRect contents_rect;
  if (!layout_object->ChildPrePaintBlockedByDisplayLock())
    contents_rect = RecalcContentsInkOverflow();
  RecalcInkOverflow(contents_rect);

  // Copy the computed values to the |OwnerBox| if |this| is the last fragment.

  // Fragmentainers may or may not have |BreakToken|s, and that
  // |CopyVisualOverflowFromFragments| cannot compute stitched coordinate for
  // them. See crbug.com/1197561.
  if (UNLIKELY(IsFragmentainerBox()))
    return;

  if (BreakToken()) {
    DCHECK_NE(this, &OwnerLayoutBox()->PhysicalFragments().back());
    return;
  }
  DCHECK_EQ(this, &OwnerLayoutBox()->PhysicalFragments().back());

  // We need to copy to the owner box, but |OwnerLayoutBox| should be equal to
  // |GetLayoutObject| except for column boxes, and since we early-return for
  // column boxes, |GetMutableLayoutObject| should do the work.
  DCHECK_EQ(MutableOwnerLayoutBox(), GetMutableLayoutObject());
  LayoutBox* owner_box = To<LayoutBox>(GetMutableLayoutObject());
  DCHECK(owner_box);
  DCHECK(owner_box->PhysicalFragments().Contains(*this));
  owner_box->CopyVisualOverflowFromFragments();
}

// Recalculate ink overflow of children. Returns the contents ink overflow
// for |this|.
PhysicalRect NGPhysicalBoxFragment::RecalcContentsInkOverflow() {
  DCHECK(GetSelfOrContainerLayoutObject());
  DCHECK(!DisplayLockUtilities::LockedAncestorPreventingPrePaint(
      *GetSelfOrContainerLayoutObject()));
  DCHECK(
      !GetSelfOrContainerLayoutObject()->ChildPrePaintBlockedByDisplayLock());

  PhysicalRect contents_rect;
  if (const NGFragmentItems* items = Items()) {
    NGInlineCursor cursor(*this, *items);
    NGInlinePaintContext child_inline_context;
    contents_rect = NGFragmentItem::RecalcInkOverflowForCursor(
        &cursor, &child_inline_context);

    // Add text decorations and emphasis mark ink over flow for combined
    // text.
    const auto* const text_combine =
        DynamicTo<LayoutNGTextCombine>(GetLayoutObject());
    if (UNLIKELY(text_combine))
      contents_rect.Unite(text_combine->RecalcContentsInkOverflow());

    // Even if this turned out to be an inline formatting context with
    // fragment items (handled above), we need to handle floating descendants.
    // If a float is block-fragmented, it is resumed as a regular box fragment
    // child, rather than becoming a fragment item.
    if (!HasFloatingDescendantsForPaint())
      return contents_rect;
  }

  for (const NGLink& child : PostLayoutChildren()) {
    const auto* child_fragment = DynamicTo<NGPhysicalBoxFragment>(child.get());
    if (!child_fragment || child_fragment->HasSelfPaintingLayer())
      continue;
    DCHECK(!child_fragment->IsOutOfFlowPositioned());

    PhysicalRect child_rect;
    if (child_fragment->CanUseFragmentsForInkOverflow()) {
      child_fragment->GetMutableForPainting().RecalcInkOverflow();
      child_rect = child_fragment->InkOverflow();
    } else {
      LayoutBox* child_layout_object = child_fragment->MutableOwnerLayoutBox();
      DCHECK(child_layout_object);
      DCHECK(!child_layout_object->CanUseFragmentsForVisualOverflow());
      child_layout_object->RecalcVisualOverflow();
      // TODO(crbug.com/1144203): Reconsider this when fragment-based ink
      // overflow supports block fragmentation. Never allow flow threads to
      // propagate overflow up to a parent.
      DCHECK_EQ(child_fragment->IsColumnBox(),
                child_layout_object->IsLayoutFlowThread());
      if (child_fragment->IsColumnBox())
        continue;
      child_rect = child_layout_object->PhysicalVisualOverflowRect();
    }
    child_rect.offset += child.offset;
    contents_rect.Unite(child_rect);
  }
  return contents_rect;
}

PhysicalRect NGPhysicalBoxFragment::ComputeSelfInkOverflow() const {
  DCHECK_EQ(PostLayout(), this);
  const ComputedStyle& style = Style();

  PhysicalRect ink_overflow(LocalRect());
  if (UNLIKELY(IsTableNGRow())) {
    // This is necessary because table-rows paints beyond border box if it
    // contains rowspanned cells.
    for (const NGLink& child : PostLayoutChildren()) {
      const auto& child_fragment = To<NGPhysicalBoxFragment>(*child);
      if (!child_fragment.IsTableNGCell())
        continue;
      const auto* child_layout_object =
          To<LayoutNGTableCell>(child_fragment.GetLayoutObject());
      if (child_layout_object->ComputedRowSpan() == 1)
        continue;
      PhysicalRect child_rect;
      if (child_fragment.CanUseFragmentsForInkOverflow())
        child_rect = child_fragment.InkOverflow();
      else
        child_rect = child_layout_object->PhysicalVisualOverflowRect();
      child_rect.offset += child.offset;
      ink_overflow.Unite(child_rect);
    }
  }

  if (!style.HasVisualOverflowingEffect())
    return ink_overflow;

  ink_overflow.Expand(style.BoxDecorationOutsets());

  if (style.HasOutline() && IsOutlineOwner()) {
    Vector<PhysicalRect> outline_rects;
    LayoutObject::OutlineInfo info;
    // The result rects are in coordinates of this object's border box.
    AddSelfOutlineRects(PhysicalOffset(),
                        style.OutlineRectsShouldIncludeBlockVisualOverflow(),
                        &outline_rects, &info);
    PhysicalRect rect = UnionRect(outline_rects);
    rect.Inflate(LayoutUnit(OutlinePainter::OutlineOutsetExtent(style, info)));
    ink_overflow.Unite(rect);
  }
  return ink_overflow;
}

#if DCHECK_IS_ON()
void NGPhysicalBoxFragment::InvalidateInkOverflow() {
  SetInkOverflowType(ink_overflow_.Invalidate(InkOverflowType()));
}
#endif

void NGPhysicalBoxFragment::AddSelfOutlineRects(
    const PhysicalOffset& additional_offset,
    NGOutlineType outline_type,
    Vector<PhysicalRect>* outline_rects,
    LayoutObject::OutlineInfo* info) const {
  if (info) {
    if (IsSvgText())
      *info = LayoutObject::OutlineInfo::GetUnzoomedFromStyle(Style());
    else
      *info = LayoutObject::OutlineInfo::GetFromStyle(Style());
  }

  AddOutlineRects(additional_offset, outline_type,
                  /* container_relative */ false, outline_rects);
}

void NGPhysicalBoxFragment::AddOutlineRects(
    const PhysicalOffset& additional_offset,
    NGOutlineType outline_type,
    Vector<PhysicalRect>* outline_rects) const {
  AddOutlineRects(additional_offset, outline_type,
                  /* container_relative */ true, outline_rects);
}

void NGPhysicalBoxFragment::AddOutlineRects(
    const PhysicalOffset& additional_offset,
    NGOutlineType outline_type,
    bool inline_container_relative,
    Vector<PhysicalRect>* outline_rects) const {
  DCHECK_EQ(PostLayout(), this);

  if (IsInlineBox()) {
    AddOutlineRectsForInlineBox(additional_offset, outline_type,
                                inline_container_relative, outline_rects);
    return;
  }
  DCHECK(IsOutlineOwner());

  // For anonymous blocks, the children add outline rects.
  if (!IsAnonymousBlock()) {
    if (IsSvgText()) {
      if (const NGFragmentItems* items = Items()) {
        outline_rects->emplace_back(PhysicalRect::EnclosingRect(
            GetLayoutObject()->ObjectBoundingBox()));
      }
    } else {
      outline_rects->emplace_back(additional_offset, Size().ToLayoutSize());
    }
  }

  if (outline_type == NGOutlineType::kIncludeBlockVisualOverflow &&
      !HasNonVisibleOverflow() && !HasControlClip(*this)) {
    // Tricky code ahead: we pass a 0,0 additional_offset to
    // AddOutlineRectsForNormalChildren, and add it in after the call.
    // This is necessary because AddOutlineRectsForNormalChildren expects
    // additional_offset to be an offset from containing_block.
    // Since containing_block is our layout object, offset must be 0,0.
    // https://crbug.com/968019
    const wtf_size_t size_before = outline_rects->size();
    AddOutlineRectsForNormalChildren(
        outline_rects, PhysicalOffset(), outline_type,
        To<LayoutBoxModelObject>(GetLayoutObject()));
    if (!additional_offset.IsZero()) {
      for (PhysicalRect& rect :
           base::make_span(*outline_rects).subspan(size_before))
        rect.offset += additional_offset;
    }
    for (const auto& child : PostLayoutChildren()) {
      if (child->IsOutOfFlowPositioned()) {
        AddOutlineRectsForDescendant(
            child, outline_rects, additional_offset, outline_type,
            To<LayoutBoxModelObject>(GetLayoutObject()));
      }
    }
  }
  // TODO(kojii): Needs inline_element_continuation logic from
  // LayoutBlockFlow::AddOutlineRects?
}

void NGPhysicalBoxFragment::AddOutlineRectsForInlineBox(
    PhysicalOffset additional_offset,
    NGOutlineType outline_type,
    bool container_relative,
    Vector<PhysicalRect>* rects) const {
  DCHECK_EQ(PostLayout(), this);
  DCHECK(IsInlineBox());

  const NGPhysicalBoxFragment* container =
      InlineContainerFragmentIfOutlineOwner();
  if (!container)
    return;

  // In order to compute united outlines, collect all rectangles of inline
  // fragments for |LayoutInline| if |this| is the first inline fragment.
  // Otherwise return none.
  //
  // When |LayoutInline| is block fragmented, unite rectangles for each block
  // fragment.
  DCHECK(GetLayoutObject());
  DCHECK(GetLayoutObject()->IsLayoutInline());
  const auto* layout_object = To<LayoutInline>(GetLayoutObject());
  const wtf_size_t initial_rects_size = rects->size();
  NGInlineCursor cursor(*container);
  cursor.MoveTo(*layout_object);
  DCHECK(cursor);
  const PhysicalOffset this_offset_in_container =
      cursor.Current()->OffsetInContainerFragment();
#if DCHECK_IS_ON()
  bool has_this_fragment = false;
#endif
  for (; cursor; cursor.MoveToNextForSameLayoutObject()) {
    const NGInlineCursorPosition& current = cursor.Current();
#if DCHECK_IS_ON()
    has_this_fragment = has_this_fragment || current.BoxFragment() == this;
#endif
    if (!current.Size().IsZero()) {
      const NGPhysicalBoxFragment* fragment = current.BoxFragment();
      DCHECK(fragment);
      if (!fragment->IsOpaque() && !fragment->IsSvg())
        rects->push_back(current.RectInContainerFragment());
    }

    // Add descendants if any, in the container-relative coordinate.
    if (!current.HasChildren())
      continue;
    NGInlineCursor descendants = cursor.CursorForDescendants();
    AddOutlineRectsForCursor(rects, PhysicalOffset(), outline_type,
                             layout_object, &descendants);
  }
#if DCHECK_IS_ON()
  DCHECK(has_this_fragment);
#endif
  DCHECK_GE(rects->size(), initial_rects_size);
  if (rects->size() <= initial_rects_size)
    return;

  // At this point, |rects| are in the container coordinate space.
  // Adjust the rectangles using |additional_offset| and |container_relative|.
  if (!container_relative)
    additional_offset -= this_offset_in_container;
  if (additional_offset.IsZero())
    return;
  for (PhysicalRect& rect :
       base::make_span(rects->begin() + initial_rects_size, rects->end()))
    rect.offset += additional_offset;
}

PositionWithAffinity NGPhysicalBoxFragment::PositionForPoint(
    PhysicalOffset point) const {
  if (layout_object_->IsBox() && !layout_object_->IsLayoutNGObject()) {
    // Layout engine boundary. Enter legacy PositionForPoint().
    return layout_object_->PositionForPoint(point);
  }

  const PhysicalOffset point_in_contents =
      IsScrollContainer()
          ? point + PhysicalOffset(PixelSnappedScrolledContentOffset())
          : point;

  if (!layout_object_->ChildPaintBlockedByDisplayLock()) {
    if (const NGFragmentItems* items = Items()) {
      NGInlineCursor cursor(*this, *items);
      if (const PositionWithAffinity position =
              cursor.PositionForPointInInlineFormattingContext(
                  point_in_contents, *this))
        return AdjustForEditingBoundary(position);
      return layout_object_->CreatePositionWithAffinity(0);
    }
  }

  if (IsA<LayoutBlockFlow>(*layout_object_) &&
      layout_object_->ChildrenInline()) {
    // Here |this| may have out-of-flow children without inline children, we
    // don't find closest child of |point| for out-of-flow children.
    // See WebFrameTest.SmartClipData
    return layout_object_->CreatePositionWithAffinity(0);
  }

  if (layout_object_->IsTable())
    return PositionForPointInTable(point_in_contents);

  if (ShouldUsePositionForPointInBlockFlowDirection(*layout_object_))
    return PositionForPointInBlockFlowDirection(point_in_contents);

  return PositionForPointByClosestChild(point_in_contents);
}

PositionWithAffinity NGPhysicalBoxFragment::PositionForPointByClosestChild(
    PhysicalOffset point_in_contents) const {
  if (layout_object_->ChildPaintBlockedByDisplayLock()) {
    // If this node is DisplayLocked, then Children() will have invalid layout
    // information.
    return AdjustForEditingBoundary(
        FirstPositionInOrBeforeNode(*layout_object_->GetNode()));
  }

  NGLink closest_child = {nullptr};
  LayoutUnit shortest_distance = LayoutUnit::Max();
  bool found_hit_test_candidate = false;
  const PhysicalSize pixel_size(LayoutUnit(1), LayoutUnit(1));
  const PhysicalRect point_rect(point_in_contents, pixel_size);

  // This is a general-purpose algorithm for finding the nearest child. There
  // may be cases where want to introduce specialized algorithms that e.g. takes
  // the progression direction into account (so that we can break earlier, or
  // even add special behavior). Children in block containers progress in the
  // block direction, for instance, while table cells progress in the inline
  // direction. Flex containers may progress in the inline direction, reverse
  // inline direction, block direction or reverse block direction. Multicol
  // containers progress both in the inline direction (columns) and block
  // direction (column rows and spanners).
  for (const NGLink& child : Children()) {
    const auto& box_fragment = To<NGPhysicalBoxFragment>(*child.fragment);
    bool is_hit_test_candidate = IsHitTestCandidate(box_fragment);
    if (!is_hit_test_candidate) {
      if (found_hit_test_candidate)
        continue;
      // We prefer valid hit-test candidates, but if there are no such children,
      // we'll lower our requirements somewhat. The exact reasoning behind the
      // details here is unknown, but it is something that evolved during
      // WebKit's early years.
      if (box_fragment.Style().Visibility() != EVisibility::kVisible ||
          (box_fragment.Children().empty() && !box_fragment.IsBlockFlow()))
        continue;
    }

    PhysicalRect child_rect(child.offset, child->Size());
    LayoutUnit horizontal_distance;
    if (child_rect.X() > point_rect.X())
      horizontal_distance = child_rect.X() - point_rect.X();
    else if (point_rect.Right() > child_rect.Right())
      horizontal_distance = point_rect.Right() - child_rect.Right();
    LayoutUnit vertical_distance;
    if (child_rect.Y() > point_rect.Y())
      vertical_distance = child_rect.Y() - point_rect.Y();
    else if (point_rect.Bottom() > child_rect.Bottom())
      vertical_distance = point_rect.Bottom() - child_rect.Bottom();

    if (!horizontal_distance && !vertical_distance) {
      // We actually hit a child. We're done.
      closest_child = child;
      break;
    }

    const LayoutUnit distance = horizontal_distance * horizontal_distance +
                                vertical_distance * vertical_distance;

    if (shortest_distance > distance ||
        (is_hit_test_candidate && !found_hit_test_candidate)) {
      // This child is either closer to the point than any previous child, or
      // this is the first child that is an actual hit-test candidate.
      shortest_distance = distance;
      closest_child = child;
      found_hit_test_candidate = is_hit_test_candidate;
    }
  }

  if (!closest_child.fragment)
    return layout_object_->FirstPositionInOrBeforeThis();
  return To<NGPhysicalBoxFragment>(*closest_child)
      .PositionForPoint(point_in_contents - closest_child.offset);
}

PositionWithAffinity
NGPhysicalBoxFragment::PositionForPointInBlockFlowDirection(
    PhysicalOffset point_in_contents) const {
  // Note: Children of <table> and "columns" are not laid out in block flow
  // direction.
  DCHECK(!layout_object_->IsTable()) << this;
  DCHECK(ShouldUsePositionForPointInBlockFlowDirection(*layout_object_))
      << this;

  if (layout_object_->ChildPaintBlockedByDisplayLock()) {
    // If this node is DisplayLocked, then Children() will have invalid layout
    // information.
    return AdjustForEditingBoundary(
        FirstPositionInOrBeforeNode(*layout_object_->GetNode()));
  }

  const bool blocks_are_flipped = Style().IsFlippedBlocksWritingMode();
  WritingModeConverter converter(Style().GetWritingDirection(), Size());
  const LogicalOffset logical_point_in_contents =
      converter.ToLogical(point_in_contents, PhysicalSize());

  // Loop over block children to find a child logically below
  // |point_in_contents|.
  const NGLink* last_candidate_box = nullptr;
  for (const NGLink& child : Children()) {
    const auto& box_fragment = To<NGPhysicalBoxFragment>(*child.fragment);
    if (!IsHitTestCandidate(box_fragment))
      continue;
    // We hit child if our click is above the bottom of its padding box (like
    // IE6/7 and FF3).
    const LogicalRect logical_child_rect =
        converter.ToLogical(PhysicalRect(child.offset, box_fragment.Size()));
    if (logical_point_in_contents.block_offset <
            logical_child_rect.BlockEndOffset() ||
        (blocks_are_flipped && logical_point_in_contents.block_offset ==
                                   logical_child_rect.BlockEndOffset())) {
      // |child| is logically below |point_in_contents|.
      return PositionForPointRespectingEditingBoundaries(
          To<NGPhysicalBoxFragment>(*child.fragment),
          point_in_contents - child.offset);
    }

    // |last_candidate_box| is logical above |point_in_contents|.
    last_candidate_box = &child;
  }

  // Here all children are logically above |point_in_contents|.
  if (last_candidate_box) {
    // editing/selection/block-with-positioned-lastchild.html reaches here.
    return PositionForPointRespectingEditingBoundaries(
        To<NGPhysicalBoxFragment>(*last_candidate_box->fragment),
        point_in_contents - last_candidate_box->offset);
  }

  // We only get here if there are no hit test candidate children below the
  // click.
  return PositionForPointByClosestChild(point_in_contents);
}

PositionWithAffinity NGPhysicalBoxFragment::PositionForPointInTable(
    PhysicalOffset point_in_contents) const {
  DCHECK(layout_object_->IsTable()) << this;
  if (!layout_object_->NonPseudoNode())
    return PositionForPointByClosestChild(point_in_contents);

  // Adjust for writing-mode:vertical-rl
  const LayoutUnit adjusted_left = Style().IsFlippedBlocksWritingMode()
                                       ? Size().width - point_in_contents.left
                                       : point_in_contents.left;
  if (adjusted_left < 0 || adjusted_left > Size().width ||
      point_in_contents.top < 0 || point_in_contents.top > Size().height) {
    // |point_in_contents| is outside of <table>.
    // See editing/selection/click-before-and-after-table.html
    if (adjusted_left <= Size().width / 2)
      return layout_object_->FirstPositionInOrBeforeThis();
    return layout_object_->LastPositionInOrAfterThis();
  }

  return PositionForPointByClosestChild(point_in_contents);
}

PositionWithAffinity
NGPhysicalBoxFragment::PositionForPointRespectingEditingBoundaries(
    const NGPhysicalBoxFragment& child,
    PhysicalOffset point_in_child) const {
  Node* const child_node = child.NonPseudoNode();
  if (!child.IsCSSBox() || !child_node)
    return child.PositionForPoint(point_in_child);

  // First make sure that the editability of the parent and child agree.
  // TODO(layout-dev): Could we just walk the DOM tree instead here?
  const LayoutObject* ancestor = layout_object_;
  while (ancestor && !ancestor->NonPseudoNode())
    ancestor = ancestor->Parent();
  if (!ancestor || !ancestor->Parent() ||
      (ancestor->HasLayer() && ancestor->Parent()->IsLayoutView()) ||
      IsEditable(*ancestor->NonPseudoNode()) == IsEditable(*child_node)) {
    return child.PositionForPoint(point_in_child);
  }

  // If editiability isn't the same in the ancestor and the child, then we
  // return a visible position just before or after the child, whichever side is
  // closer.
  WritingModeConverter converter(child.Style().GetWritingDirection(),
                                 child.Size());
  const LogicalOffset logical_point_in_child =
      converter.ToLogical(point_in_child, PhysicalSize());
  const LayoutUnit logical_child_inline_size =
      converter.ToLogical(child.Size()).inline_size;
  if (logical_point_in_child.inline_offset < logical_child_inline_size / 2)
    return child.GetLayoutObject()->PositionBeforeThis();
  return child.GetLayoutObject()->PositionAfterThis();
}

NGPhysicalBoxStrut NGPhysicalBoxFragment::OverflowClipMarginOutsets() const {
  DCHECK(Style().OverflowClipMargin());
  DCHECK(ShouldApplyOverflowClipMargin());
  DCHECK(!IsScrollContainer());

  const auto& overflow_clip_margin = Style().OverflowClipMargin();
  NGPhysicalBoxStrut outsets;

  // First inset the overflow rect based on the reference box. The
  // |child_overflow_rect| initialized above assumes clipping to
  // border-box.
  switch (overflow_clip_margin->GetReferenceBox()) {
    case StyleOverflowClipMargin::ReferenceBox::kBorderBox:
      break;
    case StyleOverflowClipMargin::ReferenceBox::kPaddingBox:
      outsets -= Borders();
      break;
    case StyleOverflowClipMargin::ReferenceBox::kContentBox:
      outsets -= Borders();
      outsets -= Padding();
      break;
  }

  // Now expand the rect based on the given margin. The margin only
  // applies if the side is a painted with this child fragment.
  outsets += NGPhysicalBoxStrut(overflow_clip_margin->GetMargin());
  outsets.TruncateSides(SidesToInclude());

  return outsets;
}

#if DCHECK_IS_ON()
NGPhysicalBoxFragment::AllowPostLayoutScope::AllowPostLayoutScope() {
  ++allow_count_;
}

NGPhysicalBoxFragment::AllowPostLayoutScope::~AllowPostLayoutScope() {
  DCHECK(allow_count_);
  --allow_count_;
}

void NGPhysicalBoxFragment::CheckSameForSimplifiedLayout(
    const NGPhysicalBoxFragment& other,
    bool check_same_block_size,
    bool check_no_fragmentation) const {
  DCHECK_EQ(layout_object_, other.layout_object_);

  LogicalSize size = size_.ConvertToLogical(Style().GetWritingMode());
  LogicalSize other_size =
      other.size_.ConvertToLogical(Style().GetWritingMode());
  DCHECK_EQ(size.inline_size, other_size.inline_size);
  if (check_same_block_size)
    DCHECK_EQ(size.block_size, other_size.block_size);

  if (check_no_fragmentation) {
    // "simplified" layout doesn't work within a fragmentation context.
    DCHECK(!break_token_ && !other.break_token_);
  }

  DCHECK_EQ(type_, other.type_);
  DCHECK_EQ(sub_type_, other.sub_type_);
  DCHECK_EQ(style_variant_, other.style_variant_);
  DCHECK_EQ(is_hidden_for_paint_, other.is_hidden_for_paint_);
  DCHECK_EQ(is_opaque_, other.is_opaque_);
  DCHECK_EQ(is_block_in_inline_, other.is_block_in_inline_);
  DCHECK_EQ(is_math_fraction_, other.is_math_fraction_);
  DCHECK_EQ(is_math_operator_, other.is_math_operator_);

  // |has_floating_descendants_for_paint_| can change during simplified layout.
  DCHECK_EQ(may_have_descendant_above_block_start_,
            other.may_have_descendant_above_block_start_);
  DCHECK_EQ(depends_on_percentage_block_size_,
            other.depends_on_percentage_block_size_);
  DCHECK_EQ(bit_field_.get<HasDescendantsForTablePartFlag>(),
            other.bit_field_.get<HasDescendantsForTablePartFlag>());
  DCHECK_EQ(IsFragmentationContextRoot(), other.IsFragmentationContextRoot());

  DCHECK_EQ(is_fieldset_container_, other.is_fieldset_container_);
  DCHECK_EQ(is_table_ng_part_, other.is_table_ng_part_);
  DCHECK_EQ(is_legacy_layout_root_, other.is_legacy_layout_root_);
  DCHECK_EQ(is_painted_atomically_, other.is_painted_atomically_);
  DCHECK_EQ(has_collapsed_borders_, other.has_collapsed_borders_);

  DCHECK_EQ(HasItems(), other.HasItems());
  DCHECK_EQ(IsInlineFormattingContext(), other.IsInlineFormattingContext());
  DCHECK_EQ(IncludeBorderTop(), other.IncludeBorderTop());
  DCHECK_EQ(IncludeBorderRight(), other.IncludeBorderRight());
  DCHECK_EQ(IncludeBorderBottom(), other.IncludeBorderBottom());
  DCHECK_EQ(IncludeBorderLeft(), other.IncludeBorderLeft());

  // The oof_positioned_descendants_ vector can change during "simplified"
  // layout. This occurs when an OOF-descendant changes from "fixed" to
  // "absolute" (or visa versa) changing its containing block.

  // Legacy layout can (incorrectly) shift baseline position(s) during
  // "simplified" layout.
  DCHECK(IsLegacyLayoutRoot() || FirstBaseline() == other.FirstBaseline());
  DCHECK(IsLegacyLayoutRoot() || LastBaseline() == other.LastBaseline());

  if (IsTableNG()) {
    DCHECK_EQ(TableGridRect(), other.TableGridRect());

    if (TableColumnGeometries()) {
      DCHECK(other.TableColumnGeometries());
      DCHECK(*TableColumnGeometries() == *other.TableColumnGeometries());
    } else {
      DCHECK(!other.TableColumnGeometries());
    }

    DCHECK_EQ(TableCollapsedBorders(), other.TableCollapsedBorders());

    if (TableCollapsedBordersGeometry()) {
      DCHECK(other.TableCollapsedBordersGeometry());
      TableCollapsedBordersGeometry()->CheckSameForSimplifiedLayout(
          *other.TableCollapsedBordersGeometry());
    } else {
      DCHECK(!other.TableCollapsedBordersGeometry());
    }
  }

  if (IsTableNGCell())
    DCHECK_EQ(TableCellColumnIndex(), other.TableCellColumnIndex());

  DCHECK(Borders() == other.Borders());
  DCHECK(Padding() == other.Padding());
  // NOTE: The |InflowBounds| can change if scrollbars are added/removed.
}

// Check our flags represent the actual children correctly.
void NGPhysicalBoxFragment::CheckIntegrity() const {
  bool has_inflow_blocks = false;
  bool has_inlines = false;
  bool has_line_boxes = false;
  bool has_floats = false;
  bool has_list_markers = false;

  for (const NGLink& child : Children()) {
    if (child->IsFloating())
      has_floats = true;
    else if (child->IsOutOfFlowPositioned())
      ;  // OOF can be in the fragment tree regardless of |HasItems|.
    else if (child->IsLineBox())
      has_line_boxes = true;
    else if (child->IsListMarker())
      has_list_markers = true;
    else if (child->IsInline())
      has_inlines = true;
    else
      has_inflow_blocks = true;
  }

  // If we have line boxes, |IsInlineFormattingContext()| is true, but the
  // reverse is not always true.
  if (has_line_boxes || has_inlines)
    DCHECK(IsInlineFormattingContext());

  // If display-locked, we may not have any children.
  DCHECK(layout_object_);
  if (layout_object_ && layout_object_->ChildPaintBlockedByDisplayLock())
    return;

  if (RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled()) {
    if (has_line_boxes)
      DCHECK(HasItems());
  } else {
    DCHECK_EQ(HasItems(), has_line_boxes);
  }

  if (has_line_boxes) {
    DCHECK(!has_inlines);
    DCHECK(!has_inflow_blocks);
    // The following objects should be in the items, not in the tree. One
    // exception is that floats may occur as regular fragments in the tree
    // after a fragmentainer break.
    DCHECK(!has_floats || !IsFirstForNode());
    DCHECK(!has_list_markers);
  }
}

void NGPhysicalBoxFragment::AssertFragmentTreeSelf() const {
  DCHECK(!IsInlineBox());
  DCHECK(OwnerLayoutBox());
  DCHECK_EQ(this, PostLayout());
}

void NGPhysicalBoxFragment::AssertFragmentTreeChildren(
    bool allow_destroyed_or_moved) const {
  if (const NGFragmentItems* items = Items()) {
    for (NGInlineCursor cursor(*this, *items); cursor; cursor.MoveToNext()) {
      const NGFragmentItem& item = *cursor.Current();
      if (item.IsLayoutObjectDestroyedOrMoved()) {
        DCHECK(allow_destroyed_or_moved);
        continue;
      }
      if (const auto* box = item.BoxFragment()) {
        DCHECK(!box->IsLayoutObjectDestroyedOrMoved());
        if (!box->IsInlineBox())
          box->AssertFragmentTreeSelf();
      }
    }
  }

  for (const NGLink& child : Children()) {
    if (child->IsLayoutObjectDestroyedOrMoved()) {
      DCHECK(allow_destroyed_or_moved);
      continue;
    }
    if (const auto* box =
            DynamicTo<NGPhysicalBoxFragment>(child.fragment.Get()))
      box->AssertFragmentTreeSelf();
  }
}
#endif

void NGPhysicalBoxFragment::TraceAfterDispatch(Visitor* visitor) const {
  // Accessing |const_num_children_| inside Trace() here is safe since it is
  // const. Note we don't check children_valid_ since that is not threadsafe.
  // Tracing the child links themselves is safe from a background thread.
  for (const auto& child : base::make_span(children_, const_num_children_))
    visitor->Trace(child);
  // |HasItems()| and |ConstHasRareData()| are const and set
  // in ctor so they do not cause TOCTOU.
  if (HasItems())
    visitor->Trace(*ComputeItemsAddress());
  if (ConstHasRareData())
    visitor->Trace(*ComputeRareDataAddress());
  NGPhysicalFragment::TraceAfterDispatch(visitor);
}

void NGPhysicalBoxFragment::RareData::Trace(Visitor* visitor) const {
  visitor->Trace(table_column_geometries);
}

}  // namespace blink