-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
inline.rs
1745 lines (1578 loc) · 71 KB
/
inline.rs
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use super::float::PlacementAmongFloats;
use super::CollapsibleWithParentStartMargin;
use crate::cell::ArcRefCell;
use crate::context::LayoutContext;
use crate::flow::float::{FloatBox, SequentialLayoutState};
use crate::flow::FlowLayout;
use crate::formatting_contexts::IndependentFormattingContext;
use crate::fragment_tree::{
AnonymousFragment, BaseFragmentInfo, BoxFragment, CollapsedBlockMargins, CollapsedMargin,
FontMetrics, Fragment, HoistedSharedFragment, TextFragment,
};
use crate::geom::flow_relative::{Rect, Vec2};
use crate::geom::LengthOrAuto;
use crate::positioned::{
relative_adjustement, AbsolutelyPositionedBox, PositioningContext, PositioningContextLength,
};
use crate::sizing::ContentSizes;
use crate::style_ext::{
ComputedValuesExt, Display, DisplayGeneratingBox, DisplayOutside, PaddingBorderMargin,
};
use crate::ContainingBlock;
use app_units::Au;
use atomic_refcell::AtomicRef;
use gfx::text::glyph::GlyphStore;
use gfx::text::text_run::GlyphRun;
use servo_arc::Arc;
use std::cell::OnceCell;
use style::computed_values::white_space::T as WhiteSpace;
use style::logical_geometry::WritingMode;
use style::properties::ComputedValues;
use style::values::computed::Length;
use style::values::generics::text::LineHeight;
use style::values::specified::text::TextAlignKeyword;
use style::values::specified::text::TextDecorationLine;
use style::Zero;
use webrender_api::FontInstanceKey;
use xi_unicode::LineBreakLeafIter;
#[derive(Debug, Serialize)]
pub(crate) struct InlineFormattingContext {
pub(super) inline_level_boxes: Vec<ArcRefCell<InlineLevelBox>>,
pub(super) text_decoration_line: TextDecorationLine,
// Whether this IFC contains the 1st formatted line of an element
// https://www.w3.org/TR/css-pseudo-4/#first-formatted-line
pub(super) has_first_formatted_line: bool,
pub(super) contains_floats: bool,
/// Whether this IFC being constructed currently ends with whitespace. This is used to
/// implement rule 4 of <https://www.w3.org/TR/css-text-3/#collapse>:
///
/// > Any collapsible space immediately following another collapsible space—even one
/// > outside the boundary of the inline containing that space, provided both spaces are
/// > within the same inline formatting context—is collapsed to have zero advance width.
/// > (It is invisible, but retains its soft wrap opportunity, if any.)
pub(super) ends_with_whitespace: bool,
}
#[derive(Debug, Serialize)]
pub(crate) enum InlineLevelBox {
InlineBox(InlineBox),
TextRun(TextRun),
OutOfFlowAbsolutelyPositionedBox(ArcRefCell<AbsolutelyPositionedBox>),
OutOfFlowFloatBox(FloatBox),
Atomic(IndependentFormattingContext),
}
#[derive(Debug, Serialize)]
pub(crate) struct InlineBox {
pub base_fragment_info: BaseFragmentInfo,
#[serde(skip_serializing)]
pub style: Arc<ComputedValues>,
pub first_fragment: bool,
pub last_fragment: bool,
pub children: Vec<ArcRefCell<InlineLevelBox>>,
}
/// https://www.w3.org/TR/css-display-3/#css-text-run
#[derive(Debug, Serialize)]
pub(crate) struct TextRun {
pub base_fragment_info: BaseFragmentInfo,
#[serde(skip_serializing)]
pub parent_style: Arc<ComputedValues>,
pub text: String,
pub has_uncollapsible_content: bool,
}
struct InlineNestingLevelState<'box_tree> {
remaining_boxes: InlineBoxChildIter<'box_tree>,
line_items_so_far: Vec<LineItem>,
white_space: WhiteSpace,
/// Indicates whether this nesting level have text decorations in effect.
/// From https://drafts.csswg.org/css-text-decor/#line-decoration
// "When specified on or propagated to a block container that establishes
// an IFC..."
text_decoration_line: TextDecorationLine,
}
struct PartialInlineBoxFragment<'box_tree> {
base_fragment_info: BaseFragmentInfo,
style: Arc<ComputedValues>,
pbm: PaddingBorderMargin,
/// Whether or not this inline box has already been part of a previous line.
/// We need to create at least one Fragment for every inline box, but on following
/// lines, if the inline box is totally empty (such as after a preserved line
/// break), then we don't want to create empty Fragments for it.
was_part_of_previous_line: bool,
parent_nesting_level: InlineNestingLevelState<'box_tree>,
}
/// Information about the current line under construction for a particular
/// [`InlineFormattingContextState`]. This tracks position and size information while
/// [`LineItem`]s are collected and is used as input when those [`LineItem`]s are
/// converted into [`Fragment`]s during the final phase of line layout. Note that this
/// does not store the [`LineItem`]s themselves, as they are stored as part of the
/// nesting state in the [`InlineFormattingContextState`].
struct LineUnderConstruction {
/// The position of where this line will start once it is laid out. This includes any
/// offset from `text-indent`.
start_position: Vec2<Length>,
/// The current inline position in the line being laid out into [`LineItems`] in this
/// [`InlineFormattingContext`] independent of the depth in the nesting level.
inline_position: Length,
/// If the current line ends with whitespace, this tracks the advance width of that
/// whitespace. This is used to find the "real" width of a line if trailing whitespace
/// is trimmed from the end.
trailing_whitespace_advance: Length,
/// The currently calculated block size of this line, taking into account all inline
/// content already laid out into [`LineItem`]s. Later, content may increase the block
/// size.
block_size: Length,
/// Whether any active linebox has added a glyph, border, margin, or padding
/// to this line, which indicates that the next run that exceeds the line length
/// can cause a line break.
has_content: bool,
/// Whether or not there are floats that did not fit on the current line. Before
/// the [`LineItems`] of this line are laid out, these floats will need to be
/// placed directly below this line, but still as children of this line's Fragments.
has_floats_waiting_to_be_placed: bool,
/// A position of this line (relative to the containing block / inline formatting
/// context boundaries) so that would flow around floats. Note that when this is not
/// none, it takes precedence over [`LineUnderConstruction::start_position`].
float_placement: OnceCell<Rect<Length>>,
}
impl LineUnderConstruction {
fn new(start_position: Vec2<Length>) -> Self {
Self {
inline_position: start_position.inline.clone(),
trailing_whitespace_advance: Length::zero(),
start_position: start_position,
block_size: Length::zero(),
has_content: false,
has_floats_waiting_to_be_placed: false,
float_placement: OnceCell::new(),
}
}
fn line_block_start_considering_float_placement(&self) -> Length {
match self.float_placement.get() {
Some(float_placement) => float_placement.start_corner.block,
None => self.start_position.block,
}
}
fn replace_float_placement(&mut self, new_placement: Rect<Length>) {
self.float_placement.take();
let _ = self.float_placement.set(new_placement);
}
}
struct InlineFormattingContextState<'box_tree, 'a, 'b> {
positioning_context: &'a mut PositioningContext,
containing_block: &'b ContainingBlock<'b>,
sequential_layout_state: Option<&'a mut SequentialLayoutState>,
/// A vector of fragment that are laid out. This includes one [`Fragment::Anonymous`]
/// per line that is currently laid out plus fragments for all floats, which
/// are currently laid out at the top-level of each [`InlineFormattingContext`].
fragments: Vec<Fragment>,
/// Information about the line currently being laid out into [`LineItems`]s. The
/// [`LineItem`]s themselves are stored in the nesting state.
current_line: LineUnderConstruction,
/// The line breaking state for this inline formatting context.
linebreaker: Option<LineBreakLeafIter>,
partial_inline_boxes_stack: Vec<PartialInlineBoxFragment<'box_tree>>,
current_nesting_level: InlineNestingLevelState<'box_tree>,
}
impl<'box_tree, 'a, 'b> InlineFormattingContextState<'box_tree, 'a, 'b> {
/// Push a completed [LineItem] to the current nesteding level of this
/// [InlineFormattingContext].
fn push_line_item(
&mut self,
inline_size: Length,
line_item: LineItem,
last_whitespace_advance: Length,
) {
self.current_line.has_content = true;
self.current_line.inline_position += inline_size;
self.current_line.trailing_whitespace_advance = last_whitespace_advance;
self.current_line
.block_size
.max_assign(line_item.block_size());
self.current_nesting_level.line_items_so_far.push(line_item);
}
/// Finish layout of all the partial inline boxes in the current line,
/// finish current line and start a new one.
fn finish_line_and_reset(&mut self, layout_context: &LayoutContext) {
let mut nesting_level = &mut self.current_nesting_level;
for partial in self.partial_inline_boxes_stack.iter_mut().rev() {
partial.finish_layout(
nesting_level,
&mut self.current_line.inline_position,
false, /* at_end_of_inline_element */
);
nesting_level = &mut partial.parent_nesting_level;
}
let line_items = std::mem::take(&mut nesting_level.line_items_so_far);
self.finish_current_line(layout_context, line_items, self.containing_block);
}
fn finish_current_line(
&mut self,
layout_context: &LayoutContext,
mut line_items: Vec<LineItem>,
containing_block: &ContainingBlock,
) {
// If the placement due to floats, moved the line start position down, we need to
// make sure to advance the sequential layout state by that extra advance due to
// float placement.
let extra_advance_due_to_floats = self
.current_line
.float_placement
.get()
.map(|placement| placement.start_corner.block - self.current_line.start_position.block)
.unwrap_or_else(Length::zero);
if let Some(sequential_layout_state) = self.sequential_layout_state.as_mut() {
sequential_layout_state
.advance_block_position(self.current_line.block_size + extra_advance_due_to_floats);
}
if self.current_line.has_floats_waiting_to_be_placed {
place_pending_floats(self, &mut line_items);
}
// From <https://www.w3.org/TR/css-text-3/#white-space-phase-2>:
// > 3. A sequence of collapsible spaces at the end of a line is removed,
// > as well as any trailing U+1680 OGHAM SPACE MARK whose white-space
// > property is normal, nowrap, or pre-line.
let mut whitespace_trimmed = Length::zero();
for item in line_items.iter_mut().rev() {
if !item.trim_whitespace_at_end(&mut whitespace_trimmed) {
break;
}
}
let inline_start_position =
self.calculate_inline_start_for_current_line(containing_block, whitespace_trimmed);
let block_start_position = self
.current_line
.line_block_start_considering_float_placement();
let mut state = LineItemLayoutState {
inline_position: inline_start_position,
max_block_size: Length::zero(),
inline_start_of_parent: Length::zero(),
ifc_containing_block: containing_block,
positioning_context: &mut self.positioning_context,
line_block_start: block_start_position,
};
let positioning_context_length = state.positioning_context.len();
let fragments = layout_line_items(line_items, layout_context, &mut state);
let size = Vec2 {
inline: containing_block.inline_size,
block: state.max_block_size,
};
// The inline part of this start offset was taken into account when determining
// the inline start of the line in `calculate_inline_start_for_current_line` so
// we do not need to include it in the `start_corner` of the line's main Fragment.
let start_corner = Vec2 {
inline: Length::zero(),
block: block_start_position,
};
let line_had_content =
!fragments.is_empty() || state.positioning_context.len() != positioning_context_length;
if line_had_content {
state
.positioning_context
.adjust_static_position_of_hoisted_fragments_with_offset(
&start_corner,
positioning_context_length,
);
self.fragments
.push(Fragment::Anonymous(AnonymousFragment::new(
Rect { start_corner, size },
fragments,
containing_block.style.writing_mode,
)));
}
self.current_line = LineUnderConstruction::new(Vec2 {
inline: Length::zero(),
block: block_start_position + self.current_line.block_size,
});
}
/// Given the amount of whitespace trimmed from the line and taking into consideration
/// the `text-align` property, calculate where the line under construction starts in
/// the inline axis.
fn calculate_inline_start_for_current_line(
&self,
containing_block: &ContainingBlock,
whitespace_trimmed: Length,
) -> Length {
enum TextAlign {
Start,
Center,
End,
}
let line_left_is_inline_start = containing_block
.style
.writing_mode
.line_left_is_inline_start();
let text_align = match containing_block.style.clone_text_align() {
TextAlignKeyword::Start => TextAlign::Start,
TextAlignKeyword::Center => TextAlign::Center,
TextAlignKeyword::End => TextAlign::End,
TextAlignKeyword::Left => {
if line_left_is_inline_start {
TextAlign::Start
} else {
TextAlign::End
}
},
TextAlignKeyword::Right => {
if line_left_is_inline_start {
TextAlign::End
} else {
TextAlign::Start
}
},
TextAlignKeyword::Justify => {
// TODO: Add support for justfied text.
TextAlign::Start
},
TextAlignKeyword::ServoCenter |
TextAlignKeyword::ServoLeft |
TextAlignKeyword::ServoRight => {
// TODO: Implement these modes which seem to be used by quirks mode.
TextAlign::Start
},
};
let (line_start, line_end) = match self.current_line.float_placement.get() {
Some(float_placement) => (
float_placement.start_corner.inline,
float_placement.max_inline_position(),
),
None => (Length::zero(), self.containing_block.inline_size),
};
let space_after_floats = line_end - line_start;
// Properly handling text-indent requires that we do not align the text
// into the text-indent.
// See <https://drafts.csswg.org/css-text/#text-indent-property>
// "This property specifies the indentation applied to lines of inline content in
// a block. The indent is treated as a margin applied to the start edge of the
// line box."
let text_indent = self.current_line.start_position.inline;
let line_length = self.current_line.inline_position - whitespace_trimmed - text_indent;
line_start +
match text_align {
TextAlign::Start => text_indent,
TextAlign::End => (space_after_floats - line_length).max(text_indent),
TextAlign::Center => {
let available_space = containing_block.inline_size - text_indent;
((available_space - line_length) / 2.) + text_indent
},
}
}
fn place_float_fragment(&mut self, fragment: &mut BoxFragment) {
let state = self
.sequential_layout_state
.as_mut()
.expect("Tried to lay out a float with no sequential placement state!");
let block_offset_from_containining_block_top = state
.current_block_position_including_margins() -
state.current_containing_block_offset();
state.place_float_fragment(
fragment,
CollapsedMargin::zero(),
block_offset_from_containining_block_top,
);
}
/// Given a new potential line size for the current line, create a "placement" for that line.
/// This tells us whether or not the new potential line will fit in the current block position
/// or need to be moved. In addition, the placement rect determinse the inline start and end
/// of the line if it's used as the final placement among floats.
fn place_line_among_floats(&self, potential_line_size: &Vec2<Length>) -> Rect<Length> {
let sequential_layout_state = self
.sequential_layout_state
.as_ref()
.expect("Should not have called this function without having floats.");
let ifc_offset_in_float_container = Vec2 {
inline: sequential_layout_state
.floats
.containing_block_info
.inline_start,
block: sequential_layout_state
.floats
.containing_block_info
.block_start +
sequential_layout_state
.floats
.containing_block_info
.block_start_margins_not_collapsed
.solve(),
};
let ceiling = self
.current_line
.line_block_start_considering_float_placement();
let mut placement = PlacementAmongFloats::new(
&sequential_layout_state.floats,
ceiling + ifc_offset_in_float_container.block,
potential_line_size.clone(),
&PaddingBorderMargin::zero(),
);
let mut placement_rect = placement.place();
placement_rect.start_corner = &placement_rect.start_corner - &ifc_offset_in_float_container;
placement_rect
}
/// Returns true if a new potential line size for the current line would require a line
/// break. This takes into account floats and will also update the "placement among
/// floats" for this line if the potential line size would not cause a line break.
/// Thus, calling this method has side effects and should only be done while in the
/// process of laying out line content that is always going to be committed to this
/// line or the next.
fn new_potential_line_size_causes_line_break(
&mut self,
potential_line_size: &Vec2<Length>,
) -> bool {
// If this is the first content on the line and we already have a float placement,
// that means that the placement was initialized by a leading float in the IFC.
// This placement needs to be updated, because the first line content might push
// the block start of the line downward.
if !self.current_line.has_content && self.sequential_layout_state.is_some() {
let new_placement = self.place_line_among_floats(potential_line_size);
self.current_line.replace_float_placement(new_placement);
}
if potential_line_size.inline > self.containing_block.inline_size {
return true;
}
// If we already have a placement among floats for this line and the new potential
// line size, causes a change in the block position, then we will need a line
// break. This block of code also takes the opportunity to update the placement
// among floats in the case that line does fit at the same block position (because
// its inline start may change).
let old_placement = self.current_line.float_placement.get().cloned();
if let Some(old_placement) = old_placement {
if potential_line_size.block > old_placement.size.block {
let new_placement = self.place_line_among_floats(potential_line_size);
if new_placement.start_corner.block != old_placement.start_corner.block {
return true;
} else {
self.current_line.replace_float_placement(new_placement);
return false;
}
}
}
// Otherwise the new potential line size will require a newline if it fits in the
// inline space available for this line. This space may be smaller than the
// containing block if floats shrink the available inline space.
let available_inline_space = if self.sequential_layout_state.is_some() {
let float_placement = self
.current_line
.float_placement
.get_or_init(|| self.place_line_among_floats(potential_line_size));
float_placement.max_inline_position() - float_placement.start_corner.inline
} else {
self.containing_block.inline_size
};
potential_line_size.inline > available_inline_space
}
}
impl InlineFormattingContext {
pub(super) fn new(
text_decoration_line: TextDecorationLine,
has_first_formatted_line: bool,
ends_with_whitespace: bool,
) -> InlineFormattingContext {
InlineFormattingContext {
inline_level_boxes: Default::default(),
text_decoration_line,
has_first_formatted_line,
contains_floats: false,
ends_with_whitespace,
}
}
// This works on an already-constructed `InlineFormattingContext`,
// Which would have to change if/when
// `BlockContainer::construct` parallelize their construction.
pub(super) fn inline_content_sizes(
&self,
layout_context: &LayoutContext,
containing_block_writing_mode: WritingMode,
) -> ContentSizes {
struct Computation<'a> {
layout_context: &'a LayoutContext<'a>,
containing_block_writing_mode: WritingMode,
paragraph: ContentSizes,
current_line: ContentSizes,
/// Size for whitepsace pending to be added to this line.
pending_whitespace: Length,
/// Whether or not this IFC has seen any non-whitespace content.
had_non_whitespace_content_yet: bool,
/// The global linebreaking state.
linebreaker: Option<LineBreakLeafIter>,
}
impl Computation<'_> {
fn traverse(&mut self, inline_level_boxes: &[ArcRefCell<InlineLevelBox>]) {
for inline_level_box in inline_level_boxes {
match &mut *inline_level_box.borrow_mut() {
InlineLevelBox::InlineBox(inline_box) => {
let padding =
inline_box.style.padding(self.containing_block_writing_mode);
let border = inline_box
.style
.border_width(self.containing_block_writing_mode);
let margin =
inline_box.style.margin(self.containing_block_writing_mode);
macro_rules! add {
($condition: ident, $side: ident) => {
if inline_box.$condition {
// For margins and paddings, a cyclic percentage is resolved against zero
// for determining intrinsic size contributions.
// https://drafts.csswg.org/css-sizing-3/#min-percentage-contribution
let zero = Length::zero();
let mut length = padding.$side.percentage_relative_to(zero) + border.$side;
if let Some(lp) = margin.$side.non_auto() {
length += lp.percentage_relative_to(zero)
}
self.add_length(length);
}
};
}
add!(first_fragment, inline_start);
self.traverse(&inline_box.children);
add!(last_fragment, inline_end);
},
InlineLevelBox::TextRun(text_run) => {
let BreakAndShapeResult {
runs,
break_at_start,
..
} = text_run
.break_and_shape(self.layout_context, &mut self.linebreaker);
if break_at_start {
self.line_break_opportunity()
}
for run in &runs {
let advance = Length::from(run.glyph_store.total_advance());
if !run.glyph_store.is_whitespace() {
self.had_non_whitespace_content_yet = true;
self.current_line.min_content += advance;
self.current_line.max_content +=
self.pending_whitespace + advance;
self.pending_whitespace = Length::zero();
} else {
// Discard any leading whitespace in the IFC. This will always be trimmed.
if !self.had_non_whitespace_content_yet {
continue;
}
// Wait to take into account other whitespace until we see more content.
// Whitespace at the end of the IFC will always be trimmed.
self.line_break_opportunity();
self.pending_whitespace += advance;
}
}
},
InlineLevelBox::Atomic(atomic) => {
let outer = atomic.outer_inline_content_sizes(
self.layout_context,
self.containing_block_writing_mode,
);
self.current_line.min_content +=
self.pending_whitespace + outer.min_content;
self.current_line.max_content += outer.max_content;
self.pending_whitespace = Length::zero();
self.had_non_whitespace_content_yet = true;
},
InlineLevelBox::OutOfFlowFloatBox(_) |
InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(_) => {},
}
}
}
fn add_length(&mut self, l: Length) {
self.current_line.min_content += l;
self.current_line.max_content += l;
}
fn line_break_opportunity(&mut self) {
self.paragraph
.min_content
.max_assign(take(&mut self.current_line.min_content));
}
fn forced_line_break(&mut self) {
self.line_break_opportunity();
self.paragraph
.max_content
.max_assign(take(&mut self.current_line.max_content));
}
}
fn take<T: Zero>(x: &mut T) -> T {
std::mem::replace(x, T::zero())
}
let mut computation = Computation {
layout_context,
containing_block_writing_mode,
paragraph: ContentSizes::zero(),
current_line: ContentSizes::zero(),
pending_whitespace: Length::zero(),
had_non_whitespace_content_yet: false,
linebreaker: None,
};
computation.traverse(&self.inline_level_boxes);
computation.forced_line_break();
computation.paragraph
}
pub(super) fn layout(
&self,
layout_context: &LayoutContext,
positioning_context: &mut PositioningContext,
containing_block: &ContainingBlock,
sequential_layout_state: Option<&mut SequentialLayoutState>,
collapsible_with_parent_start_margin: CollapsibleWithParentStartMargin,
) -> FlowLayout {
let first_line_inline_start = if self.has_first_formatted_line {
containing_block
.style
.get_inherited_text()
.text_indent
.to_used_value(containing_block.inline_size.into())
.into()
} else {
Length::zero()
};
let mut ifc = InlineFormattingContextState {
positioning_context,
containing_block,
sequential_layout_state,
fragments: Vec::new(),
current_line: LineUnderConstruction::new(Vec2 {
inline: first_line_inline_start,
block: Length::zero(),
}),
linebreaker: None,
partial_inline_boxes_stack: Vec::new(),
current_nesting_level: InlineNestingLevelState {
remaining_boxes: InlineBoxChildIter::from_formatting_context(self),
line_items_so_far: Vec::with_capacity(self.inline_level_boxes.len()),
white_space: containing_block.style.clone_inherited_text().white_space,
text_decoration_line: self.text_decoration_line,
},
};
// FIXME(pcwalton): This assumes that margins never collapse through inline formatting
// contexts (i.e. that inline formatting contexts are never empty). Is that right?
// FIXME(mrobinson): This should not happen if the IFC collapses through.
if let Some(ref mut sequential_layout_state) = ifc.sequential_layout_state {
sequential_layout_state.collapse_margins();
// FIXME(mrobinson): Collapse margins in the containing block offsets as well??
}
loop {
if let Some(child) = ifc.current_nesting_level.remaining_boxes.next() {
match &mut *child.borrow_mut() {
InlineLevelBox::InlineBox(inline) => {
let partial =
PartialInlineBoxFragment::new(inline, child.clone(), &mut ifc);
ifc.partial_inline_boxes_stack.push(partial);
},
InlineLevelBox::TextRun(run) => {
run.layout_into_line_items(layout_context, &mut ifc)
},
InlineLevelBox::Atomic(atomic_formatting_context) => {
atomic_formatting_context.layout_into_line_items(layout_context, &mut ifc);
},
InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(box_) => {
ifc.current_nesting_level.line_items_so_far.push(
LineItem::AbsolutelyPositioned(AbsolutelyPositionedLineItem {
absolutely_positioned_box: box_.clone(),
}),
);
},
InlineLevelBox::OutOfFlowFloatBox(float_box) => {
float_box.layout_into_line_items(layout_context, &mut ifc);
},
}
} else if let Some(mut partial) = ifc.partial_inline_boxes_stack.pop() {
// We reached the end of the remaining boxes in this nesting level, so we finish it and
// start working on the parent nesting level again.
partial.finish_layout(
&mut ifc.current_nesting_level,
&mut ifc.current_line.inline_position,
true, /* at_end_of_inline_element */
);
ifc.current_nesting_level = partial.parent_nesting_level
} else {
// We reached the end of the entire IFC.
break;
}
}
let line_items = std::mem::take(&mut ifc.current_nesting_level.line_items_so_far);
ifc.finish_current_line(layout_context, line_items, containing_block);
let mut collapsible_margins_in_children = CollapsedBlockMargins::zero();
let content_block_size = ifc.current_line.start_position.block;
collapsible_margins_in_children.collapsed_through =
content_block_size == Length::zero() && collapsible_with_parent_start_margin.0;
return FlowLayout {
fragments: ifc.fragments,
content_block_size,
collapsible_margins_in_children,
};
}
/// Return true if this [InlineFormattingContext] is empty for the purposes of ignoring
/// during box tree construction. An IFC is empty if it only contains TextRuns with
/// completely collapsible whitespace. When that happens it can be ignored completely.
pub fn is_empty(&self) -> bool {
fn inline_level_boxes_are_empty(boxes: &[ArcRefCell<InlineLevelBox>]) -> bool {
boxes
.iter()
.all(|inline_level_box| inline_level_box_is_empty(&*inline_level_box.borrow()))
}
fn inline_level_box_is_empty(inline_level_box: &InlineLevelBox) -> bool {
match inline_level_box {
InlineLevelBox::InlineBox(_) => false,
InlineLevelBox::TextRun(text_run) => !text_run.has_uncollapsible_content,
InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(_) => false,
InlineLevelBox::OutOfFlowFloatBox(_) => false,
InlineLevelBox::Atomic(_) => false,
}
}
inline_level_boxes_are_empty(&self.inline_level_boxes)
}
}
impl<'box_tree> PartialInlineBoxFragment<'box_tree> {
fn new(
inline_box: &InlineBox,
this_inline_level_box: ArcRefCell<InlineLevelBox>,
ifc: &mut InlineFormattingContextState<'box_tree, '_, '_>,
) -> PartialInlineBoxFragment<'box_tree> {
let style = inline_box.style.clone();
let mut pbm = style.padding_border_margin(&ifc.containing_block);
if inline_box.first_fragment {
ifc.current_line.inline_position += pbm.padding.inline_start +
pbm.border.inline_start +
pbm.margin.inline_start.auto_is(Length::zero)
} else {
pbm.padding.inline_start = Length::zero();
pbm.border.inline_start = Length::zero();
pbm.margin.inline_start = LengthOrAuto::zero();
}
let text_decoration_line =
ifc.current_nesting_level.text_decoration_line | style.clone_text_decoration_line();
let white_space = style.clone_inherited_text().white_space;
PartialInlineBoxFragment {
base_fragment_info: inline_box.base_fragment_info,
style,
pbm,
was_part_of_previous_line: false,
parent_nesting_level: std::mem::replace(
&mut ifc.current_nesting_level,
InlineNestingLevelState {
remaining_boxes: InlineBoxChildIter::from_inline_level_box(
this_inline_level_box,
),
line_items_so_far: Vec::with_capacity(inline_box.children.len()),
white_space,
text_decoration_line: text_decoration_line,
},
),
}
}
fn finish_layout(
&mut self,
nesting_level: &mut InlineNestingLevelState,
inline_position: &mut Length,
at_end_of_inline_element: bool,
) {
// If we are finishing in order to fragment this InlineBox into multiple lines, do
// not add end margins, borders, and padding.
if !at_end_of_inline_element {
self.pbm.padding.inline_end = Length::zero();
self.pbm.border.inline_end = Length::zero();
self.pbm.margin.inline_end = LengthOrAuto::zero();
} else {
*inline_position += self.pbm.padding.inline_end +
self.pbm.border.inline_end +
self.pbm.margin.inline_end.auto_is(Length::zero)
}
self.parent_nesting_level
.line_items_so_far
.push(LineItem::InlineBox(InlineBoxLineItem {
base_fragment_info: self.base_fragment_info,
style: self.style.clone(),
pbm: self.pbm.clone(),
children: std::mem::take(&mut nesting_level.line_items_so_far),
always_make_fragment: !self.was_part_of_previous_line,
}));
// This InlineBox now has at least one Fragment that corresponds to it, so
// if subsequent lines can ignore it if it is empty on those lines.
self.was_part_of_previous_line = true;
// If this partial / inline box appears on any subsequent lines, it should not
// have any start margin, border, or padding.
self.pbm.padding.inline_start = Length::zero();
self.pbm.border.inline_start = Length::zero();
self.pbm.margin.inline_start = LengthOrAuto::zero();
}
}
impl IndependentFormattingContext {
fn layout_into_line_items(
&mut self,
layout_context: &LayoutContext,
ifc: &mut InlineFormattingContextState,
) {
let style = self.style();
let pbm = style.padding_border_margin(&ifc.containing_block);
let margin = pbm.margin.auto_is(Length::zero);
let pbm_sums = &(&pbm.padding + &pbm.border) + &margin;
let mut child_positioning_context = None;
// We need to know the inline size of the atomic before deciding whether to do the line break.
let fragment = match self {
IndependentFormattingContext::Replaced(replaced) => {
let size = replaced.contents.used_size_as_if_inline_element(
ifc.containing_block,
&replaced.style,
None,
&pbm,
);
let fragments = replaced
.contents
.make_fragments(&replaced.style, size.clone());
let content_rect = Rect {
start_corner: pbm_sums.start_offset(),
size,
};
BoxFragment::new(
replaced.base_fragment_info,
replaced.style.clone(),
fragments,
content_rect,
pbm.padding,
pbm.border,
margin,
None,
CollapsedBlockMargins::zero(),
)
},
IndependentFormattingContext::NonReplaced(non_replaced) => {
let box_size = non_replaced
.style
.content_box_size(&ifc.containing_block, &pbm);
let max_box_size = non_replaced
.style
.content_max_box_size(&ifc.containing_block, &pbm);
let min_box_size = non_replaced
.style
.content_min_box_size(&ifc.containing_block, &pbm)
.auto_is(Length::zero);
// https://drafts.csswg.org/css2/visudet.html#inlineblock-width
let tentative_inline_size = box_size.inline.auto_is(|| {
let available_size = ifc.containing_block.inline_size - pbm_sums.inline_sum();
non_replaced
.inline_content_sizes(layout_context)
.shrink_to_fit(available_size)
});
// https://drafts.csswg.org/css2/visudet.html#min-max-widths
// In this case “applying the rules above again” with a non-auto inline-size
// always results in that size.
let inline_size = tentative_inline_size
.clamp_between_extremums(min_box_size.inline, max_box_size.inline);
let containing_block_for_children = ContainingBlock {
inline_size,
block_size: box_size.block,
style: &non_replaced.style,
};
assert_eq!(
ifc.containing_block.style.writing_mode,
containing_block_for_children.style.writing_mode,
"Mixed writing modes are not supported yet"
);
// This always collects for the nearest positioned ancestor even if the parent positioning
// context doesn't. The thing is we haven't kept track up to this point and there isn't
// any harm in keeping the hoisted boxes separate.
child_positioning_context = Some(PositioningContext::new_for_subtree(
true, /* collects_for_nearest_positioned_ancestor */
));
let independent_layout = non_replaced.layout(
layout_context,
child_positioning_context.as_mut().unwrap(),
&containing_block_for_children,
);
// https://drafts.csswg.org/css2/visudet.html#block-root-margin
let tentative_block_size = box_size
.block
.auto_is(|| independent_layout.content_block_size);
// https://drafts.csswg.org/css2/visudet.html#min-max-heights
// In this case “applying the rules above again” with a non-auto block-size
// always results in that size.
let block_size = tentative_block_size
.clamp_between_extremums(min_box_size.block, max_box_size.block);
let content_rect = Rect {
start_corner: pbm_sums.start_offset(),
size: Vec2 {
block: block_size,
inline: inline_size,
},
};
BoxFragment::new(
non_replaced.base_fragment_info,
non_replaced.style.clone(),
independent_layout.fragments,
content_rect,
pbm.padding,
pbm.border,
margin,
None,
CollapsedBlockMargins::zero(),
)
},
};
let size = &pbm_sums.sum() + &fragment.content_rect.size;
let new_potential_line_size = Vec2 {