-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
ng_inline_layout_algorithm.cc
1648 lines (1462 loc) · 70.4 KB
/
ng_inline_layout_algorithm.cc
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
// 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/inline/ng_inline_layout_algorithm.h"
#include <memory>
#include "base/compiler_specific.h"
#include "base/containers/adapters.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.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_bidi_paragraph.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_initial_letter_utils.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_info.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_ruby_utils.h"
#include "third_party/blink/renderer/core/layout/ng/list/layout_ng_outside_list_marker.h"
#include "third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.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.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_disable_side_effects_scope.h"
#include "third_party/blink/renderer/core/layout/ng/ng_floats_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_space_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
NGInlineLayoutAlgorithm::NGInlineLayoutAlgorithm(
NGInlineNode inline_node,
const NGConstraintSpace& space,
const NGInlineBreakToken* break_token,
const NGColumnSpannerPath* column_spanner_path,
NGInlineChildLayoutContext* context)
: NGLayoutAlgorithm(
inline_node,
inline_node.GetDocument()
.GetStyleResolver()
.CreateAnonymousStyleWithDisplay(inline_node.Style(),
EDisplay::kBlock),
space,
// Use LTR direction since inline layout handles bidi by itself and
// lays out in visual order.
TextDirection::kLtr,
break_token),
box_states_(nullptr),
context_(context),
column_spanner_path_(column_spanner_path),
baseline_type_(container_builder_.Style().GetFontBaseline()),
quirks_mode_(inline_node.GetDocument().InLineHeightQuirksMode()),
cached_line_items_(MakeGarbageCollected<NGLogicalLineItems>()) {
DCHECK(context);
}
// Define the destructor here, so that we can forward-declare more in the
// header.
NGInlineLayoutAlgorithm::~NGInlineLayoutAlgorithm() = default;
NGInlineBoxState* NGInlineLayoutAlgorithm::HandleOpenTag(
const NGInlineItem& item,
const NGInlineItemResult& item_result,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) const {
NGInlineBoxState* box = box_states->OnOpenTag(
ConstraintSpace(), item, item_result, baseline_type_, line_box);
// Compute text metrics for all inline boxes since even empty inlines
// influence the line height, except when quirks mode and the box is empty
// for the purpose of empty block calculation.
// https://drafts.csswg.org/css2/visudet.html#line-height
if (!quirks_mode_ || !item.IsEmptyItem())
box->ComputeTextMetrics(*item.Style(), *box->font, baseline_type_);
if (item.Style()->HasMask()) {
// Layout may change the bounding box, which affects MaskClip.
if (LayoutObject* object = item.GetLayoutObject())
object->SetNeedsPaintPropertyUpdate();
}
return box;
}
NGInlineBoxState* NGInlineLayoutAlgorithm::HandleCloseTag(
const NGInlineItem& item,
const NGInlineItemResult& item_result,
NGLogicalLineItems* line_box,
NGInlineBoxState* box) {
if (UNLIKELY(quirks_mode_ && !item.IsEmptyItem()))
box->EnsureTextMetrics(*item.Style(), *box->font, baseline_type_);
box = box_states_->OnCloseTag(ConstraintSpace(), line_box, box,
baseline_type_, item.HasEndEdge());
// Just clear |NeedsLayout| flags. Culled inline boxes do not need paint
// invalidations. If this object produces box fragments,
// |NGInlineBoxStateStack| takes care of invalidations.
if (!NGDisableSideEffectsScope::IsDisabled())
item.GetLayoutObject()->ClearNeedsLayoutWithoutPaintInvalidation();
return box;
}
// Prepare NGInlineLayoutStateStack for a new line.
void NGInlineLayoutAlgorithm::PrepareBoxStates(
const NGLineInfo& line_info,
const NGInlineBreakToken* break_token) {
#if DCHECK_IS_ON()
is_box_states_from_context_ = false;
#endif
// Use the initial box states if no break token; i.e., a line from the start.
if (!break_token) {
box_states_ = context_->ResetBoxStates();
return;
}
// Check if the box states in NGChildLayoutContext is valid for this line.
// If the previous line was ::first-line, always rebuild because box states
// have ::first-line styles.
const HeapVector<NGInlineItem>& items = line_info.ItemsData().items;
if (!break_token->UseFirstLineStyle()) {
box_states_ =
context_->BoxStatesIfValidForItemIndex(items, break_token->ItemIndex());
if (box_states_) {
#if DCHECK_IS_ON()
is_box_states_from_context_ = true;
#endif
return;
}
}
// If not, rebuild the box states for the break token.
box_states_ = context_->ResetBoxStates();
RebuildBoxStates(line_info, break_token, box_states_);
}
static LayoutUnit AdjustLineOffsetForHanging(NGLineInfo* line_info,
LayoutUnit& line_offset) {
if (IsLtr(line_info->BaseDirection()))
return LayoutUnit();
// If !line_info->ShouldHangTrailingSpaces(), the hang width is not considered
// in ApplyTextAlign, and so line_offset points to where the left edge of the
// hanging spaces should be. Since the line box rect has to start at the left
// edge of the text instead (needed for caret positioning), we increase
// line_offset.
LayoutUnit hang_width = line_info->HangWidth();
if (!line_info->ShouldHangTrailingSpaces()) {
line_offset += hang_width;
}
// Now line_offset always points to where the left edge of the text should be.
// If there are any hanging spaces, the starting position of the line must be
// offset by the width of the hanging spaces so that the text starts at
// line_offset.
return -hang_width;
}
void NGInlineLayoutAlgorithm::RebuildBoxStates(
const NGLineInfo& line_info,
const NGInlineBreakToken* break_token,
NGInlineLayoutStateStack* box_states) const {
// Compute which tags are not closed at the beginning of this line.
NGInlineItemsData::OpenTagItems open_items;
line_info.ItemsData().GetOpenTagItems(break_token->ItemIndex(), &open_items);
// Create box states for tags that are not closed yet.
DCHECK_EQ(cached_line_items_->size(), 0u);
NGLogicalLineItems& line_box = *cached_line_items_;
box_states->OnBeginPlaceItems(Node(), line_info.LineStyle(), baseline_type_,
quirks_mode_, &line_box);
for (const NGInlineItem* item : open_items) {
NGInlineItemResult item_result;
NGLineBreaker::ComputeOpenTagResult(*item, ConstraintSpace(),
Node().IsSvgText(), &item_result);
HandleOpenTag(*item, item_result, &line_box, box_states);
}
line_box.clear();
}
#if DCHECK_IS_ON()
void NGInlineLayoutAlgorithm::CheckBoxStates(
const NGLineInfo& line_info,
const NGInlineBreakToken* break_token) const {
NGInlineLayoutStateStack rebuilt;
RebuildBoxStates(line_info, break_token, &rebuilt);
DCHECK_EQ(cached_line_items_->size(), 0u);
NGLogicalLineItems& line_box = *cached_line_items_;
rebuilt.OnBeginPlaceItems(Node(), line_info.LineStyle(), baseline_type_,
quirks_mode_, &line_box);
DCHECK(box_states_);
box_states_->CheckSame(rebuilt);
line_box.clear();
}
#endif
void NGInlineLayoutAlgorithm::CreateLine(
const NGLineLayoutOpportunity& opportunity,
NGLineInfo* line_info,
NGLogicalLineItems* line_box,
NGLineBreaker* line_breaker) {
// Needs MutableResults to move ShapeResult out of the NGLineInfo.
NGInlineItemResults* line_items = line_info->MutableResults();
// Clear the current line without releasing the buffer.
line_box->Shrink(0);
// Apply justification before placing items, because it affects size/position
// of items, which are needed to compute inline static positions.
LayoutUnit line_offset_for_text_align = ApplyTextAlign(line_info);
// Compute heights of all inline items by placing the dominant baseline at 0.
// The baseline is adjusted after the height of the line box is computed.
const ComputedStyle& line_style = line_info->LineStyle();
box_states_->SetIsEmptyLine(line_info->IsEmptyLine());
NGInlineBoxState* box = box_states_->OnBeginPlaceItems(
Node(), line_style, baseline_type_, quirks_mode_, line_box);
#if DCHECK_IS_ON()
if (is_box_states_from_context_)
CheckBoxStates(*line_info, BreakToken());
#endif
bool has_out_of_flow_positioned_items = false;
bool has_floating_items = false;
bool has_relative_positioned_items = false;
const NGInlineItemResult* initial_letter_item_result = nullptr;
// List items trigger strict line height, i.e. we make room for the line box
// strut, for *every* line. This matches other browsers. The intention may
// have been to make sure that there's always room for the list item marker,
// but that doesn't explain why it's done for every line...
if (quirks_mode_ && line_style.Display() == EDisplay::kListItem)
box->ComputeTextMetrics(line_style, *box->font, baseline_type_);
for (NGInlineItemResult& item_result : *line_items) {
DCHECK(item_result.item);
const NGInlineItem& item = *item_result.item;
#if DCHECK_IS_ON()
if (line_info->IsBlockInInline()) {
DCHECK_EQ(line_items->size(), 1u);
DCHECK_EQ(item.Type(), NGInlineItem::kBlockInInline);
}
#endif
if (item.Type() == NGInlineItem::kText) {
DCHECK(item.GetLayoutObject());
DCHECK(item.GetLayoutObject()->IsText() ||
item.GetLayoutObject()->IsLayoutNGListItem());
DCHECK(item_result.shape_result);
if (UNLIKELY(quirks_mode_))
box->EnsureTextMetrics(*item.Style(), *box->font, baseline_type_);
// Take all used fonts into account if 'line-height: normal'.
if (box->include_used_fonts)
box->AccumulateUsedFonts(item_result.shape_result.get());
DCHECK(item.TextType() == NGTextType::kNormal ||
item.TextType() == NGTextType::kSymbolMarker);
if (UNLIKELY(item_result.is_hyphenated)) {
DCHECK(item_result.hyphen_string);
DCHECK(item_result.hyphen_shape_result);
LayoutUnit hyphen_inline_size = item_result.HyphenInlineSize();
line_box->AddChild(item, item_result, item_result.TextOffset(),
box->text_top,
item_result.inline_size - hyphen_inline_size,
box->text_height, item.BidiLevel());
PlaceHyphen(item_result, hyphen_inline_size, line_box, box);
} else if (UNLIKELY(Node().IsTextCombine())) {
// We make combined text at block offset 0 with 1em height.
// Painter paints text at block offset + |font.internal_leading / 2|.
const auto one_em = item.Style()->ComputedFontSizeAsFixed();
const auto text_height = one_em;
const auto text_top = LayoutUnit();
line_box->AddChild(item, item_result, item_result.TextOffset(),
text_top, item_result.inline_size, text_height,
item.BidiLevel());
} else {
line_box->AddChild(item, item_result, item_result.TextOffset(),
box->text_top, item_result.inline_size,
box->text_height, item.BidiLevel());
}
// Text boxes always need full paint invalidations.
item.GetLayoutObject()->ClearNeedsLayoutWithFullPaintInvalidation();
} else if (item.Type() == NGInlineItem::kControl) {
PlaceControlItem(item, *line_info, &item_result, line_box, box);
} else if (item.Type() == NGInlineItem::kOpenTag) {
box = HandleOpenTag(item, item_result, line_box, box_states_);
} else if (item.Type() == NGInlineItem::kCloseTag) {
box = HandleCloseTag(item, item_result, line_box, box);
} else if (item.Type() == NGInlineItem::kAtomicInline) {
box = PlaceAtomicInline(item, *line_info, &item_result, line_box);
has_relative_positioned_items |=
item.Style()->GetPosition() == EPosition::kRelative;
} else if (item.Type() == NGInlineItem::kBlockInInline) {
DCHECK(line_info->IsBlockInInline());
PlaceBlockInInline(item, *line_info, &item_result, line_box);
} else if (item.Type() == NGInlineItem::kListMarker) {
PlaceListMarker(item, &item_result, *line_info);
} else if (item.Type() == NGInlineItem::kOutOfFlowPositioned) {
// An inline-level OOF child positions itself based on its direction, a
// block-level OOF child positions itself based on the direction of its
// block-level container.
TextDirection direction =
item.GetLayoutObject()->StyleRef().IsOriginalDisplayInlineType()
? item.Direction()
: ConstraintSpace().Direction();
line_box->AddChild(item.GetLayoutObject(), item.BidiLevel(), direction);
has_out_of_flow_positioned_items = true;
} else if (item.Type() == NGInlineItem::kFloating) {
if (item_result.positioned_float) {
if (!item_result.positioned_float->need_break_before) {
DCHECK(item_result.positioned_float->layout_result);
line_box->AddChild(item_result.positioned_float->layout_result,
item_result.positioned_float->bfc_offset,
item.BidiLevel());
}
} else {
line_box->AddChild(item.GetLayoutObject(), item.BidiLevel());
}
has_floating_items = true;
has_relative_positioned_items |=
item.Style()->GetPosition() == EPosition::kRelative;
} else if (item.Type() == NGInlineItem::kBidiControl) {
line_box->AddChild(item.BidiLevel());
} else if (UNLIKELY(item.Type() == NGInlineItem::kInitialLetterBox)) {
// The initial letter does not increase the logical height of the line
// box in which it participates[1]. So, we should not changes
// `NGInlineBoxState::metrics`, or not call ` ComputeTextMetrics()` to
// incorporate from `ComputedStyle::GetFont()` of the initial letter box.
// See also `NGLineInfo::ComputeTotalBlockSize()` for calculation of
// layout opportunities.
// [1] https://drafts.csswg.org/css-inline/#initial-letter-block-position
DCHECK(!initial_letter_item_result);
initial_letter_item_result = &item_result;
PlaceInitialLetterBox(item, *line_info, &item_result, line_box);
}
}
box_states_->OnEndPlaceItems(ConstraintSpace(), line_box, baseline_type_);
if (UNLIKELY(Node().IsBidiEnabled())) {
box_states_->PrepareForReorder(line_box);
BidiReorder(line_info->BaseDirection(), line_box);
box_states_->UpdateAfterReorder(line_box);
} else {
DCHECK(IsLtr(line_info->BaseDirection()));
}
const LayoutUnit hang_width = line_info->HangWidth();
const LayoutUnit position =
AdjustLineOffsetForHanging(line_info, line_offset_for_text_align);
LayoutUnit inline_size = box_states_->ComputeInlinePositions(
line_box, position, line_info->IsBlockInInline());
if (UNLIKELY(hang_width)) {
// If we've shifted the line items the inline-size is already correct.
if (position == LayoutUnit())
inline_size -= hang_width;
container_builder_.SetHangInlineSize(hang_width);
}
// Truncate the line if:
// - 'text-overflow: ellipsis' is set and we *aren't* a line-clamp context.
// - If we've reached the line-clamp limit.
if (UNLIKELY(((line_info->HasOverflow() &&
!ConstraintSpace().IsLineClampContext() &&
node_.GetLayoutBlockFlow()->ShouldTruncateOverflowingText()) ||
ConstraintSpace().LinesUntilClamp() == 1) &&
!line_info->IsBlockInInline())) {
DCHECK(!line_info->IsBlockInInline());
NGLineTruncator truncator(*line_info);
auto* input =
DynamicTo<HTMLInputElement>(node_.GetLayoutBlockFlow()->GetNode());
if (input && input->ShouldApplyMiddleEllipsis()) {
inline_size =
truncator.TruncateLineInTheMiddle(inline_size, line_box, box_states_);
} else {
inline_size = truncator.TruncateLine(inline_size, line_box, box_states_);
}
}
// Negative margins can make the position negative, but the inline size is
// always positive or 0.
inline_size = inline_size.ClampNegativeToZero();
if (line_info->IsBlockInInline()) {
container_builder_.SetBfcLineOffset(
ConstraintSpace().BfcOffset().line_offset);
} else {
// Other 'text-align' values than 'justify' move line boxes as a whole, but
// indivisual items do not change their relative position to the line box.
LayoutUnit bfc_line_offset =
line_info->BfcOffset().line_offset + line_offset_for_text_align;
if (IsLtr(line_info->BaseDirection()))
bfc_line_offset += line_info->TextIndent();
container_builder_.SetBfcLineOffset(bfc_line_offset);
}
// Force an editable empty line to have metrics, so that is has a height.
if (UNLIKELY(line_info->HasLineEvenIfEmpty())) {
box_states_->LineBoxState().EnsureTextMetrics(
line_info->LineStyle(), *box_states_->LineBoxState().font,
baseline_type_);
}
const FontHeight& line_box_metrics = box_states_->LineBoxState().metrics;
if (UNLIKELY(Node().HasRuby() && !line_info->IsEmptyLine())) {
line_info->SetAnnotationBlockStartAdjustment(
SetAnnotationOverflow(*line_info, *line_box, line_box_metrics));
}
if (UNLIKELY(initial_letter_item_result)) {
DCHECK(!line_info->IsEmptyLine());
// `container_builder_.BfcLineOffset()` holds left edge of current line
// after applying `text-align` and `text-indent`.
//
// * *
// | |
// +V------------------+ +----V---------------+
// LTR | this is line 1. | RTL | this is line 1.|
//
// Margins should be `NGBoxStrut` instead of `NGLineBoxStrut` for
// calculating block offset. Test[1], for flipped line writing mode,
// verifies differences between them.
// [1]
// https://wpt.live/css/css-inline/initial-letter/initial-letter-block-position-margins-vlr.html
const NGExclusion* exclusion = PostPlaceInitialLetterBox(
line_box_metrics,
NGBoxStrut(initial_letter_item_result->margins,
line_info->LineStyle().IsFlippedLinesWritingMode()),
line_box,
NGBfcOffset(container_builder_.BfcLineOffset(),
line_info->BfcOffset().block_offset),
line_info);
ExclusionSpace().Add(exclusion);
}
// Place out-of-flow positioned objects.
// This adjusts the NGLogicalLineItem::offset member to contain
// the static position of the OOF positioned children relative to the linebox.
if (has_out_of_flow_positioned_items) {
DCHECK(!line_info->IsBlockInInline());
PlaceOutOfFlowObjects(*line_info, line_box_metrics, line_box);
}
// Place floating objects.
// This adjusts the NGLogicalLineItem::offset member to
// contain the position of the float relative to the linebox.
// Additionally it will perform layout on any unpositioned floats which
// needed the line height to correctly determine their final position.
if (has_floating_items) {
DCHECK(!line_info->IsBlockInInline());
// Test[1] has a float to be pushed down to next line.
// [1]
// https://wpt.live/css/css-inline/initial-letter/initial-letter-floats-005.html
PlaceFloatingObjects(*line_info, line_box_metrics, opportunity,
line_info->ComputeBlockStartAdjustment(), line_box,
line_breaker);
}
// Apply any relative positioned offsets to *items* which have relative
// positioning, (atomic-inlines, and floats). This will only move the
// individual item.
if (has_relative_positioned_items)
PlaceRelativePositionedItems(line_box);
// Apply any relative positioned offsets to any boxes (and their children).
box_states_->ApplyRelativePositioning(ConstraintSpace(), line_box);
// Create box fragments if needed. After this point forward, |line_box| is a
// tree structure.
// The individual children don't move position within the |line_box|, rather
// the children have their layout_result, fragment, (or similar) set to null,
// creating a "hole" in the array.
if (box_states_->HasBoxFragments()) {
box_states_->CreateBoxFragments(ConstraintSpace(), line_box,
line_info->IsBlockInInline());
}
// Update item index of the box states in the context.
context_->SetItemIndex(line_info->ItemsData().items,
line_info->EndItemIndex());
if (line_info->UseFirstLineStyle())
container_builder_.SetStyleVariant(NGStyleVariant::kFirstLine);
// Even if we have something in-flow, it may just be empty items that
// shouldn't trigger creation of a line. Exit now if that's the case.
if (line_info->IsEmptyLine())
return;
if (!line_box_metrics.IsEmpty())
container_builder_.SetMetrics(line_box_metrics);
// |container_builder_| is already set up by |PlaceBlockInInline|.
if (line_info->IsBlockInInline())
return;
// Up until this point, children are placed so that the dominant baseline is
// at 0. Move them to the final baseline position, and set the logical top of
// the line box to the line top.
//
// For SVG <text>, the block offset of the initial 'current text position'
// should be 0. As for the inline offset, see
// NGSvgTextLayoutAttributesBuilder::Build().
//
// For text-combine-upright:all, the block offset should be zero to make
// combined text in 1em x 1em box.
if (UNLIKELY(Node().IsTextCombine())) {
// The effective size of combined text is 1em square[1]
// [1] https://drafts.csswg.org/css-writing-modes-3/#text-combine-layout
const auto one_em = Node().Style().ComputedFontSizeAsFixed();
inline_size = std::min(inline_size, one_em);
} else if (UNLIKELY(Node().IsInitialLetterBox())) {
const FontHeight& adjusted_metrics =
AdjustInitialLetterInTextPosition(line_box_metrics, line_box);
if (!adjusted_metrics.IsEmpty()) {
container_builder_.SetMetrics(adjusted_metrics);
line_box->MoveInBlockDirection(adjusted_metrics.ascent);
}
} else if (LIKELY(!Node().IsSvgText())) {
// Convert baseline relative block offset of `NGLogicalLineItem::rect` to
// to line box relative block offset.
line_box->MoveInBlockDirection(line_box_metrics.ascent);
}
container_builder_.SetInlineSize(inline_size);
}
void NGInlineLayoutAlgorithm::PlaceControlItem(const NGInlineItem& item,
const NGLineInfo& line_info,
NGInlineItemResult* item_result,
NGLogicalLineItems* line_box,
NGInlineBoxState* box) {
DCHECK_EQ(item.Type(), NGInlineItem::kControl);
DCHECK_GE(item.Length(), 1u);
DCHECK(!item.TextShapeResult());
#if DCHECK_IS_ON()
UChar character = line_info.ItemsData().text_content[item.StartOffset()];
NGTextType text_type;
switch (character) {
case kNewlineCharacter:
text_type = NGTextType::kForcedLineBreak;
break;
case kTabulationCharacter:
text_type = NGTextType::kFlowControl;
break;
case kZeroWidthSpaceCharacter:
text_type = NGTextType::kFlowControl;
break;
default:
NOTREACHED();
return;
}
DCHECK_EQ(item.TextType(), text_type);
#endif
// Don't generate fragments if this is a generated (not in DOM) break
// opportunity during the white space collapsing in NGInlineItemBuilder.
if (UNLIKELY(item.IsGeneratedForLineBreak()))
return;
DCHECK(item.GetLayoutObject());
DCHECK(item.GetLayoutObject()->IsText());
if (!NGDisableSideEffectsScope::IsDisabled())
item.GetLayoutObject()->ClearNeedsLayoutWithFullPaintInvalidation();
if (UNLIKELY(quirks_mode_ && !box->HasMetrics()))
box->EnsureTextMetrics(*item.Style(), *box->font, baseline_type_);
line_box->AddChild(item, std::move(item_result->shape_result),
item_result->TextOffset(), box->text_top,
item_result->inline_size, box->text_height,
item.BidiLevel());
}
void NGInlineLayoutAlgorithm::PlaceHyphen(const NGInlineItemResult& item_result,
LayoutUnit hyphen_inline_size,
NGLogicalLineItems* line_box,
NGInlineBoxState* box) {
DCHECK(item_result.item);
DCHECK(item_result.is_hyphenated);
DCHECK(item_result.hyphen_string);
DCHECK(item_result.hyphen_shape_result);
DCHECK_EQ(hyphen_inline_size, item_result.HyphenInlineSize());
const NGInlineItem& item = *item_result.item;
line_box->AddChild(
item, ShapeResultView::Create(item_result.hyphen_shape_result.get()),
item_result.hyphen_string, box->text_top, hyphen_inline_size,
box->text_height, item.BidiLevel());
}
NGInlineBoxState* NGInlineLayoutAlgorithm::PlaceAtomicInline(
const NGInlineItem& item,
const NGLineInfo& line_info,
NGInlineItemResult* item_result,
NGLogicalLineItems* line_box) {
DCHECK(item_result->layout_result);
// Reset the ellipsizing state. Atomic inline is monolithic.
LayoutObject* layout_object = item.GetLayoutObject();
DCHECK(layout_object);
DCHECK(layout_object->IsAtomicInlineLevel());
DCHECK_EQ(To<LayoutBox>(layout_object)->GetNGPaginationBreakability(),
LayoutBox::kForbidBreaks);
layout_object->SetIsTruncated(false);
item_result->has_edge = true;
NGInlineBoxState* box = box_states_->OnOpenTag(
ConstraintSpace(), item, *item_result, baseline_type_, *line_box);
if (LIKELY(!IsA<LayoutNGTextCombine>(layout_object))) {
PlaceLayoutResult(item_result, line_box, box, box->margin_inline_start);
} else {
// The metrics should be as text instead of atomic inline box.
const auto& style = layout_object->Parent()->StyleRef();
box->ComputeTextMetrics(style, style.GetFont(), baseline_type_);
// Note: |item_result->spacing_before| is non-zero if this |item_result|
// is |LayoutNGTextCombine| and after CJK character.
// See "text-combine-justify.html".
const LayoutUnit inline_offset =
box->margin_inline_start + item_result->spacing_before;
line_box->AddChild(std::move(item_result->layout_result),
LogicalOffset{inline_offset, box->text_top},
item_result->inline_size, /* children_count */ 0,
item.BidiLevel());
}
return box_states_->OnCloseTag(ConstraintSpace(), line_box, box,
baseline_type_);
}
// Place a NGLayoutResult into the line box.
void NGInlineLayoutAlgorithm::PlaceLayoutResult(NGInlineItemResult* item_result,
NGLogicalLineItems* line_box,
NGInlineBoxState* box,
LayoutUnit inline_offset) {
DCHECK(item_result->layout_result);
DCHECK(item_result->item);
const NGInlineItem& item = *item_result->item;
DCHECK(item.Style());
FontHeight metrics =
NGBoxFragment(ConstraintSpace().GetWritingDirection(),
To<NGPhysicalBoxFragment>(
item_result->layout_result->PhysicalFragment()))
.BaselineMetrics(item_result->margins, baseline_type_);
if (box)
box->metrics.Unite(metrics);
LayoutUnit line_top = item_result->margins.line_over - metrics.ascent;
line_box->AddChild(std::move(item_result->layout_result),
LogicalOffset{inline_offset, line_top},
item_result->inline_size, /* children_count */ 0,
item.BidiLevel());
}
void NGInlineLayoutAlgorithm::PlaceBlockInInline(
const NGInlineItem& item,
const NGLineInfo& line_info,
NGInlineItemResult* item_result,
NGLogicalLineItems* line_box) {
DCHECK_EQ(item.Type(), NGInlineItem::kBlockInInline);
LayoutObject* layout_object = item.GetLayoutObject();
DCHECK(layout_object);
DCHECK(layout_object->IsAnonymous());
DCHECK(!layout_object->IsInline());
DCHECK(item_result->layout_result);
const NGLayoutResult& result = *item_result->layout_result;
const auto& box_fragment =
To<NGPhysicalBoxFragment>(result.PhysicalFragment());
NGBoxFragment fragment(ConstraintSpace().GetWritingDirection(), box_fragment);
// Setup |container_builder_|. Set it up here instead of in |CreateLine|,
// because there should be only one block-in-inline, and we need data from the
// |NGLayoutResult|.
container_builder_.SetIsBlockInInline();
container_builder_.SetInlineSize(fragment.InlineSize());
if (!result.IsSelfCollapsing()) {
// Block-in-inline is wrapped in an anonymous block that has no margins.
const FontHeight metrics = fragment.BaselineMetrics(
/* margins */ NGLineBoxStrut(), baseline_type_);
box_states_->OnBlockInInline(metrics, line_box);
}
end_margin_strut_ = result.EndMarginStrut();
container_builder_.SetExclusionSpace(result.ExclusionSpace());
container_builder_.SetAdjoiningObjectTypes(result.AdjoiningObjectTypes());
lines_until_clamp_ = result.LinesUntilClamp();
if (UNLIKELY(box_fragment.MayHaveDescendantAboveBlockStart()))
container_builder_.SetMayHaveDescendantAboveBlockStart(true);
line_box->AddChild(std::move(item_result->layout_result),
/* offset */ LogicalOffset(), item_result->inline_size,
/* children_count */ 0, item.BidiLevel());
}
void NGInlineLayoutAlgorithm::PlaceInitialLetterBox(
const NGInlineItem& item,
const NGLineInfo& line_info,
NGInlineItemResult* item_result,
NGLogicalLineItems* line_box) {
DCHECK(item_result->layout_result);
DCHECK(!IsA<LayoutNGTextCombine>(item.GetLayoutObject()));
DCHECK(!item_result->spacing_before);
item_result->has_edge = true;
// Because of the initial letter box should not contribute baseline position
// to surrounding text, we should not update `NGInlineBoxState` for avoiding
// to affect `line_box_metrics`.
//
// Note: `item.Style()` which holds style of `<::first-letter>` should not be
// include in `NGInlineBoxState::font_metrics` and `metrics`, because they
// don't affect baseline of surrounding text.
line_box->AddChild(
std::move(item_result->layout_result),
LogicalOffset{item_result->margins.inline_start, LayoutUnit()},
item_result->inline_size, /* children_count */ 0, item.BidiLevel());
}
// Place all out-of-flow objects in |line_box_|.
void NGInlineLayoutAlgorithm::PlaceOutOfFlowObjects(
const NGLineInfo& line_info,
const FontHeight& line_box_metrics,
NGLogicalLineItems* line_box) {
DCHECK(line_info.IsEmptyLine() || !line_box_metrics.IsEmpty())
<< "Non-empty lines must have a valid set of linebox metrics.";
// All children within the linebox are positioned relative to the baseline,
// then shifted later using NGLineBoxFragmentBuilder::MoveInBlockDirection.
LayoutUnit baseline_adjustment =
line_info.IsEmptyLine() ? LayoutUnit() : -line_box_metrics.ascent;
LayoutUnit line_height =
line_info.IsEmptyLine() ? LayoutUnit() : line_box_metrics.LineHeight();
// The location of the "next" line.
//
// This uses NGConstraintSpace::Direction rather than
// NGLineInfo::BaseDirection as this is for a block-level object rather than
// an inline-level object.
//
// Similarly this uses the available size to determine which edge to align
// to, and *does not* avoid floats.
LayoutUnit block_level_line_location =
IsLtr(ConstraintSpace().Direction())
? LayoutUnit()
: ConstraintSpace().AvailableSize().inline_size;
// This offset represents the position of the "next" line, relative to the
// line we are currently creating, (this takes into account text-indent, etc).
LayoutUnit block_level_inline_offset =
block_level_line_location - (container_builder_.BfcLineOffset() -
ConstraintSpace().BfcOffset().line_offset);
// To correctly determine which "line" block-level out-of-flow positioned
// object is placed on, we need to keep track of if there is any inline-level
// content preceeding it.
bool has_preceding_inline_level_content = false;
bool has_rtl_block_level_out_of_flow_objects = false;
bool is_ltr = IsLtr(line_info.BaseDirection());
for (NGLogicalLineItem& child : *line_box) {
has_preceding_inline_level_content |= child.HasInFlowFragment();
const LayoutObject* box = child.out_of_flow_positioned_box;
if (!box)
continue;
LogicalOffset static_offset(LayoutUnit(), baseline_adjustment);
if (box->StyleRef().IsOriginalDisplayInlineType()) {
// An inline-level OOF element positions itself within the line, at the
// position it would have been if it was in-flow.
static_offset.inline_offset = child.rect.offset.inline_offset;
// The static-position of inline-level OOF-positioned nodes depends on
// previous floats (if any).
//
// If we are an empty-inline we may not have the correct BFC block-offset
// yet. Due to this we need to mark this node as having adjoining
// objects, and perform a re-layout if our position shifts.
container_builder_.AddAdjoiningObjectTypes(kAdjoiningInlineOutOfFlow);
} else {
// A block-level OOF element positions itself on the "next" line. However
// only shifts down if there is preceding inline-level content.
static_offset.inline_offset = block_level_inline_offset;
if (is_ltr) {
if (has_preceding_inline_level_content)
static_offset.block_offset += line_height;
} else {
// "Preceding" is in logical order, but this loop is in visual order. In
// RTL, move objects down in the reverse-order loop below.
has_rtl_block_level_out_of_flow_objects = true;
}
}
child.rect.offset = static_offset;
}
if (UNLIKELY(has_rtl_block_level_out_of_flow_objects)) {
has_preceding_inline_level_content = false;
for (NGLogicalLineItem& child : base::Reversed(*line_box)) {
const LayoutObject* box = child.out_of_flow_positioned_box;
if (!box) {
has_preceding_inline_level_content |= child.HasInFlowFragment();
continue;
}
if (has_preceding_inline_level_content &&
!box->StyleRef().IsOriginalDisplayInlineType()) {
child.rect.offset.block_offset += line_height;
}
}
}
}
void NGInlineLayoutAlgorithm::PlaceFloatingObjects(
const NGLineInfo& line_info,
const FontHeight& line_box_metrics,
const NGLineLayoutOpportunity& opportunity,
LayoutUnit ruby_block_start_adjust,
NGLogicalLineItems* line_box,
NGLineBreaker* line_breaker) {
DCHECK(line_info.IsEmptyLine() || !line_box_metrics.IsEmpty())
<< "Non-empty lines must have a valid set of linebox metrics.";
// All children within the linebox are positioned relative to the baseline,
// then shifted later using NGLineBoxFragmentBuilder::MoveInBlockDirection.
LayoutUnit baseline_adjustment =
line_info.IsEmptyLine() ? LayoutUnit() : -line_box_metrics.ascent;
LayoutUnit line_height =
line_info.IsEmptyLine() ? LayoutUnit() : line_box_metrics.LineHeight();
// Any unpositioned floats we encounter need to be placed on the "next" line.
// This BFC block-offset represents the start of the "next" line.
LayoutUnit origin_bfc_block_offset =
opportunity.bfc_block_offset + line_height;
LayoutUnit bfc_line_offset = container_builder_.BfcLineOffset();
LayoutUnit bfc_block_offset =
line_info.IsEmptyLine()
? ConstraintSpace().ExpectedBfcBlockOffset()
: line_info.BfcOffset().block_offset + ruby_block_start_adjust;
for (NGLogicalLineItem& child : *line_box) {
// We need to position any floats which should be on the "next" line now.
// If this is an empty inline, all floats are positioned during the
// PositionLeadingFloats step.
if (child.unpositioned_float) {
NGPositionedFloat positioned_float = PositionFloat(
origin_bfc_block_offset, child.unpositioned_float, &ExclusionSpace());
if (positioned_float.need_break_before) {
// We decided to break before the float. No fragment here. Create a
// break token and propagate it to the block container.
NGBlockNode float_node(To<LayoutBox>(child.unpositioned_float.Get()));
auto* break_before = NGBlockBreakToken::CreateBreakBefore(
float_node, /* is_forced_break */ false);
line_breaker->PropagateBreakToken(break_before);
continue;
} else {
// If the float broke inside, we need to propagate the break token to
// the block container, so that we'll resume in the next fragmentainer.
if (const NGBreakToken* token =
positioned_float.layout_result->PhysicalFragment().BreakToken())
line_breaker->PropagateBreakToken(To<NGBlockBreakToken>(token));
child.layout_result = std::move(positioned_float.layout_result);
child.bfc_offset = positioned_float.bfc_offset;
child.unpositioned_float = nullptr;
}
}
// Skip any children which aren't positioned floats.
if (!child.layout_result ||
!child.layout_result->PhysicalFragment().IsFloating())
continue;
LayoutUnit block_offset =
child.bfc_offset.block_offset - bfc_block_offset + baseline_adjustment;
// We need to manually account for the flipped-lines writing mode here :(.
if (IsFlippedLinesWritingMode(ConstraintSpace().GetWritingMode())) {
NGFragment fragment(ConstraintSpace().GetWritingDirection(),
child.layout_result->PhysicalFragment());
block_offset = -fragment.BlockSize() - block_offset;
}
child.rect.offset = {child.bfc_offset.line_offset - bfc_line_offset,
block_offset};
}
}
void NGInlineLayoutAlgorithm::PlaceRelativePositionedItems(
NGLogicalLineItems* line_box) {
for (auto& child : *line_box) {
const auto* physical_fragment = child.PhysicalFragment();
if (!physical_fragment)
continue;
child.rect.offset += ComputeRelativeOffsetForInline(
ConstraintSpace(), physical_fragment->Style());
}
}
// Place a list marker.
void NGInlineLayoutAlgorithm::PlaceListMarker(const NGInlineItem& item,
NGInlineItemResult* item_result,
const NGLineInfo& line_info) {
if (UNLIKELY(quirks_mode_)) {
box_states_->LineBoxState().EnsureTextMetrics(
*item.Style(), item.Style()->GetFont(), baseline_type_);
}
}
// Justify the line. This changes the size of items by adding spacing.
// Returns false if justification failed and should fall back to start-aligned.
absl::optional<LayoutUnit> NGInlineLayoutAlgorithm::ApplyJustify(
LayoutUnit space,
NGLineInfo* line_info) {
// Empty lines should align to start.
if (line_info->IsEmptyLine())
return absl::nullopt;
// Justify the end of visible text, ignoring preserved trailing spaces.
unsigned end_offset = line_info->EndOffsetForJustify();
// If this line overflows, fallback to 'text-align: start'.
if (space <= 0)
return absl::nullopt;
// Can't justify an empty string.
if (end_offset == line_info->StartOffset())
return absl::nullopt;
const UChar kTextCombineItemMarker = 0x3042; // U+3042 Hiragana Letter A
// Note: |line_info->StartOffset()| can be different from
// |NGItemsResults[0].StartOffset()|, e.g. <b><input> <input></b> when
// line break before space (leading space). See http://crbug.com/1240791
const unsigned line_text_start_offset =
line_info->Results().front().StartOffset();
// Construct the line text to compute spacing for.
StringBuilder line_text_builder;
if (UNLIKELY(line_info->MayHaveTextCombineItem())) {
for (const NGInlineItemResult& item_result : line_info->Results()) {
if (item_result.StartOffset() >= end_offset)
break;
if (item_result.item->IsTextCombine()) {
// To apply justification before and after the combined text, we put
// ideographic character to increment |ShapeResultSpacing::
// expansion_opportunity_count_| for legacy layout compatibility.
// See "fast/writing-mode/text-combine-justify.html".
// Note: The spec[1] says we should treat combined text as U+FFFC.
// [1] https://drafts.csswg.org/css-writing-modes-3/#text-combine-layout
line_text_builder.Append(kTextCombineItemMarker);
continue;
}
line_text_builder.Append(StringView(line_info->ItemsData().text_content,
item_result.StartOffset(),
item_result.Length()));
}
} else {
line_text_builder.Append(StringView(line_info->ItemsData().text_content,
line_text_start_offset,
end_offset - line_text_start_offset));
}
// Append a hyphen if the last word is hyphenated. The hyphen is in
// |ShapeResult|, but not in text. |ShapeResultSpacing| needs the text that
// matches to the |ShapeResult|.
DCHECK(!line_info->Results().empty());
const NGInlineItemResult& last_item_result = line_info->Results().back();
if (last_item_result.hyphen_string)
line_text_builder.Append(last_item_result.hyphen_string);
// Compute the spacing to justify.
// Releasing string, StringBuilder reset.
String line_text = line_text_builder.ReleaseString();
DCHECK_GT(line_text.length(), 0u);
ShapeResultSpacing<String> spacing(line_text, Node().IsSvgText());
spacing.SetExpansion(space, line_info->BaseDirection());