-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
inline.rs
1940 lines (1718 loc) · 87.2 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 http://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
use ServoArc;
use app_units::{Au, MIN_AU};
use block::AbsoluteAssignBSizesTraversal;
use context::LayoutContext;
use display_list::{DisplayListBuildState, InlineFlowDisplayListBuilding};
use display_list::StackingContextCollectionState;
use euclid::{Point2D, Size2D};
use floats::{FloatKind, Floats, PlacementInfo};
use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag};
use flow::{FlowFlags, EarlyAbsolutePositionInfo, GetBaseFlow, OpaqueFlow};
use flow_ref::FlowRef;
use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow};
use fragment::FragmentFlags;
use fragment::SpecificFragmentInfo;
use gfx::display_list::OpaqueNode;
use gfx::font::FontMetrics;
use gfx::font_context::FontContext;
use gfx_traits::print_tree::PrintTree;
use layout_debug;
use model::IntrinsicISizesContribution;
use range::{Range, RangeIndex};
use script_layout_interface::wrapper_traits::PseudoElementType;
use std::{fmt, i32, isize, mem};
use std::cmp::max;
use std::collections::VecDeque;
use std::sync::Arc;
use style::computed_values::display::T as Display;
use style::computed_values::overflow_x::T as StyleOverflow;
use style::computed_values::position::T as Position;
use style::computed_values::text_align::T as TextAlign;
use style::computed_values::text_justify::T as TextJustify;
use style::computed_values::white_space::T as WhiteSpace;
use style::logical_geometry::{LogicalRect, LogicalSize, WritingMode};
use style::properties::ComputedValues;
use style::servo::restyle_damage::ServoRestyleDamage;
use style::values::computed::box_::VerticalAlign;
use style::values::generics::box_::VerticalAlign as GenericVerticalAlign;
use style::values::specified::text::TextOverflowSide;
use text;
use traversal::PreorderFlowTraversal;
use unicode_bidi as bidi;
/// `Line`s are represented as offsets into the child list, rather than
/// as an object that "owns" fragments. Choosing a different set of line
/// breaks requires a new list of offsets, and possibly some splitting and
/// merging of TextFragments.
///
/// A similar list will keep track of the mapping between CSS fragments and
/// the corresponding fragments in the inline flow.
///
/// After line breaks are determined, render fragments in the inline flow may
/// overlap visually. For example, in the case of nested inline CSS fragments,
/// outer inlines must be at least as large as the inner inlines, for
/// purposes of drawing noninherited things like backgrounds, borders,
/// outlines.
///
/// N.B. roc has an alternative design where the list instead consists of
/// things like "start outer fragment, text, start inner fragment, text, end inner
/// fragment, text, end outer fragment, text". This seems a little complicated to
/// serve as the starting point, but the current design doesn't make it
/// hard to try out that alternative.
///
/// Line fragments also contain some metadata used during line breaking. The
/// green zone is the area that the line can expand to before it collides
/// with a float or a horizontal wall of the containing block. The block-start
/// inline-start corner of the green zone is the same as that of the line, but
/// the green zone can be taller and wider than the line itself.
#[derive(Clone, Debug, Serialize)]
pub struct Line {
/// A range of line indices that describe line breaks.
///
/// For example, consider the following HTML and rendered element with
/// linebreaks:
///
/// ~~~html
/// <span>I <span>like truffles, <img></span> yes I do.</span>
/// ~~~
///
/// ~~~text
/// +------------+
/// | I like |
/// | truffles, |
/// | +----+ |
/// | | | |
/// | +----+ yes |
/// | I do. |
/// +------------+
/// ~~~
///
/// The ranges that describe these lines would be:
///
/// | [0, 2) | [2, 3) | [3, 5) | [5, 6) |
/// |----------|-------------|-------------|----------|
/// | 'I like' | 'truffles,' | '<img> yes' | 'I do.' |
pub range: Range<FragmentIndex>,
/// The bidirectional embedding level runs for this line, in visual order.
///
/// Can be set to `None` if the line is 100% left-to-right.
pub visual_runs: Option<Vec<(Range<FragmentIndex>, bidi::Level)>>,
/// The bounds are the exact position and extents of the line with respect
/// to the parent box.
///
/// For example, for the HTML below...
///
/// ~~~html
/// <div><span>I <span>like truffles, <img></span></div>
/// ~~~
///
/// ...the bounds would be:
///
/// ~~~text
/// +-----------------------------------------------------------+
/// | ^ |
/// | | |
/// | origin.y |
/// | | |
/// | v |
/// |< - origin.x ->+ - - - - - - - - +---------+---- |
/// | | | | ^ |
/// | | | <img> | size.block |
/// | I like truffles, | | v |
/// | + - - - - - - - - +---------+---- |
/// | | | |
/// | |<------ size.inline ------>| |
/// | |
/// | |
/// +-----------------------------------------------------------+
/// ~~~
pub bounds: LogicalRect<Au>,
/// The green zone is the greatest extent from which a line can extend to
/// before it collides with a float.
///
/// ~~~text
/// +-----------------------+
/// |::::::::::::::::: |
/// |:::::::::::::::::FFFFFF|
/// |============:::::FFFFFF|
/// |:::::::::::::::::FFFFFF|
/// |:::::::::::::::::FFFFFF|
/// |::::::::::::::::: |
/// | FFFFFFFFF |
/// | FFFFFFFFF |
/// | FFFFFFFFF |
/// | |
/// +-----------------------+
///
/// === line
/// ::: green zone
/// FFF float
/// ~~~
pub green_zone: LogicalSize<Au>,
/// The minimum metrics for this line, as specified by the style.
pub minimum_metrics: LineMetrics,
/// The actual metrics for this line.
pub metrics: LineMetrics,
}
impl Line {
fn new(writing_mode: WritingMode, minimum_metrics: &LineMetrics) -> Line {
Line {
range: Range::empty(),
visual_runs: None,
bounds: LogicalRect::zero(writing_mode),
green_zone: LogicalSize::zero(writing_mode),
minimum_metrics: *minimum_metrics,
metrics: *minimum_metrics,
}
}
/// Returns the new metrics that this line would have if `new_fragment` were added to it.
///
/// FIXME(pcwalton): this assumes that the tallest fragment in the line determines the line
/// block-size. This might not be the case with some weird text fonts.
fn new_metrics_for_fragment(&self, new_fragment: &Fragment, layout_context: &LayoutContext)
-> LineMetrics {
if !new_fragment.is_vertically_aligned_to_top_or_bottom() {
let fragment_inline_metrics =
new_fragment.aligned_inline_metrics(layout_context, &self.minimum_metrics, None);
self.metrics.new_metrics_for_fragment(&fragment_inline_metrics)
} else {
self.metrics
}
}
/// Returns the new block size that this line would have if `new_fragment` were added to it.
/// `new_inline_metrics` represents the new inline metrics that this line would have; it can
/// be computed with `new_inline_metrics()`.
fn new_block_size_for_fragment(&self,
new_fragment: &Fragment,
new_line_metrics: &LineMetrics,
layout_context: &LayoutContext)
-> Au {
let new_block_size = if new_fragment.is_vertically_aligned_to_top_or_bottom() {
max(new_fragment.aligned_inline_metrics(layout_context, &self.minimum_metrics, None)
.space_needed(),
self.minimum_metrics.space_needed())
} else {
new_line_metrics.space_needed()
};
max(self.bounds.size.block, new_block_size)
}
}
int_range_index! {
#[derive(Serialize)]
#[doc = "The index of a fragment in a flattened vector of DOM elements."]
struct FragmentIndex(isize)
}
/// Arranges fragments into lines, splitting them up as necessary.
struct LineBreaker {
/// The floats we need to flow around.
floats: Floats,
/// The resulting fragment list for the flow, consisting of possibly-broken fragments.
new_fragments: Vec<Fragment>,
/// The next fragment or fragments that we need to work on.
work_list: VecDeque<Fragment>,
/// The line we're currently working on.
pending_line: Line,
/// The lines we've already committed.
lines: Vec<Line>,
/// The index of the last known good line breaking opportunity. The opportunity will either
/// be inside this fragment (if it is splittable) or immediately prior to it.
last_known_line_breaking_opportunity: Option<FragmentIndex>,
/// The current position in the block direction.
cur_b: Au,
/// The computed value of the indentation for the first line (`text-indent`, CSS 2.1 § 16.1).
first_line_indentation: Au,
/// The minimum metrics for each line, as specified by the line height and font style.
minimum_metrics: LineMetrics,
}
impl LineBreaker {
/// Creates a new `LineBreaker` with a set of floats and the indentation of the first line.
fn new(float_context: Floats, first_line_indentation: Au, minimum_line_metrics: &LineMetrics)
-> LineBreaker {
LineBreaker {
new_fragments: Vec::new(),
work_list: VecDeque::new(),
pending_line: Line::new(float_context.writing_mode, minimum_line_metrics),
floats: float_context,
lines: Vec::new(),
cur_b: Au(0),
last_known_line_breaking_opportunity: None,
first_line_indentation: first_line_indentation,
minimum_metrics: *minimum_line_metrics,
}
}
/// Resets the `LineBreaker` to the initial state it had after a call to `new`.
fn reset_scanner(&mut self) {
self.lines = Vec::new();
self.new_fragments = Vec::new();
self.cur_b = Au(0);
self.reset_line();
}
/// Reinitializes the pending line to blank data.
fn reset_line(&mut self) -> Line {
self.last_known_line_breaking_opportunity = None;
mem::replace(&mut self.pending_line,
Line::new(self.floats.writing_mode, &self.minimum_metrics))
}
/// Reflows fragments for the given inline flow.
fn scan_for_lines(&mut self,
flow: &mut InlineFlow,
layout_context: &LayoutContext) {
self.reset_scanner();
// Create our fragment iterator.
debug!("LineBreaker: scanning for lines, {} fragments", flow.fragments.len());
let mut old_fragments = mem::replace(&mut flow.fragments, InlineFragments::new());
let old_fragment_iter = old_fragments.fragments.into_iter();
// TODO(pcwalton): This would likely be better as a list of dirty line
// indices. That way we could resynchronize if we discover during reflow
// that all subsequent fragments must have the same position as they had
// in the previous reflow. I don't know how common this case really is
// in practice, but it's probably worth handling.
self.lines = Vec::new();
// Do the reflow.
self.reflow_fragments(old_fragment_iter, flow, layout_context);
// Perform unicode bidirectional layout.
let para_level = flow.base.writing_mode.to_bidi_level();
// The text within a fragment is at a single bidi embedding level
// (because we split fragments on level run boundaries during flow
// construction), so we can build a level array with just one entry per
// fragment.
let levels: Vec<bidi::Level> = self.new_fragments.iter().map(
|fragment| match fragment.specific {
SpecificFragmentInfo::ScannedText(ref info) => info.run.bidi_level,
_ => para_level
}
).collect();
let mut lines = mem::replace(&mut self.lines, Vec::new());
// If everything is LTR, don't bother with reordering.
if bidi::level::has_rtl(&levels) {
// Compute and store the visual ordering of the fragments within the
// line.
for line in &mut lines {
let range = line.range.begin().to_usize()..line.range.end().to_usize();
// FIXME: Update to use BidiInfo::visual_runs, as this algorithm needs access to
// the original text and original BidiClass of its characters.
#[allow(deprecated)]
let runs = bidi::deprecated::visual_runs(range, &levels);
line.visual_runs = Some(runs.iter().map(|run| {
let start = FragmentIndex(run.start as isize);
let len = FragmentIndex(run.len() as isize);
(Range::new(start, len), levels[run.start])
}).collect());
}
}
// Place the fragments back into the flow.
old_fragments.fragments = mem::replace(&mut self.new_fragments, vec![]);
flow.fragments = old_fragments;
flow.lines = lines;
}
/// Reflows the given fragments, which have been plucked out of the inline flow.
fn reflow_fragments<'a, I>(&mut self,
mut old_fragment_iter: I,
flow: &'a InlineFlow,
layout_context: &LayoutContext)
where I: Iterator<Item=Fragment>,
{
loop {
// Acquire the next fragment to lay out from the work list or fragment list, as
// appropriate.
let fragment = match self.next_unbroken_fragment(&mut old_fragment_iter) {
None => break,
Some(fragment) => fragment,
};
// Do not reflow truncated fragments. Reflow the original fragment only.
let fragment = if fragment.flags.contains(FragmentFlags::IS_ELLIPSIS) {
continue
} else if let SpecificFragmentInfo::TruncatedFragment(info) = fragment.specific {
info.full
} else {
fragment
};
// Try to append the fragment.
self.reflow_fragment(fragment, flow, layout_context);
}
if !self.pending_line_is_empty() {
debug!("LineBreaker: partially full line {} at end of scanning; committing it",
self.lines.len());
self.flush_current_line()
}
}
/// Acquires a new fragment to lay out from the work list or fragment list as appropriate.
/// Note that you probably don't want to call this method directly in order to be incremental-
/// reflow-safe; try `next_unbroken_fragment` instead.
fn next_fragment<I>(&mut self,
old_fragment_iter: &mut I)
-> Option<Fragment>
where I: Iterator<Item=Fragment>,
{
self.work_list.pop_front().or_else(|| old_fragment_iter.next())
}
/// Acquires a new fragment to lay out from the work list or fragment list,
/// merging it with any subsequent fragments as appropriate. In effect, what
/// this method does is to return the next fragment to lay out, undoing line
/// break operations that any previous reflows may have performed. You
/// probably want to be using this method instead of `next_fragment`.
fn next_unbroken_fragment<I>(&mut self,
old_fragment_iter: &mut I)
-> Option<Fragment>
where I: Iterator<Item=Fragment>,
{
let mut result = self.next_fragment(old_fragment_iter)?;
loop {
let candidate = match self.next_fragment(old_fragment_iter) {
None => return Some(result),
Some(fragment) => fragment,
};
let need_to_merge = match (&mut result.specific, &candidate.specific) {
(&mut SpecificFragmentInfo::ScannedText(ref mut result_info),
&SpecificFragmentInfo::ScannedText(ref candidate_info)) => {
result.margin.inline_end == Au(0) &&
candidate.margin.inline_start == Au(0) &&
result.border_padding.inline_end == Au(0) &&
candidate.border_padding.inline_start == Au(0) &&
result_info.selected() == candidate_info.selected() &&
Arc::ptr_eq(&result_info.run, &candidate_info.run) &&
inline_contexts_are_equal(&result.inline_context,
&candidate.inline_context)
}
_ => false,
};
if need_to_merge {
result.merge_with(candidate);
continue
}
self.work_list.push_front(candidate);
return Some(result)
}
}
/// Commits a line to the list.
fn flush_current_line(&mut self) {
debug!("LineBreaker: flushing line {}: {:?}", self.lines.len(), self.pending_line);
self.strip_trailing_whitespace_from_pending_line_if_necessary();
self.lines.push(self.pending_line.clone());
self.cur_b = self.pending_line.bounds.start.b + self.pending_line.bounds.size.block;
self.reset_line();
}
/// Removes trailing whitespace from the pending line if necessary. This is done right before
/// flushing it.
fn strip_trailing_whitespace_from_pending_line_if_necessary(&mut self) {
if self.pending_line.range.is_empty() {
return
}
let last_fragment_index = self.pending_line.range.end() - FragmentIndex(1);
let fragment = &mut self.new_fragments[last_fragment_index.get() as usize];
let old_fragment_inline_size = fragment.border_box.size.inline;
fragment.strip_trailing_whitespace_if_necessary();
self.pending_line.bounds.size.inline +=
fragment.border_box.size.inline - old_fragment_inline_size;
}
/// Computes the position of a line that has only the provided fragment. Returns the bounding
/// rect of the line's green zone (whose origin coincides with the line's origin) and the
/// actual inline-size of the first fragment after splitting.
fn initial_line_placement(&self,
flow: &InlineFlow,
first_fragment: &Fragment,
ceiling: Au)
-> (LogicalRect<Au>, Au) {
debug!("LineBreaker: trying to place first fragment of line {}; fragment size: {:?}, \
splittable: {}",
self.lines.len(),
first_fragment.border_box.size,
first_fragment.can_split());
// Initially, pretend a splittable fragment has zero inline-size. We will move it later if
// it has nonzero inline-size and that causes problems.
let placement_inline_size = if first_fragment.can_split() {
first_fragment.minimum_splittable_inline_size()
} else {
first_fragment.margin_box_inline_size() + self.indentation_for_pending_fragment()
};
// Try to place the fragment between floats.
let line_bounds = self.floats.place_between_floats(&PlacementInfo {
size: LogicalSize::new(self.floats.writing_mode,
placement_inline_size,
first_fragment.border_box.size.block),
ceiling: ceiling,
max_inline_size: flow.base.position.size.inline,
kind: FloatKind::Left,
});
let fragment_margin_box_inline_size = first_fragment.margin_box_inline_size();
// Simple case: if the fragment fits, then we can stop here.
if line_bounds.size.inline > fragment_margin_box_inline_size {
debug!("LineBreaker: fragment fits on line {}", self.lines.len());
return (line_bounds, fragment_margin_box_inline_size);
}
// If not, but we can't split the fragment, then we'll place the line here and it will
// overflow.
if !first_fragment.can_split() {
debug!("LineBreaker: line doesn't fit, but is unsplittable");
}
(line_bounds, fragment_margin_box_inline_size)
}
/// Performs float collision avoidance. This is called when adding a fragment is going to
/// increase the block-size, and because of that we will collide with some floats.
///
/// We have two options here:
/// 1) Move the entire line so that it doesn't collide any more.
/// 2) Break the line and put the new fragment on the next line.
///
/// The problem with option 1 is that we might move the line and then wind up breaking anyway,
/// which violates the standard. But option 2 is going to look weird sometimes.
///
/// So we'll try to move the line whenever we can, but break if we have to.
///
/// Returns false if and only if we should break the line.
fn avoid_floats(&mut self,
flow: &InlineFlow,
in_fragment: Fragment,
new_block_size: Au)
-> bool {
debug!("LineBreaker: entering float collision avoider!");
// First predict where the next line is going to be.
let (next_line, first_fragment_inline_size) =
self.initial_line_placement(flow,
&in_fragment,
self.pending_line.bounds.start.b);
let next_green_zone = next_line.size;
let new_inline_size = self.pending_line.bounds.size.inline + first_fragment_inline_size;
// Now, see if everything can fit at the new location.
if next_green_zone.inline >= new_inline_size && next_green_zone.block >= new_block_size {
debug!("LineBreaker: case=adding fragment collides vertically with floats: moving \
line");
self.pending_line.bounds.start = next_line.start;
self.pending_line.green_zone = next_green_zone;
debug_assert!(!self.pending_line_is_empty(), "Non-terminating line breaking");
self.work_list.push_front(in_fragment);
return true
}
debug!("LineBreaker: case=adding fragment collides vertically with floats: breaking line");
self.work_list.push_front(in_fragment);
false
}
/// Tries to append the given fragment to the line, splitting it if necessary. Commits the
/// current line if needed.
fn reflow_fragment(&mut self,
mut fragment: Fragment,
flow: &InlineFlow,
layout_context: &LayoutContext) {
// Undo any whitespace stripping from previous reflows.
fragment.reset_text_range_and_inline_size();
// Determine initial placement for the fragment if we need to.
//
// Also, determine whether we can legally break the line before, or
// inside, this fragment.
let fragment_is_line_break_opportunity = if self.pending_line_is_empty() {
fragment.strip_leading_whitespace_if_necessary();
let (line_bounds, _) = self.initial_line_placement(flow, &fragment, self.cur_b);
self.pending_line.bounds.start = line_bounds.start;
self.pending_line.green_zone = line_bounds.size;
false
} else {
if fragment.suppress_line_break_before() {
false
} else {
fragment.white_space().allow_wrap()
}
};
debug!("LineBreaker: trying to append to line {} \
(fragment size: {:?}, green zone: {:?}): {:?}",
self.lines.len(),
fragment.border_box.size,
self.pending_line.green_zone,
fragment);
// NB: At this point, if `green_zone.inline <
// self.pending_line.bounds.size.inline` or `green_zone.block <
// self.pending_line.bounds.size.block`, then we committed a line that
// overlaps with floats.
let green_zone = self.pending_line.green_zone;
let new_line_metrics = self.pending_line.new_metrics_for_fragment(&fragment,
layout_context);
let new_block_size = self.pending_line.new_block_size_for_fragment(&fragment,
&new_line_metrics,
layout_context);
if new_block_size > green_zone.block {
// Uh-oh. Float collision imminent. Enter the float collision avoider!
if !self.avoid_floats(flow, fragment, new_block_size) {
self.flush_current_line();
}
return
}
// Record the last known good line break opportunity if this is one.
if fragment_is_line_break_opportunity {
self.last_known_line_breaking_opportunity = Some(self.pending_line.range.end())
}
// If we must flush the line after finishing this fragment due to `white-space: pre`,
// detect that.
let line_flush_mode = if fragment.white_space().preserve_newlines() {
if fragment.requires_line_break_afterward_if_wrapping_on_newlines() {
LineFlushMode::Flush
} else {
LineFlushMode::No
}
} else {
LineFlushMode::No
};
// If we're not going to overflow the green zone vertically, we might still do so
// horizontally. We'll try to place the whole fragment on this line and break somewhere if
// it doesn't fit.
let indentation = self.indentation_for_pending_fragment();
let new_inline_size = self.pending_line.bounds.size.inline +
fragment.margin_box_inline_size() + indentation;
if new_inline_size <= green_zone.inline {
debug!("LineBreaker: fragment fits without splitting");
self.push_fragment_to_line(layout_context, fragment, line_flush_mode);
return
}
// If the wrapping mode prevents us from splitting, then back up and split at the last
// known good split point.
if !fragment.white_space().allow_wrap() {
debug!("LineBreaker: fragment can't split; falling back to last known good split point");
self.split_line_at_last_known_good_position(layout_context, fragment, line_flush_mode);
return;
}
// Split it up!
let available_inline_size = green_zone.inline -
self.pending_line.bounds.size.inline -
indentation;
let inline_start_fragment;
let inline_end_fragment;
let split_result = match fragment.calculate_split_position(available_inline_size,
self.pending_line_is_empty()) {
None => {
// We failed to split. Defer to the next line if we're allowed to; otherwise,
// rewind to the last line breaking opportunity.
if fragment_is_line_break_opportunity {
debug!("LineBreaker: fragment was unsplittable; deferring to next line");
self.work_list.push_front(fragment);
self.flush_current_line();
} else {
self.split_line_at_last_known_good_position(layout_context,
fragment,
LineFlushMode::No);
}
return
}
Some(split_result) => split_result,
};
inline_start_fragment = split_result.inline_start.as_ref().map(|x| {
fragment.transform_with_split_info(x, split_result.text_run.clone())
});
inline_end_fragment = split_result.inline_end.as_ref().map(|x| {
fragment.transform_with_split_info(x, split_result.text_run.clone())
});
// Push the first fragment onto the line we're working on and start off the next line with
// the second fragment. If there's no second fragment, the next line will start off empty.
match (inline_start_fragment, inline_end_fragment) {
(Some(mut inline_start_fragment), Some(mut inline_end_fragment)) => {
inline_start_fragment.border_padding.inline_end = Au(0);
if let Some(ref mut inline_context) = inline_start_fragment.inline_context {
for node in &mut inline_context.nodes {
node.flags.remove(InlineFragmentNodeFlags::LAST_FRAGMENT_OF_ELEMENT);
}
}
inline_start_fragment.border_box.size.inline += inline_start_fragment.border_padding.inline_start;
inline_end_fragment.border_padding.inline_start = Au(0);
if let Some(ref mut inline_context) = inline_end_fragment.inline_context {
for node in &mut inline_context.nodes {
node.flags.remove(InlineFragmentNodeFlags::FIRST_FRAGMENT_OF_ELEMENT);
}
}
inline_end_fragment.border_box.size.inline += inline_end_fragment.border_padding.inline_end;
self.push_fragment_to_line(layout_context,
inline_start_fragment,
LineFlushMode::Flush);
self.work_list.push_front(inline_end_fragment)
},
(Some(fragment), None) => {
self.push_fragment_to_line(layout_context, fragment, line_flush_mode);
}
(None, Some(fragment)) => {
// Yes, this can happen!
self.flush_current_line();
self.work_list.push_front(fragment)
}
(None, None) => {}
}
}
/// Pushes a fragment to the current line unconditionally, possibly truncating it and placing
/// an ellipsis based on the value of `text-overflow`. If `flush_line` is `Flush`, then flushes
/// the line afterward;
fn push_fragment_to_line(&mut self,
layout_context: &LayoutContext,
fragment: Fragment,
line_flush_mode: LineFlushMode) {
let indentation = self.indentation_for_pending_fragment();
if self.pending_line_is_empty() {
debug_assert!(self.new_fragments.len() <= (isize::MAX as usize));
self.pending_line.range.reset(FragmentIndex(self.new_fragments.len() as isize),
FragmentIndex(0));
}
// Determine if an ellipsis will be necessary to account for `text-overflow`.
let available_inline_size = self.pending_line.green_zone.inline -
self.pending_line.bounds.size.inline - indentation;
let ellipsis = match (&fragment.style().get_text().text_overflow.second,
fragment.style().get_box().overflow_x) {
(&TextOverflowSide::Clip, _) | (_, StyleOverflow::Visible) => None,
(&TextOverflowSide::Ellipsis, _) => {
if fragment.margin_box_inline_size() > available_inline_size {
Some("…".to_string())
} else {
None
}
},
(&TextOverflowSide::String(ref string), _) => {
if fragment.margin_box_inline_size() > available_inline_size {
Some(string.to_string())
} else {
None
}
}
};
if let Some(string) = ellipsis {
let ellipsis = fragment.transform_into_ellipsis(layout_context, string);
let truncated = fragment.truncate_to_inline_size(available_inline_size -
ellipsis.margin_box_inline_size());
self.push_fragment_to_line_ignoring_text_overflow(truncated, layout_context);
self.push_fragment_to_line_ignoring_text_overflow(ellipsis, layout_context);
} else {
self.push_fragment_to_line_ignoring_text_overflow(fragment, layout_context);
}
if line_flush_mode == LineFlushMode::Flush {
self.flush_current_line()
}
}
/// Pushes a fragment to the current line unconditionally, without placing an ellipsis in the
/// case of `text-overflow: ellipsis`.
fn push_fragment_to_line_ignoring_text_overflow(&mut self,
fragment: Fragment,
layout_context: &LayoutContext) {
let indentation = self.indentation_for_pending_fragment();
self.pending_line.range.extend_by(FragmentIndex(1));
if !fragment.is_inline_absolute() && !fragment.is_hypothetical() {
self.pending_line.bounds.size.inline = self.pending_line.bounds.size.inline +
fragment.margin_box_inline_size() + indentation;
self.pending_line.metrics = self.pending_line.new_metrics_for_fragment(&fragment,
layout_context);
self.pending_line.bounds.size.block =
self.pending_line.new_block_size_for_fragment(&fragment,
&self.pending_line.metrics,
layout_context);
}
self.new_fragments.push(fragment);
}
fn split_line_at_last_known_good_position(&mut self,
layout_context: &LayoutContext,
cur_fragment: Fragment,
line_flush_mode: LineFlushMode) {
let last_known_line_breaking_opportunity =
match self.last_known_line_breaking_opportunity {
None => {
// No line breaking opportunity exists at all for this line. Overflow.
self.push_fragment_to_line(layout_context, cur_fragment, line_flush_mode);
return;
}
Some(last_known_line_breaking_opportunity) => last_known_line_breaking_opportunity,
};
self.work_list.push_front(cur_fragment);
for fragment_index in (last_known_line_breaking_opportunity.get()..
self.pending_line.range.end().get()).rev() {
debug_assert!(fragment_index == (self.new_fragments.len() as isize) - 1);
self.work_list.push_front(self.new_fragments.pop().unwrap());
}
// FIXME(pcwalton): This should actually attempt to split the last fragment if
// possible to do so, to handle cases like:
//
// (available width)
// +-------------+
// The alphabet
// (<em>abcdefghijklmnopqrstuvwxyz</em>)
//
// Here, the last known-good split point is inside the fragment containing
// "The alphabet (", which has already been committed by the time we get to this
// point. Unfortunately, the existing splitting API (`calculate_split_position`)
// has no concept of "split right before the last non-whitespace position". We'll
// need to add that feature to the API to handle this case correctly.
self.pending_line.range.extend_to(last_known_line_breaking_opportunity);
self.flush_current_line();
}
/// Returns the indentation that needs to be applied before the fragment we're reflowing.
fn indentation_for_pending_fragment(&self) -> Au {
if self.pending_line_is_empty() && self.lines.is_empty() {
self.first_line_indentation
} else {
Au(0)
}
}
/// Returns true if the pending line is empty and false otherwise.
fn pending_line_is_empty(&self) -> bool {
self.pending_line.range.length() == FragmentIndex(0)
}
}
/// Represents a list of inline fragments, including element ranges.
#[derive(Clone, Serialize)]
pub struct InlineFragments {
/// The fragments themselves.
pub fragments: Vec<Fragment>,
}
impl InlineFragments {
/// Creates an empty set of inline fragments.
pub fn new() -> InlineFragments {
InlineFragments {
fragments: vec![],
}
}
/// Returns the number of inline fragments.
pub fn len(&self) -> usize {
self.fragments.len()
}
/// Returns true if this list contains no fragments and false if it contains at least one
/// fragment.
pub fn is_empty(&self) -> bool {
self.fragments.is_empty()
}
/// A convenience function to return the fragment at a given index.
pub fn get(&self, index: usize) -> &Fragment {
&self.fragments[index]
}
/// A convenience function to return a mutable reference to the fragment at a given index.
pub fn get_mut(&mut self, index: usize) -> &mut Fragment {
&mut self.fragments[index]
}
}
#[allow(unsafe_code)]
unsafe impl ::flow::HasBaseFlow for InlineFlow {}
/// Flows for inline layout.
#[derive(Serialize)]
#[repr(C)]
pub struct InlineFlow {
/// Data common to all flows.
pub base: BaseFlow,
/// A vector of all inline fragments. Several fragments may correspond to one node/element.
pub fragments: InlineFragments,
/// A vector of ranges into fragments that represents line positions. These ranges are disjoint
/// and are the result of inline layout. This also includes some metadata used for positioning
/// lines.
pub lines: Vec<Line>,
/// The minimum metrics for each line, as specified by the line height and font style.
pub minimum_line_metrics: LineMetrics,
/// The amount of indentation to use on the first line. This is determined by our block parent
/// (because percentages are relative to the containing block, and we aren't in a position to
/// compute things relative to our parent's containing block).
pub first_line_indentation: Au,
}
impl InlineFlow {
pub fn from_fragments(fragments: InlineFragments, writing_mode: WritingMode) -> InlineFlow {
let mut flow = InlineFlow {
base: BaseFlow::new(None, writing_mode, ForceNonfloatedFlag::ForceNonfloated),
fragments: fragments,
lines: Vec::new(),
minimum_line_metrics: LineMetrics::new(Au(0), Au(0)),
first_line_indentation: Au(0),
};
if flow.fragments.fragments.iter().any(Fragment::is_unscanned_generated_content) {
flow.base.restyle_damage.insert(ServoRestyleDamage::RESOLVE_GENERATED_CONTENT);
}
flow
}
/// Sets fragment positions in the inline direction based on alignment for one line. This
/// performs text justification if mandated by the style.
fn set_inline_fragment_positions(fragments: &mut InlineFragments,
line: &Line,
line_align: TextAlign,
indentation: Au,
is_last_line: bool) {
// Figure out how much inline-size we have.
let slack_inline_size = max(Au(0), line.green_zone.inline - line.bounds.size.inline);
// Compute the value we're going to use for `text-justify`.
if fragments.fragments.is_empty() {
return
}
let text_justify = fragments.fragments[0].style().get_inheritedtext().text_justify;
// Translate `left` and `right` to logical directions.
let is_ltr = fragments.fragments[0].style().writing_mode.is_bidi_ltr();
let line_align = match (line_align, is_ltr) {
(TextAlign::Left, true) |
(TextAlign::ServoLeft, true) |
(TextAlign::Right, false) |
(TextAlign::ServoRight, false) => TextAlign::Start,
(TextAlign::Left, false) |
(TextAlign::ServoLeft, false) |
(TextAlign::Right, true) |
(TextAlign::ServoRight, true) => TextAlign::End,
_ => line_align
};
// Set the fragment inline positions based on that alignment, and justify the text if
// necessary.
let mut inline_start_position_for_fragment = line.bounds.start.i + indentation;
match line_align {
TextAlign::Justify if !is_last_line && text_justify != TextJustify::None => {
InlineFlow::justify_inline_fragments(fragments, line, slack_inline_size)
}
TextAlign::Justify | TextAlign::Start => {}
TextAlign::Center | TextAlign::ServoCenter => {
inline_start_position_for_fragment = inline_start_position_for_fragment +
slack_inline_size.scale_by(0.5)
}
TextAlign::End => {
inline_start_position_for_fragment = inline_start_position_for_fragment +
slack_inline_size
}
TextAlign::Left |
TextAlign::ServoLeft |
TextAlign::Right |
TextAlign::ServoRight => unreachable!()
}
// Lay out the fragments in visual order.
let run_count = match line.visual_runs {
Some(ref runs) => runs.len(),
None => 1
};
for run_idx in 0..run_count {
let (range, level) = match line.visual_runs {
Some(ref runs) if is_ltr => runs[run_idx],
Some(ref runs) => runs[run_count - run_idx - 1], // reverse order for RTL runs
None => (line.range, bidi::Level::ltr())
};
struct MaybeReverse<I> {
iter: I,
reverse: bool,
}
impl<I: DoubleEndedIterator> Iterator for MaybeReverse<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
if self.reverse {
self.iter.next_back()
} else {
self.iter.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
// If the bidi embedding direction is opposite the layout direction, lay out this