mirror of
https://github.com/servo/servo.git
synced 2025-08-08 23:15:33 +01:00
layout: Add a InlineFormattingContextBuilder
(#32415)
The main change here is that collapsed and `text-transform`'d text is computed as it's processed by DOM traversal. This single transformed text is stored in the root of the `InlineFormattingContext`. This will eventually allow performing linebreaking and shaping of the entire inline formatting context at once. Allowing for intelligent processing of linebreaking and also shaping across elements. This matches more closely what LayoutNG does. This shouldn't have any (or negligable) behavioral changes, but will allow us to prevent linebreaking inside of clusters in a followup change. Co-authored-by: Rakhi Sharma <atbrakhi@igalia.com>
This commit is contained in:
parent
00b77ce73c
commit
48ab8d8847
12 changed files with 964 additions and 805 deletions
610
components/layout_2020/flow/inline/construct.rs
Normal file
610
components/layout_2020/flow/inline/construct.rs
Normal file
|
@ -0,0 +1,610 @@
|
|||
/* 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 std::borrow::Cow;
|
||||
use std::char::{ToLowercase, ToUppercase};
|
||||
|
||||
use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
|
||||
use style::values::computed::{TextDecorationLine, TextTransform};
|
||||
use style::values::specified::text::TextTransformCase;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use super::text_run::TextRun;
|
||||
use super::{InlineBox, InlineFormattingContext, InlineLevelBox};
|
||||
use crate::cell::ArcRefCell;
|
||||
use crate::context::LayoutContext;
|
||||
use crate::dom::NodeExt;
|
||||
use crate::dom_traversal::NodeAndStyleInfo;
|
||||
use crate::flow::float::FloatBox;
|
||||
use crate::formatting_contexts::IndependentFormattingContext;
|
||||
use crate::positioned::AbsolutelyPositionedBox;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct InlineFormattingContextBuilder {
|
||||
pub text_segments: Vec<String>,
|
||||
current_text_offset: usize,
|
||||
|
||||
/// Whether the last processed node ended 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.)
|
||||
last_inline_box_ended_with_collapsible_white_space: bool,
|
||||
|
||||
/// Whether or not the current state of the inline formatting context is on a word boundary
|
||||
/// for the purposes of `text-transform: capitalize`.
|
||||
on_word_boundary: bool,
|
||||
|
||||
/// Whether or not this inline formatting context will contain floats.
|
||||
pub contains_floats: bool,
|
||||
|
||||
/// Inline elements are direct descendants of the element that establishes
|
||||
/// the inline formatting context that this builder builds.
|
||||
pub root_inline_boxes: Vec<ArcRefCell<InlineLevelBox>>,
|
||||
|
||||
/// Whether or not the inline formatting context under construction has any
|
||||
/// uncollapsible text content.
|
||||
pub has_uncollapsible_text_content: bool,
|
||||
|
||||
/// The ongoing stack of inline boxes stack of the builder.
|
||||
///
|
||||
/// Contains all the currently ongoing inline boxes we entered so far.
|
||||
/// The traversal is at all times as deep in the tree as this stack is,
|
||||
/// which is why the code doesn't need to keep track of the actual
|
||||
/// container root (see `handle_inline_level_element`).
|
||||
///
|
||||
/// Whenever the end of a DOM element that represents an inline box is
|
||||
/// reached, the inline box at the top of this stack is complete and ready
|
||||
/// to be pushed to the children of the next last ongoing inline box
|
||||
/// the ongoing inline formatting context if the stack is now empty,
|
||||
/// which means we reached the end of a child of the actual
|
||||
/// container root (see `move_to_next_sibling`).
|
||||
///
|
||||
/// When an inline box ends, it's removed from this stack and added to
|
||||
/// [`Self::root_inline_boxes`].
|
||||
inline_box_stack: Vec<InlineBox>,
|
||||
}
|
||||
|
||||
impl InlineFormattingContextBuilder {
|
||||
pub(crate) fn new() -> Self {
|
||||
// For the purposes of `text-transform: capitalize` the start of the IFC is a word boundary.
|
||||
Self {
|
||||
on_word_boundary: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn currently_processing_inline_box(&self) -> bool {
|
||||
!self.inline_box_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Return true if this [`InlineFormattingContextBuilder`] 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(crate) fn is_empty(&self) -> bool {
|
||||
if self.has_uncollapsible_text_content {
|
||||
return false;
|
||||
}
|
||||
|
||||
if !self.inline_box_stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
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,
|
||||
// Text content is handled by `self.has_uncollapsible_text` content above in order
|
||||
// to avoid having to iterate through the character once again.
|
||||
InlineLevelBox::TextRun(_) => true,
|
||||
InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(_) => false,
|
||||
InlineLevelBox::OutOfFlowFloatBox(_) => false,
|
||||
InlineLevelBox::Atomic(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
inline_level_boxes_are_empty(&self.root_inline_boxes)
|
||||
}
|
||||
|
||||
// Retrieves the mutable reference of inline boxes either from the last
|
||||
// element of a stack or directly from the formatting context, depending on the situation.
|
||||
fn current_inline_level_boxes(&mut self) -> &mut Vec<ArcRefCell<InlineLevelBox>> {
|
||||
match self.inline_box_stack.last_mut() {
|
||||
Some(last) => &mut last.children,
|
||||
None => &mut self.root_inline_boxes,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn push_atomic(
|
||||
&mut self,
|
||||
independent_formatting_context: IndependentFormattingContext,
|
||||
) -> ArcRefCell<InlineLevelBox> {
|
||||
let inline_level_box =
|
||||
ArcRefCell::new(InlineLevelBox::Atomic(independent_formatting_context));
|
||||
self.current_inline_level_boxes()
|
||||
.push(inline_level_box.clone());
|
||||
self.last_inline_box_ended_with_collapsible_white_space = false;
|
||||
self.on_word_boundary = true;
|
||||
inline_level_box
|
||||
}
|
||||
|
||||
pub(crate) fn push_absolutely_positioned_box(
|
||||
&mut self,
|
||||
absolutely_positioned_box: AbsolutelyPositionedBox,
|
||||
) -> ArcRefCell<InlineLevelBox> {
|
||||
let absolutely_positioned_box = ArcRefCell::new(absolutely_positioned_box);
|
||||
let inline_level_box = ArcRefCell::new(InlineLevelBox::OutOfFlowAbsolutelyPositionedBox(
|
||||
absolutely_positioned_box,
|
||||
));
|
||||
self.current_inline_level_boxes()
|
||||
.push(inline_level_box.clone());
|
||||
inline_level_box
|
||||
}
|
||||
|
||||
pub(crate) fn push_float_box(&mut self, float_box: FloatBox) -> ArcRefCell<InlineLevelBox> {
|
||||
let inline_level_box = ArcRefCell::new(InlineLevelBox::OutOfFlowFloatBox(float_box));
|
||||
self.current_inline_level_boxes()
|
||||
.push(inline_level_box.clone());
|
||||
self.contains_floats = true;
|
||||
inline_level_box
|
||||
}
|
||||
|
||||
pub(crate) fn start_inline_box<'dom, Node: NodeExt<'dom>>(
|
||||
&mut self,
|
||||
info: &NodeAndStyleInfo<Node>,
|
||||
) {
|
||||
self.inline_box_stack.push(InlineBox::new(info))
|
||||
}
|
||||
|
||||
pub(crate) fn end_inline_box(&mut self) -> ArcRefCell<InlineLevelBox> {
|
||||
self.end_inline_box_internal(true)
|
||||
}
|
||||
|
||||
fn end_inline_box_internal(&mut self, is_last_fragment: bool) -> ArcRefCell<InlineLevelBox> {
|
||||
let mut inline_box = self
|
||||
.inline_box_stack
|
||||
.pop()
|
||||
.expect("no ongoing inline level box found");
|
||||
|
||||
if is_last_fragment {
|
||||
inline_box.is_last_fragment = true;
|
||||
}
|
||||
|
||||
let inline_box = ArcRefCell::new(InlineLevelBox::InlineBox(inline_box));
|
||||
self.current_inline_level_boxes().push(inline_box.clone());
|
||||
|
||||
inline_box
|
||||
}
|
||||
|
||||
pub(crate) fn push_text<'dom, Node: NodeExt<'dom>>(
|
||||
&mut self,
|
||||
text: Cow<'dom, str>,
|
||||
info: &NodeAndStyleInfo<Node>,
|
||||
) {
|
||||
let white_space_collapse = info.style.clone_white_space_collapse();
|
||||
let collapsed = WhitespaceCollapse::new(
|
||||
text.chars(),
|
||||
white_space_collapse,
|
||||
self.last_inline_box_ended_with_collapsible_white_space,
|
||||
);
|
||||
|
||||
let text_transform = info.style.clone_text_transform();
|
||||
let capitalized_text: String;
|
||||
let char_iterator: Box<dyn Iterator<Item = char>> =
|
||||
if text_transform.case_ == TextTransformCase::Capitalize {
|
||||
// `TextTransformation` doesn't support capitalization, so we must capitalize the whole
|
||||
// string at once and make a copy. Here `on_word_boundary` indicates whether or not the
|
||||
// inline formatting context as a whole is on a word boundary. This is different from
|
||||
// `last_inline_box_ended_with_collapsible_white_space` because the word boundaries are
|
||||
// between atomic inlines and at the start of the IFC, and because preserved spaces
|
||||
// are a word boundary.
|
||||
let collapsed_string: String = collapsed.collect();
|
||||
capitalized_text = capitalize_string(&collapsed_string, self.on_word_boundary);
|
||||
Box::new(capitalized_text.chars())
|
||||
} else if !text_transform.is_none() {
|
||||
// If `text-transform` is active, wrap the `WhitespaceCollapse` iterator in
|
||||
// a `TextTransformation` iterator.
|
||||
Box::new(TextTransformation::new(collapsed, text_transform))
|
||||
} else {
|
||||
Box::new(collapsed)
|
||||
};
|
||||
|
||||
let white_space_collapse = info.style.clone_white_space_collapse();
|
||||
let new_text: String = char_iterator
|
||||
.map(|character| {
|
||||
self.has_uncollapsible_text_content |= matches!(
|
||||
white_space_collapse,
|
||||
WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces
|
||||
) || !character.is_ascii_whitespace() ||
|
||||
(character == '\n' && white_space_collapse != WhiteSpaceCollapse::Collapse);
|
||||
character
|
||||
})
|
||||
.collect();
|
||||
|
||||
if new_text.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(last_character) = new_text.chars().next_back() {
|
||||
self.on_word_boundary = last_character.is_whitespace();
|
||||
self.last_inline_box_ended_with_collapsible_white_space =
|
||||
self.on_word_boundary && white_space_collapse != WhiteSpaceCollapse::Preserve;
|
||||
}
|
||||
|
||||
let new_range = self.current_text_offset..self.current_text_offset + new_text.len();
|
||||
self.current_text_offset = new_range.end;
|
||||
self.text_segments.push(new_text);
|
||||
|
||||
let inlines = self.current_inline_level_boxes();
|
||||
if let Some(mut last_box) = inlines.last_mut().map(|last| last.borrow_mut()) {
|
||||
if let InlineLevelBox::TextRun(ref mut text_run) = *last_box {
|
||||
text_run.text_range.end = new_range.end;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
inlines.push(ArcRefCell::new(InlineLevelBox::TextRun(TextRun::new(
|
||||
info.into(),
|
||||
info.style.clone(),
|
||||
new_range,
|
||||
))));
|
||||
}
|
||||
|
||||
pub(crate) fn split_around_block_and_finish(
|
||||
&mut self,
|
||||
layout_context: &LayoutContext,
|
||||
text_decoration_line: TextDecorationLine,
|
||||
has_first_formatted_line: bool,
|
||||
) -> Option<InlineFormattingContext> {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Create a new inline builder which will be active after the block splits this inline formatting
|
||||
// context. It has the same inline box structure as this builder, except the boxes are
|
||||
// marked as not being the first fragment. No inline content is carried over to this new
|
||||
// builder.
|
||||
let mut inline_buidler_from_before_split = std::mem::replace(
|
||||
self,
|
||||
InlineFormattingContextBuilder {
|
||||
on_word_boundary: true,
|
||||
inline_box_stack: self
|
||||
.inline_box_stack
|
||||
.iter()
|
||||
.map(|inline_box| inline_box.split_around_block())
|
||||
.collect(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
// End all ongoing inline boxes in the first builder, but ensure that they are not
|
||||
// marked as the final fragments, so that they do not get inline end margin, borders,
|
||||
// and padding.
|
||||
while !inline_buidler_from_before_split.inline_box_stack.is_empty() {
|
||||
inline_buidler_from_before_split.end_inline_box_internal(false);
|
||||
}
|
||||
|
||||
inline_buidler_from_before_split.finish(
|
||||
layout_context,
|
||||
text_decoration_line,
|
||||
has_first_formatted_line,
|
||||
)
|
||||
}
|
||||
|
||||
/// Finish the current inline formatting context, returning [`None`] if the context was empty.
|
||||
pub(crate) fn finish(
|
||||
&mut self,
|
||||
layout_context: &LayoutContext,
|
||||
text_decoration_line: TextDecorationLine,
|
||||
has_first_formatted_line: bool,
|
||||
) -> Option<InlineFormattingContext> {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let old_builder = std::mem::replace(self, InlineFormattingContextBuilder::new());
|
||||
assert!(old_builder.inline_box_stack.is_empty());
|
||||
|
||||
Some(InlineFormattingContext::new_with_builder(
|
||||
old_builder,
|
||||
layout_context,
|
||||
text_decoration_line,
|
||||
has_first_formatted_line,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn preserve_segment_break() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub struct WhitespaceCollapse<InputIterator> {
|
||||
char_iterator: InputIterator,
|
||||
white_space_collapse: WhiteSpaceCollapse,
|
||||
|
||||
/// Whether or not we should collapse white space completely at the start of the string.
|
||||
/// This is true when the last character handled in our owning [`super::InlineFormattingContext`]
|
||||
/// was collapsible white space.
|
||||
remove_collapsible_white_space_at_start: bool,
|
||||
|
||||
/// Whether or not the last character produced was newline. There is special behavior
|
||||
/// we do after each newline.
|
||||
following_newline: bool,
|
||||
|
||||
/// Whether or not we have seen any non-white space characters, indicating that we are not
|
||||
/// in a collapsible white space section at the beginning of the string.
|
||||
have_seen_non_white_space_characters: bool,
|
||||
|
||||
/// Whether the last character that we processed was a non-newline white space character. When
|
||||
/// collapsing white space we need to wait until the next non-white space character or the end
|
||||
/// of the string to push a single white space.
|
||||
inside_white_space: bool,
|
||||
|
||||
/// When we enter a collapsible white space region, we may need to wait to produce a single
|
||||
/// white space character as soon as we encounter a non-white space character. When that
|
||||
/// happens we queue up the non-white space character for the next iterator call.
|
||||
character_pending_to_return: Option<char>,
|
||||
}
|
||||
|
||||
impl<InputIterator> WhitespaceCollapse<InputIterator> {
|
||||
pub fn new(
|
||||
char_iterator: InputIterator,
|
||||
white_space_collapse: WhiteSpaceCollapse,
|
||||
trim_beginning_white_space: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
char_iterator,
|
||||
white_space_collapse,
|
||||
remove_collapsible_white_space_at_start: trim_beginning_white_space,
|
||||
inside_white_space: false,
|
||||
following_newline: false,
|
||||
have_seen_non_white_space_characters: false,
|
||||
character_pending_to_return: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_leading_trimmed_white_space(&self) -> bool {
|
||||
!self.have_seen_non_white_space_characters && self.remove_collapsible_white_space_at_start
|
||||
}
|
||||
|
||||
/// Whether or not we need to produce a space character if the next character is not a newline
|
||||
/// and not white space. This happens when we are exiting a section of white space and we
|
||||
/// waited to produce a single space character for the entire section of white space (but
|
||||
/// not following or preceding a newline).
|
||||
fn need_to_produce_space_character_after_white_space(&self) -> bool {
|
||||
self.inside_white_space && !self.following_newline && !self.is_leading_trimmed_white_space()
|
||||
}
|
||||
}
|
||||
|
||||
impl<InputIterator> Iterator for WhitespaceCollapse<InputIterator>
|
||||
where
|
||||
InputIterator: Iterator<Item = char>,
|
||||
{
|
||||
type Item = char;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
// Point 4.1.1 first bullet:
|
||||
// > If white-space is set to normal, nowrap, or pre-line, whitespace
|
||||
// > characters are considered collapsible
|
||||
// If whitespace is not considered collapsible, it is preserved entirely, which
|
||||
// means that we can simply return the input string exactly.
|
||||
if self.white_space_collapse == WhiteSpaceCollapse::Preserve ||
|
||||
self.white_space_collapse == WhiteSpaceCollapse::BreakSpaces
|
||||
{
|
||||
// From <https://drafts.csswg.org/css-text-3/#white-space-processing>:
|
||||
// > Carriage returns (U+000D) are treated identically to spaces (U+0020) in all respects.
|
||||
//
|
||||
// In the non-preserved case these are converted to space below.
|
||||
return match self.char_iterator.next() {
|
||||
Some('\r') => Some(' '),
|
||||
next => next,
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(character) = self.character_pending_to_return.take() {
|
||||
self.inside_white_space = false;
|
||||
self.have_seen_non_white_space_characters = true;
|
||||
self.following_newline = false;
|
||||
return Some(character);
|
||||
}
|
||||
|
||||
while let Some(character) = self.char_iterator.next() {
|
||||
// Don't push non-newline whitespace immediately. Instead wait to push it until we
|
||||
// know that it isn't followed by a newline. See `push_pending_whitespace_if_needed`
|
||||
// above.
|
||||
if character.is_ascii_whitespace() && character != '\n' {
|
||||
self.inside_white_space = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Point 4.1.1:
|
||||
// > 2. Collapsible segment breaks are transformed for rendering according to the
|
||||
// > segment break transformation rules.
|
||||
if character == '\n' {
|
||||
// From <https://drafts.csswg.org/css-text-3/#line-break-transform>
|
||||
// (4.1.3 -- the segment break transformation rules):
|
||||
//
|
||||
// > When white-space is pre, pre-wrap, or pre-line, segment breaks are not
|
||||
// > collapsible and are instead transformed into a preserved line feed"
|
||||
if self.white_space_collapse != WhiteSpaceCollapse::Collapse {
|
||||
self.inside_white_space = false;
|
||||
self.following_newline = true;
|
||||
return Some(character);
|
||||
|
||||
// Point 4.1.3:
|
||||
// > 1. First, any collapsible segment break immediately following another
|
||||
// > collapsible segment break is removed.
|
||||
// > 2. Then any remaining segment break is either transformed into a space (U+0020)
|
||||
// > or removed depending on the context before and after the break.
|
||||
} else if !self.following_newline &&
|
||||
preserve_segment_break() &&
|
||||
!self.is_leading_trimmed_white_space()
|
||||
{
|
||||
self.inside_white_space = false;
|
||||
self.following_newline = true;
|
||||
return Some(' ');
|
||||
} else {
|
||||
self.following_newline = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Point 4.1.1:
|
||||
// > 2. Any sequence of collapsible spaces and tabs immediately preceding or
|
||||
// > following a segment break is removed.
|
||||
// > 3. Every collapsible tab is converted to a collapsible space (U+0020).
|
||||
// > 4. 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.
|
||||
if self.need_to_produce_space_character_after_white_space() {
|
||||
self.inside_white_space = false;
|
||||
self.character_pending_to_return = Some(character);
|
||||
return Some(' ');
|
||||
}
|
||||
|
||||
self.inside_white_space = false;
|
||||
self.have_seen_non_white_space_characters = true;
|
||||
self.following_newline = false;
|
||||
return Some(character);
|
||||
}
|
||||
|
||||
if self.need_to_produce_space_character_after_white_space() {
|
||||
self.inside_white_space = false;
|
||||
return Some(' ');
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.char_iterator.size_hint()
|
||||
}
|
||||
|
||||
fn count(self) -> usize
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
self.char_iterator.count()
|
||||
}
|
||||
}
|
||||
|
||||
enum PendingCaseConversionResult {
|
||||
Uppercase(ToUppercase),
|
||||
Lowercase(ToLowercase),
|
||||
}
|
||||
|
||||
impl PendingCaseConversionResult {
|
||||
fn next(&mut self) -> Option<char> {
|
||||
match self {
|
||||
PendingCaseConversionResult::Uppercase(to_uppercase) => to_uppercase.next(),
|
||||
PendingCaseConversionResult::Lowercase(to_lowercase) => to_lowercase.next(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is an interator that consumes a char iterator and produces character transformed
|
||||
/// by the given CSS `text-transform` value. It currently does not support
|
||||
/// `text-transform: capitalize` because Unicode segmentation libraries do not support
|
||||
/// streaming input one character at a time.
|
||||
pub struct TextTransformation<InputIterator> {
|
||||
/// The input character iterator.
|
||||
char_iterator: InputIterator,
|
||||
/// The `text-transform` value to use.
|
||||
text_transform: TextTransform,
|
||||
/// If an uppercasing or lowercasing produces more than one character, this
|
||||
/// caches them so that they can be returned in subsequent iterator calls.
|
||||
pending_case_conversion_result: Option<PendingCaseConversionResult>,
|
||||
}
|
||||
|
||||
impl<InputIterator> TextTransformation<InputIterator> {
|
||||
pub fn new(char_iterator: InputIterator, text_transform: TextTransform) -> Self {
|
||||
Self {
|
||||
char_iterator,
|
||||
text_transform,
|
||||
pending_case_conversion_result: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<InputIterator> Iterator for TextTransformation<InputIterator>
|
||||
where
|
||||
InputIterator: Iterator<Item = char>,
|
||||
{
|
||||
type Item = char;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if let Some(character) = self
|
||||
.pending_case_conversion_result
|
||||
.as_mut()
|
||||
.and_then(|result| result.next())
|
||||
{
|
||||
return Some(character);
|
||||
}
|
||||
self.pending_case_conversion_result = None;
|
||||
|
||||
for character in self.char_iterator.by_ref() {
|
||||
match self.text_transform.case_ {
|
||||
TextTransformCase::None => return Some(character),
|
||||
TextTransformCase::Uppercase => {
|
||||
let mut pending_result =
|
||||
PendingCaseConversionResult::Uppercase(character.to_uppercase());
|
||||
if let Some(character) = pending_result.next() {
|
||||
self.pending_case_conversion_result = Some(pending_result);
|
||||
return Some(character);
|
||||
}
|
||||
},
|
||||
TextTransformCase::Lowercase => {
|
||||
let mut pending_result =
|
||||
PendingCaseConversionResult::Lowercase(character.to_lowercase());
|
||||
if let Some(character) = pending_result.next() {
|
||||
self.pending_case_conversion_result = Some(pending_result);
|
||||
return Some(character);
|
||||
}
|
||||
},
|
||||
// `text-transform: capitalize` currently cannot work on a per-character basis,
|
||||
// so must be handled outside of this iterator.
|
||||
// TODO: Add support for `full-width` and `full-size-kana`.
|
||||
_ => return Some(character),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a string and whether the start of the string represents a word boundary, create a copy of
|
||||
/// the string with letters after word boundaries capitalized.
|
||||
fn capitalize_string(string: &str, allow_word_at_start: bool) -> String {
|
||||
let mut output_string = String::new();
|
||||
output_string.reserve(string.len());
|
||||
|
||||
let mut bounds = string.unicode_word_indices().peekable();
|
||||
let mut byte_index = 0;
|
||||
for character in string.chars() {
|
||||
let current_byte_index = byte_index;
|
||||
byte_index += character.len_utf8();
|
||||
|
||||
if let Some((next_index, _)) = bounds.peek() {
|
||||
if *next_index == current_byte_index {
|
||||
bounds.next();
|
||||
|
||||
if current_byte_index != 0 || allow_word_at_start {
|
||||
output_string.extend(character.to_uppercase());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
output_string.push(character);
|
||||
}
|
||||
|
||||
output_string
|
||||
}
|
588
components/layout_2020/flow/inline/line.rs
Normal file
588
components/layout_2020/flow/inline/line.rs
Normal file
|
@ -0,0 +1,588 @@
|
|||
/* 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 std::vec::IntoIter;
|
||||
|
||||
use app_units::Au;
|
||||
use atomic_refcell::AtomicRef;
|
||||
use gfx::font::FontMetrics;
|
||||
use gfx::text::glyph::GlyphStore;
|
||||
use servo_arc::Arc;
|
||||
use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
|
||||
use style::properties::ComputedValues;
|
||||
use style::values::computed::Length;
|
||||
use style::values::generics::box_::{GenericVerticalAlign, VerticalAlignKeyword};
|
||||
use style::values::generics::font::LineHeight;
|
||||
use style::values::specified::box_::DisplayOutside;
|
||||
use style::values::specified::text::TextDecorationLine;
|
||||
use style::Zero;
|
||||
use webrender_api::FontInstanceKey;
|
||||
|
||||
use crate::cell::ArcRefCell;
|
||||
use crate::context::LayoutContext;
|
||||
use crate::fragment_tree::{
|
||||
BaseFragmentInfo, BoxFragment, CollapsedBlockMargins, Fragment, HoistedSharedFragment,
|
||||
TextFragment,
|
||||
};
|
||||
use crate::geom::{LogicalRect, LogicalVec2};
|
||||
use crate::positioned::{
|
||||
relative_adjustement, AbsolutelyPositionedBox, PositioningContext, PositioningContextLength,
|
||||
};
|
||||
use crate::style_ext::PaddingBorderMargin;
|
||||
use crate::ContainingBlock;
|
||||
|
||||
pub(super) struct LineMetrics {
|
||||
/// The block offset of the line start in the containing
|
||||
/// [`crate::flow::InlineFormattingContext`].
|
||||
pub block_offset: Length,
|
||||
|
||||
/// The block size of this line.
|
||||
pub block_size: Length,
|
||||
|
||||
/// The block offset of this line's baseline from [`Self::block_offset`].
|
||||
pub baseline_block_offset: Au,
|
||||
}
|
||||
|
||||
/// State used when laying out the [`LineItem`]s collected for the line currently being
|
||||
/// laid out.
|
||||
pub(super) struct LineItemLayoutState<'a> {
|
||||
pub inline_position: Length,
|
||||
|
||||
/// The offset of the parent, relative to the start position of the line.
|
||||
pub parent_offset: LogicalVec2<Length>,
|
||||
|
||||
/// The block offset of the parent's baseline relative to the block start of the line. This
|
||||
/// is often the same as [`Self::parent_offset`], but can be different for the root
|
||||
/// element.
|
||||
pub baseline_offset: Au,
|
||||
|
||||
pub ifc_containing_block: &'a ContainingBlock<'a>,
|
||||
pub positioning_context: &'a mut PositioningContext,
|
||||
|
||||
/// The amount of space to add to each justification opportunity in order to implement
|
||||
/// `text-align: justify`.
|
||||
pub justification_adjustment: Length,
|
||||
|
||||
/// The metrics of this line, which should remain constant throughout the
|
||||
/// layout process.
|
||||
pub line_metrics: &'a LineMetrics,
|
||||
}
|
||||
|
||||
pub(super) fn layout_line_items(
|
||||
iterator: &mut IntoIter<LineItem>,
|
||||
layout_context: &LayoutContext,
|
||||
state: &mut LineItemLayoutState,
|
||||
saw_end: &mut bool,
|
||||
) -> Vec<Fragment> {
|
||||
let mut fragments = vec![];
|
||||
while let Some(item) = iterator.next() {
|
||||
match item {
|
||||
LineItem::TextRun(text_line_item) => {
|
||||
if let Some(fragment) = text_line_item.layout(state) {
|
||||
fragments.push(Fragment::Text(fragment));
|
||||
}
|
||||
},
|
||||
LineItem::StartInlineBox(box_line_item) => {
|
||||
if let Some(fragment) = box_line_item.layout(iterator, layout_context, state) {
|
||||
fragments.push(Fragment::Box(fragment))
|
||||
}
|
||||
},
|
||||
LineItem::EndInlineBox => {
|
||||
*saw_end = true;
|
||||
break;
|
||||
},
|
||||
LineItem::Atomic(atomic_line_item) => {
|
||||
fragments.push(Fragment::Box(atomic_line_item.layout(state)));
|
||||
},
|
||||
LineItem::AbsolutelyPositioned(absolute_line_item) => {
|
||||
fragments.push(Fragment::AbsoluteOrFixedPositioned(
|
||||
absolute_line_item.layout(state),
|
||||
));
|
||||
},
|
||||
LineItem::Float(float_line_item) => {
|
||||
fragments.push(Fragment::Float(float_line_item.layout(state)));
|
||||
},
|
||||
}
|
||||
}
|
||||
fragments
|
||||
}
|
||||
|
||||
pub(super) enum LineItem {
|
||||
TextRun(TextRunLineItem),
|
||||
StartInlineBox(InlineBoxLineItem),
|
||||
EndInlineBox,
|
||||
Atomic(AtomicLineItem),
|
||||
AbsolutelyPositioned(AbsolutelyPositionedLineItem),
|
||||
Float(FloatLineItem),
|
||||
}
|
||||
|
||||
impl LineItem {
|
||||
pub(super) fn trim_whitespace_at_end(&mut self, whitespace_trimmed: &mut Length) -> bool {
|
||||
match self {
|
||||
LineItem::TextRun(ref mut item) => item.trim_whitespace_at_end(whitespace_trimmed),
|
||||
LineItem::StartInlineBox(_) => true,
|
||||
LineItem::EndInlineBox => true,
|
||||
LineItem::Atomic(_) => false,
|
||||
LineItem::AbsolutelyPositioned(_) => true,
|
||||
LineItem::Float(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn trim_whitespace_at_start(&mut self, whitespace_trimmed: &mut Length) -> bool {
|
||||
match self {
|
||||
LineItem::TextRun(ref mut item) => item.trim_whitespace_at_start(whitespace_trimmed),
|
||||
LineItem::StartInlineBox(_) => true,
|
||||
LineItem::EndInlineBox => true,
|
||||
LineItem::Atomic(_) => false,
|
||||
LineItem::AbsolutelyPositioned(_) => true,
|
||||
LineItem::Float(_) => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct TextRunLineItem {
|
||||
pub base_fragment_info: BaseFragmentInfo,
|
||||
pub parent_style: Arc<ComputedValues>,
|
||||
pub text: Vec<std::sync::Arc<GlyphStore>>,
|
||||
pub font_metrics: FontMetrics,
|
||||
pub font_key: FontInstanceKey,
|
||||
pub text_decoration_line: TextDecorationLine,
|
||||
}
|
||||
|
||||
impl TextRunLineItem {
|
||||
fn trim_whitespace_at_end(&mut self, whitespace_trimmed: &mut Length) -> bool {
|
||||
if matches!(
|
||||
self.parent_style.get_inherited_text().white_space_collapse,
|
||||
WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let index_of_last_non_whitespace = self
|
||||
.text
|
||||
.iter()
|
||||
.rev()
|
||||
.position(|glyph| !glyph.is_whitespace())
|
||||
.map(|offset_from_end| self.text.len() - offset_from_end);
|
||||
|
||||
let first_whitespace_index = index_of_last_non_whitespace.unwrap_or(0);
|
||||
*whitespace_trimmed += self
|
||||
.text
|
||||
.drain(first_whitespace_index..)
|
||||
.map(|glyph| Length::from(glyph.total_advance()))
|
||||
.sum();
|
||||
|
||||
// Only keep going if we only encountered whitespace.
|
||||
index_of_last_non_whitespace.is_none()
|
||||
}
|
||||
|
||||
fn trim_whitespace_at_start(&mut self, whitespace_trimmed: &mut Length) -> bool {
|
||||
if matches!(
|
||||
self.parent_style.get_inherited_text().white_space_collapse,
|
||||
WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let index_of_first_non_whitespace = self
|
||||
.text
|
||||
.iter()
|
||||
.position(|glyph| !glyph.is_whitespace())
|
||||
.unwrap_or(self.text.len());
|
||||
|
||||
*whitespace_trimmed += self
|
||||
.text
|
||||
.drain(0..index_of_first_non_whitespace)
|
||||
.map(|glyph| Length::from(glyph.total_advance()))
|
||||
.sum();
|
||||
|
||||
// Only keep going if we only encountered whitespace.
|
||||
self.text.is_empty()
|
||||
}
|
||||
|
||||
fn layout(self, state: &mut LineItemLayoutState) -> Option<TextFragment> {
|
||||
if self.text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut number_of_justification_opportunities = 0;
|
||||
let mut inline_advance: Length = self
|
||||
.text
|
||||
.iter()
|
||||
.map(|glyph_store| {
|
||||
number_of_justification_opportunities += glyph_store.total_word_separators();
|
||||
Length::from(glyph_store.total_advance())
|
||||
})
|
||||
.sum();
|
||||
|
||||
if !state.justification_adjustment.is_zero() {
|
||||
inline_advance +=
|
||||
state.justification_adjustment * number_of_justification_opportunities as f32;
|
||||
}
|
||||
|
||||
// The block start of the TextRun is often zero (meaning it has the same font metrics as the
|
||||
// inline box's strut), but for children of the inline formatting context root or for
|
||||
// fallback fonts that use baseline relatve alignment, it might be different.
|
||||
let start_corner = &LogicalVec2 {
|
||||
inline: state.inline_position,
|
||||
block: (state.baseline_offset - self.font_metrics.ascent).into(),
|
||||
} - &state.parent_offset;
|
||||
|
||||
let rect = LogicalRect {
|
||||
start_corner,
|
||||
size: LogicalVec2 {
|
||||
block: self.font_metrics.line_gap.into(),
|
||||
inline: inline_advance,
|
||||
},
|
||||
};
|
||||
|
||||
state.inline_position += inline_advance;
|
||||
Some(TextFragment {
|
||||
base: self.base_fragment_info.into(),
|
||||
parent_style: self.parent_style,
|
||||
rect,
|
||||
font_metrics: self.font_metrics,
|
||||
font_key: self.font_key,
|
||||
glyphs: self.text,
|
||||
text_decoration_line: self.text_decoration_line,
|
||||
justification_adjustment: state.justification_adjustment,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct InlineBoxLineItem {
|
||||
pub base_fragment_info: BaseFragmentInfo,
|
||||
pub style: Arc<ComputedValues>,
|
||||
pub pbm: PaddingBorderMargin,
|
||||
|
||||
/// Whether this is the first fragment for this inline box. This means that it's the
|
||||
/// first potentially split box of a block-in-inline-split (or only if there's no
|
||||
/// split) and also the first appearance of this fragment on any line.
|
||||
pub is_first_fragment: bool,
|
||||
|
||||
/// Whether this is the last fragment for this inline box. This means that it's the
|
||||
/// last potentially split box of a block-in-inline-split (or the only fragment if
|
||||
/// there's no split).
|
||||
pub is_last_fragment_of_ib_split: bool,
|
||||
|
||||
/// The FontMetrics for the default font used in this inline box.
|
||||
pub font_metrics: FontMetrics,
|
||||
|
||||
/// The block offset of this baseline relative to the baseline of the line. This will be
|
||||
/// zero for boxes with `vertical-align: top` and `vertical-align: bottom` since their
|
||||
/// baselines are calculated late in layout.
|
||||
pub baseline_offset: Au,
|
||||
}
|
||||
|
||||
impl InlineBoxLineItem {
|
||||
fn layout(
|
||||
self,
|
||||
iterator: &mut IntoIter<LineItem>,
|
||||
layout_context: &LayoutContext,
|
||||
state: &mut LineItemLayoutState,
|
||||
) -> Option<BoxFragment> {
|
||||
let style = self.style.clone();
|
||||
let mut padding = self.pbm.padding.clone();
|
||||
let mut border = self.pbm.border.clone();
|
||||
let mut margin = self.pbm.margin.auto_is(Au::zero);
|
||||
|
||||
if !self.is_first_fragment {
|
||||
padding.inline_start = Au::zero();
|
||||
border.inline_start = Au::zero();
|
||||
margin.inline_start = Au::zero();
|
||||
}
|
||||
if !self.is_last_fragment_of_ib_split {
|
||||
padding.inline_end = Au::zero();
|
||||
border.inline_end = Au::zero();
|
||||
margin.inline_end = Au::zero();
|
||||
}
|
||||
let pbm_sums = &(&padding + &border) + &margin;
|
||||
state.inline_position += pbm_sums.inline_start.into();
|
||||
|
||||
let space_above_baseline = self.calculate_space_above_baseline();
|
||||
let block_start_offset = self.calculate_block_start(state, space_above_baseline);
|
||||
|
||||
let mut positioning_context = PositioningContext::new_for_style(&style);
|
||||
let nested_positioning_context = match positioning_context.as_mut() {
|
||||
Some(positioning_context) => positioning_context,
|
||||
None => &mut state.positioning_context,
|
||||
};
|
||||
let original_nested_positioning_context_length = nested_positioning_context.len();
|
||||
|
||||
let mut nested_state = LineItemLayoutState {
|
||||
inline_position: state.inline_position,
|
||||
parent_offset: LogicalVec2 {
|
||||
inline: state.inline_position,
|
||||
block: block_start_offset.into(),
|
||||
},
|
||||
ifc_containing_block: state.ifc_containing_block,
|
||||
positioning_context: nested_positioning_context,
|
||||
justification_adjustment: state.justification_adjustment,
|
||||
line_metrics: state.line_metrics,
|
||||
baseline_offset: block_start_offset + space_above_baseline,
|
||||
};
|
||||
|
||||
let mut saw_end = false;
|
||||
let fragments =
|
||||
layout_line_items(iterator, layout_context, &mut nested_state, &mut saw_end);
|
||||
|
||||
// Only add ending padding, border, margin if this is the last fragment of a
|
||||
// potential block-in-inline split and this line included the actual end of this
|
||||
// fragment (it doesn't continue on the next line).
|
||||
if !self.is_last_fragment_of_ib_split || !saw_end {
|
||||
padding.inline_end = Au::zero();
|
||||
border.inline_end = Au::zero();
|
||||
margin.inline_end = Au::zero();
|
||||
}
|
||||
let pbm_sums = &(&padding + &border) + &margin.clone();
|
||||
|
||||
// If the inline box didn't have any content at all, don't add a Fragment for it.
|
||||
let box_has_padding_border_or_margin = pbm_sums.inline_sum() > Au::zero();
|
||||
let box_had_absolutes =
|
||||
original_nested_positioning_context_length != nested_state.positioning_context.len();
|
||||
if !self.is_first_fragment &&
|
||||
fragments.is_empty() &&
|
||||
!box_has_padding_border_or_margin &&
|
||||
!box_had_absolutes
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut content_rect = LogicalRect {
|
||||
start_corner: LogicalVec2 {
|
||||
inline: state.inline_position,
|
||||
block: block_start_offset.into(),
|
||||
},
|
||||
size: LogicalVec2 {
|
||||
inline: nested_state.inline_position - state.inline_position,
|
||||
block: self.font_metrics.line_gap.into(),
|
||||
},
|
||||
};
|
||||
|
||||
// Make `content_rect` relative to the parent Fragment.
|
||||
content_rect.start_corner = &content_rect.start_corner - &state.parent_offset;
|
||||
|
||||
// Relative adjustment should not affect the rest of line layout, so we can
|
||||
// do it right before creating the Fragment.
|
||||
if style.clone_position().is_relative() {
|
||||
content_rect.start_corner += &relative_adjustement(&style, state.ifc_containing_block);
|
||||
}
|
||||
|
||||
let mut fragment = BoxFragment::new(
|
||||
self.base_fragment_info,
|
||||
self.style.clone(),
|
||||
fragments,
|
||||
content_rect,
|
||||
padding,
|
||||
border,
|
||||
margin,
|
||||
None, /* clearance */
|
||||
CollapsedBlockMargins::zero(),
|
||||
);
|
||||
|
||||
state.inline_position = nested_state.inline_position + pbm_sums.inline_end.into();
|
||||
|
||||
if let Some(mut positioning_context) = positioning_context.take() {
|
||||
assert!(original_nested_positioning_context_length == PositioningContextLength::zero());
|
||||
positioning_context.layout_collected_children(layout_context, &mut fragment);
|
||||
positioning_context.adjust_static_position_of_hoisted_fragments_with_offset(
|
||||
&fragment.content_rect.start_corner,
|
||||
PositioningContextLength::zero(),
|
||||
);
|
||||
state.positioning_context.append(positioning_context);
|
||||
} else {
|
||||
state
|
||||
.positioning_context
|
||||
.adjust_static_position_of_hoisted_fragments_with_offset(
|
||||
&fragment.content_rect.start_corner,
|
||||
original_nested_positioning_context_length,
|
||||
);
|
||||
}
|
||||
|
||||
Some(fragment)
|
||||
}
|
||||
|
||||
/// Given our font metrics, calculate the space above the baseline we need for our content.
|
||||
/// Note that this space does not include space for any content in child inline boxes, as
|
||||
/// they are not included in our content rect.
|
||||
fn calculate_space_above_baseline(&self) -> Au {
|
||||
let (ascent, descent, line_gap) = (
|
||||
self.font_metrics.ascent,
|
||||
self.font_metrics.descent,
|
||||
self.font_metrics.line_gap,
|
||||
);
|
||||
let leading = line_gap - (ascent + descent);
|
||||
leading.scale_by(0.5) + ascent
|
||||
}
|
||||
|
||||
/// Given the state for a line item layout and the space above the baseline for this inline
|
||||
/// box, find the block start position relative to the line block start position.
|
||||
fn calculate_block_start(&self, state: &LineItemLayoutState, space_above_baseline: Au) -> Au {
|
||||
let line_gap = self.font_metrics.line_gap;
|
||||
|
||||
// The baseline offset that we have in `Self::baseline_offset` is relative to the line
|
||||
// baseline, so we need to make it relative to the line block start.
|
||||
match self.style.clone_vertical_align() {
|
||||
GenericVerticalAlign::Keyword(VerticalAlignKeyword::Top) => {
|
||||
let line_height: Au = line_height(&self.style, &self.font_metrics).into();
|
||||
(line_height - line_gap).scale_by(0.5)
|
||||
},
|
||||
GenericVerticalAlign::Keyword(VerticalAlignKeyword::Bottom) => {
|
||||
let line_height: Au = line_height(&self.style, &self.font_metrics).into();
|
||||
let half_leading = (line_height - line_gap).scale_by(0.5);
|
||||
Au::from(state.line_metrics.block_size) - line_height + half_leading
|
||||
},
|
||||
_ => {
|
||||
state.line_metrics.baseline_block_offset + self.baseline_offset -
|
||||
space_above_baseline
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct AtomicLineItem {
|
||||
pub fragment: BoxFragment,
|
||||
pub size: LogicalVec2<Length>,
|
||||
pub positioning_context: Option<PositioningContext>,
|
||||
|
||||
/// The block offset of this items' baseline relative to the baseline of the line.
|
||||
/// This will be zero for boxes with `vertical-align: top` and `vertical-align:
|
||||
/// bottom` since their baselines are calculated late in layout.
|
||||
pub baseline_offset_in_parent: Au,
|
||||
|
||||
/// The offset of the baseline inside this item.
|
||||
pub baseline_offset_in_item: Au,
|
||||
}
|
||||
|
||||
impl AtomicLineItem {
|
||||
fn layout(mut self, state: &mut LineItemLayoutState) -> BoxFragment {
|
||||
// The initial `start_corner` of the Fragment is only the PaddingBorderMargin sum start
|
||||
// offset, which is the sum of the start component of the padding, border, and margin.
|
||||
// This needs to be added to the calculated block and inline positions.
|
||||
self.fragment.content_rect.start_corner.inline += state.inline_position;
|
||||
self.fragment.content_rect.start_corner.block +=
|
||||
self.calculate_block_start(state.line_metrics);
|
||||
|
||||
// Make the final result relative to the parent box.
|
||||
self.fragment.content_rect.start_corner =
|
||||
&self.fragment.content_rect.start_corner - &state.parent_offset;
|
||||
|
||||
if self.fragment.style.clone_position().is_relative() {
|
||||
self.fragment.content_rect.start_corner +=
|
||||
&relative_adjustement(&self.fragment.style, state.ifc_containing_block);
|
||||
}
|
||||
|
||||
state.inline_position += self.size.inline;
|
||||
|
||||
if let Some(mut positioning_context) = self.positioning_context {
|
||||
positioning_context.adjust_static_position_of_hoisted_fragments_with_offset(
|
||||
&self.fragment.content_rect.start_corner,
|
||||
PositioningContextLength::zero(),
|
||||
);
|
||||
state.positioning_context.append(positioning_context);
|
||||
}
|
||||
|
||||
self.fragment
|
||||
}
|
||||
|
||||
/// Given the metrics for a line, our vertical alignment, and our block size, find a block start
|
||||
/// position relative to the top of the line.
|
||||
fn calculate_block_start(&self, line_metrics: &LineMetrics) -> Length {
|
||||
match self.fragment.style.clone_vertical_align() {
|
||||
GenericVerticalAlign::Keyword(VerticalAlignKeyword::Top) => Length::zero(),
|
||||
GenericVerticalAlign::Keyword(VerticalAlignKeyword::Bottom) => {
|
||||
line_metrics.block_size - self.size.block
|
||||
},
|
||||
|
||||
// This covers all baseline-relative vertical alignment.
|
||||
_ => {
|
||||
let baseline = line_metrics.baseline_block_offset + self.baseline_offset_in_parent;
|
||||
Length::from(baseline - self.baseline_offset_in_item)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct AbsolutelyPositionedLineItem {
|
||||
pub absolutely_positioned_box: ArcRefCell<AbsolutelyPositionedBox>,
|
||||
}
|
||||
|
||||
impl AbsolutelyPositionedLineItem {
|
||||
fn layout(self, state: &mut LineItemLayoutState) -> ArcRefCell<HoistedSharedFragment> {
|
||||
let box_ = self.absolutely_positioned_box;
|
||||
let style = AtomicRef::map(box_.borrow(), |box_| box_.context.style());
|
||||
|
||||
// From https://drafts.csswg.org/css2/#abs-non-replaced-width
|
||||
// > The static-position containing block is the containing block of a
|
||||
// > hypothetical box that would have been the first box of the element if its
|
||||
// > specified position value had been static and its specified float had been
|
||||
// > none. (Note that due to the rules in section 9.7 this hypothetical
|
||||
// > calculation might require also assuming a different computed value for
|
||||
// > display.)
|
||||
//
|
||||
// This box is different based on the original `display` value of the
|
||||
// absolutely positioned element. If it's `inline` it would be placed inline
|
||||
// at the top of the line, but if it's block it would be placed in a new
|
||||
// block position after the linebox established by this line.
|
||||
let initial_start_corner =
|
||||
if style.get_box().original_display.outside() == DisplayOutside::Inline {
|
||||
// Top of the line at the current inline position.
|
||||
LogicalVec2 {
|
||||
inline: state.inline_position - state.parent_offset.inline,
|
||||
block: -state.parent_offset.block,
|
||||
}
|
||||
} else {
|
||||
// After the bottom of the line at the start of the inline formatting context.
|
||||
LogicalVec2 {
|
||||
inline: Length::zero(),
|
||||
block: state.line_metrics.block_size - state.parent_offset.block,
|
||||
}
|
||||
};
|
||||
|
||||
let hoisted_box = AbsolutelyPositionedBox::to_hoisted(
|
||||
box_.clone(),
|
||||
initial_start_corner,
|
||||
state.ifc_containing_block,
|
||||
);
|
||||
let hoisted_fragment = hoisted_box.fragment.clone();
|
||||
state.positioning_context.push(hoisted_box);
|
||||
hoisted_fragment
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct FloatLineItem {
|
||||
pub fragment: BoxFragment,
|
||||
/// Whether or not this float Fragment has been placed yet. Fragments that
|
||||
/// do not fit on a line need to be placed after the hypothetical block start
|
||||
/// of the next line.
|
||||
pub needs_placement: bool,
|
||||
}
|
||||
|
||||
impl FloatLineItem {
|
||||
fn layout(mut self, state: &mut LineItemLayoutState<'_>) -> BoxFragment {
|
||||
// The `BoxFragment` for this float is positioned relative to the IFC, so we need
|
||||
// to move it to be positioned relative to our parent InlineBox line item. Floats
|
||||
// fragments are children of these InlineBoxes and not children of the inline
|
||||
// formatting context, so that they are parented properly for StackingContext
|
||||
// properties such as opacity & filters.
|
||||
let distance_from_parent_to_ifc = LogicalVec2 {
|
||||
inline: state.parent_offset.inline,
|
||||
block: state.line_metrics.block_offset + state.parent_offset.block,
|
||||
};
|
||||
self.fragment.content_rect.start_corner =
|
||||
&self.fragment.content_rect.start_corner - &distance_from_parent_to_ifc;
|
||||
self.fragment
|
||||
}
|
||||
}
|
||||
|
||||
fn line_height(parent_style: &ComputedValues, font_metrics: &FontMetrics) -> Length {
|
||||
let font = parent_style.get_font();
|
||||
let font_size = font.font_size.computed_size();
|
||||
match font.line_height {
|
||||
LineHeight::Normal => Length::from(font_metrics.line_gap),
|
||||
LineHeight::Number(number) => font_size * number.0,
|
||||
LineHeight::Length(length) => length.0,
|
||||
}
|
||||
}
|
2522
components/layout_2020/flow/inline/mod.rs
Normal file
2522
components/layout_2020/flow/inline/mod.rs
Normal file
File diff suppressed because it is too large
Load diff
591
components/layout_2020/flow/inline/text_run.rs
Normal file
591
components/layout_2020/flow/inline/text_run.rs
Normal file
|
@ -0,0 +1,591 @@
|
|||
/* 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 std::mem;
|
||||
use std::ops::Range;
|
||||
|
||||
use app_units::Au;
|
||||
use gfx::font::{FontRef, ShapingFlags, ShapingOptions};
|
||||
use gfx::font_cache_thread::FontCacheThread;
|
||||
use gfx::font_context::FontContext;
|
||||
use gfx::text::glyph::GlyphRun;
|
||||
use gfx_traits::ByteIndex;
|
||||
use log::warn;
|
||||
use range::Range as ServoRange;
|
||||
use serde::Serialize;
|
||||
use servo_arc::Arc;
|
||||
use style::computed_values::text_rendering::T as TextRendering;
|
||||
use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
|
||||
use style::computed_values::word_break::T as WordBreak;
|
||||
use style::properties::style_structs::InheritedText;
|
||||
use style::properties::ComputedValues;
|
||||
use style::str::char_is_whitespace;
|
||||
use style::values::computed::OverflowWrap;
|
||||
use unicode_script::Script;
|
||||
use xi_unicode::{linebreak_property, LineBreakLeafIter};
|
||||
|
||||
use super::{FontKeyAndMetrics, InlineFormattingContextState};
|
||||
use crate::fragment_tree::BaseFragmentInfo;
|
||||
|
||||
// These constants are the xi-unicode line breaking classes that are defined in
|
||||
// `table.rs`. Unfortunately, they are only identified by number.
|
||||
const XI_LINE_BREAKING_CLASS_CM: u8 = 9;
|
||||
const XI_LINE_BREAKING_CLASS_GL: u8 = 12;
|
||||
const XI_LINE_BREAKING_CLASS_ZW: u8 = 28;
|
||||
const XI_LINE_BREAKING_CLASS_WJ: u8 = 30;
|
||||
const XI_LINE_BREAKING_CLASS_ZWJ: u8 = 40;
|
||||
|
||||
/// <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_range: Range<usize>,
|
||||
|
||||
/// The text of this [`TextRun`] with a font selected, broken into unbreakable
|
||||
/// segments, and shaped.
|
||||
pub shaped_text: Vec<TextRunSegment>,
|
||||
|
||||
/// Whether or not to prevent a soft wrap opportunity at the start of this [`TextRun`].
|
||||
/// This depends on the whether the first character in the run prevents a soft wrap
|
||||
/// opportunity.
|
||||
prevent_soft_wrap_opportunity_at_start: bool,
|
||||
|
||||
/// Whether or not to prevent a soft wrap opportunity at the end of this [`TextRun`].
|
||||
/// This depends on the whether the last character in the run prevents a soft wrap
|
||||
/// opportunity.
|
||||
prevent_soft_wrap_opportunity_at_end: bool,
|
||||
}
|
||||
|
||||
// There are two reasons why we might want to break at the start:
|
||||
//
|
||||
// 1. The line breaker told us that a break was necessary between two separate
|
||||
// instances of sending text to it.
|
||||
// 2. We are following replaced content ie `have_deferred_soft_wrap_opportunity`.
|
||||
//
|
||||
// In both cases, we don't want to do this if the first character prevents a
|
||||
// soft wrap opportunity.
|
||||
#[derive(PartialEq)]
|
||||
enum SegmentStartSoftWrapPolicy {
|
||||
Force,
|
||||
Prevent,
|
||||
FollowLinebreaker,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(crate) struct TextRunSegment {
|
||||
/// The index of this font in the parent [`super::InlineFormattingContext`]'s collection of font
|
||||
/// information.
|
||||
pub font_index: usize,
|
||||
|
||||
/// The [`Script`] of this segment.
|
||||
#[serde(skip_serializing)]
|
||||
pub script: Script,
|
||||
|
||||
/// The range of bytes in the [`TextRun`]'s text that this segment covers.
|
||||
pub range: ServoRange<ByteIndex>,
|
||||
|
||||
/// Whether or not the linebreaker said that we should allow a line break at the start of this
|
||||
/// segment.
|
||||
pub break_at_start: bool,
|
||||
|
||||
/// The shaped runs within this segment.
|
||||
pub runs: Vec<GlyphRun>,
|
||||
}
|
||||
|
||||
impl TextRunSegment {
|
||||
fn new(font_index: usize, script: Script, byte_index: ByteIndex) -> Self {
|
||||
Self {
|
||||
script,
|
||||
font_index,
|
||||
range: ServoRange::new(byte_index, ByteIndex(0)),
|
||||
runs: Vec::new(),
|
||||
break_at_start: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Update this segment if the Font and Script are compatible. The update will only
|
||||
/// ever make the Script specific. Returns true if the new Font and Script are
|
||||
/// compatible with this segment or false otherwise.
|
||||
fn update_if_compatible(
|
||||
&mut self,
|
||||
new_font: &FontRef,
|
||||
script: Script,
|
||||
fonts: &[FontKeyAndMetrics],
|
||||
) -> bool {
|
||||
fn is_specific(script: Script) -> bool {
|
||||
script != Script::Common && script != Script::Inherited
|
||||
}
|
||||
|
||||
let current_font_key_and_metrics = &fonts[self.font_index];
|
||||
if new_font.font_key != current_font_key_and_metrics.key ||
|
||||
new_font.descriptor.pt_size != current_font_key_and_metrics.pt_size
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if !is_specific(self.script) && is_specific(script) {
|
||||
self.script = script;
|
||||
}
|
||||
script == self.script || !is_specific(script)
|
||||
}
|
||||
|
||||
fn layout_into_line_items(
|
||||
&self,
|
||||
text_run: &TextRun,
|
||||
mut soft_wrap_policy: SegmentStartSoftWrapPolicy,
|
||||
ifc: &mut InlineFormattingContextState,
|
||||
) {
|
||||
if self.break_at_start && soft_wrap_policy == SegmentStartSoftWrapPolicy::FollowLinebreaker
|
||||
{
|
||||
soft_wrap_policy = SegmentStartSoftWrapPolicy::Force;
|
||||
}
|
||||
|
||||
for (run_index, run) in self.runs.iter().enumerate() {
|
||||
ifc.possibly_flush_deferred_forced_line_break();
|
||||
|
||||
// If this whitespace forces a line break, queue up a hard line break the next time we
|
||||
// see any content. We don't line break immediately, because we'd like to finish processing
|
||||
// any ongoing inline boxes before ending the line.
|
||||
if run.is_single_preserved_newline() {
|
||||
ifc.defer_forced_line_break();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Break before each unbreakable run in this TextRun, except the first unless the
|
||||
// linebreaker was set to break before the first run.
|
||||
if run_index != 0 || soft_wrap_policy == SegmentStartSoftWrapPolicy::Force {
|
||||
ifc.process_soft_wrap_opportunity();
|
||||
}
|
||||
|
||||
ifc.push_glyph_store_to_unbreakable_segment(
|
||||
run.glyph_store.clone(),
|
||||
text_run,
|
||||
self.font_index,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextRun {
|
||||
pub(crate) fn new(
|
||||
base_fragment_info: BaseFragmentInfo,
|
||||
parent_style: Arc<ComputedValues>,
|
||||
text_range: Range<usize>,
|
||||
) -> Self {
|
||||
Self {
|
||||
base_fragment_info,
|
||||
parent_style,
|
||||
text_range,
|
||||
shaped_text: Vec::new(),
|
||||
prevent_soft_wrap_opportunity_at_start: false,
|
||||
prevent_soft_wrap_opportunity_at_end: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn break_and_shape(
|
||||
&mut self,
|
||||
text_content: &str,
|
||||
font_context: &FontContext<FontCacheThread>,
|
||||
linebreaker: &mut Option<LineBreakLeafIter>,
|
||||
font_cache: &mut Vec<FontKeyAndMetrics>,
|
||||
) {
|
||||
let segment_results = self.segment_text(text_content, font_context, font_cache);
|
||||
let inherited_text_style = self.parent_style.get_inherited_text().clone();
|
||||
let letter_spacing = if inherited_text_style.letter_spacing.0.px() != 0. {
|
||||
Some(app_units::Au::from(inherited_text_style.letter_spacing.0))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut flags = ShapingFlags::empty();
|
||||
if letter_spacing.is_some() {
|
||||
flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG);
|
||||
}
|
||||
if inherited_text_style.text_rendering == TextRendering::Optimizespeed {
|
||||
flags.insert(ShapingFlags::IGNORE_LIGATURES_SHAPING_FLAG);
|
||||
flags.insert(ShapingFlags::DISABLE_KERNING_SHAPING_FLAG)
|
||||
}
|
||||
if inherited_text_style.word_break == WordBreak::KeepAll {
|
||||
flags.insert(ShapingFlags::KEEP_ALL_FLAG);
|
||||
}
|
||||
|
||||
let specified_word_spacing = &inherited_text_style.word_spacing;
|
||||
let style_word_spacing: Option<Au> = specified_word_spacing.to_length().map(|l| l.into());
|
||||
let segments = segment_results
|
||||
.into_iter()
|
||||
.map(|(mut segment, font)| {
|
||||
let word_spacing = style_word_spacing.unwrap_or_else(|| {
|
||||
let space_width = font
|
||||
.glyph_index(' ')
|
||||
.map(|glyph_id| font.glyph_h_advance(glyph_id))
|
||||
.unwrap_or(gfx::font::LAST_RESORT_GLYPH_ADVANCE);
|
||||
specified_word_spacing.to_used_value(Au::from_f64_px(space_width))
|
||||
});
|
||||
let shaping_options = ShapingOptions {
|
||||
letter_spacing,
|
||||
word_spacing,
|
||||
script: segment.script,
|
||||
flags,
|
||||
};
|
||||
(segment.runs, segment.break_at_start) = break_and_shape(
|
||||
font,
|
||||
&text_content[segment.range.begin().0 as usize..segment.range.end().0 as usize],
|
||||
&inherited_text_style,
|
||||
&shaping_options,
|
||||
linebreaker,
|
||||
);
|
||||
|
||||
segment
|
||||
})
|
||||
.collect();
|
||||
|
||||
let _ = std::mem::replace(&mut self.shaped_text, segments);
|
||||
}
|
||||
|
||||
/// Take the [`TextRun`]'s text and turn it into [`TextRunSegment`]s. Each segment has a matched
|
||||
/// font and script. Fonts may differ when glyphs are found in fallback fonts. Fonts are stored
|
||||
/// in the `font_cache` which is a cache of all font keys and metrics used in this
|
||||
/// [`super::InlineFormattingContext`].
|
||||
fn segment_text(
|
||||
&mut self,
|
||||
text_content: &str,
|
||||
font_context: &FontContext<FontCacheThread>,
|
||||
font_cache: &mut Vec<FontKeyAndMetrics>,
|
||||
) -> Vec<(TextRunSegment, FontRef)> {
|
||||
let font_group = font_context.font_group(self.parent_style.clone_font());
|
||||
let mut current: Option<(TextRunSegment, FontRef)> = None;
|
||||
let mut results = Vec::new();
|
||||
|
||||
let char_iterator = TwoCharsAtATimeIterator::new(text_content.chars());
|
||||
let mut next_byte_index = 0;
|
||||
for (character, next_character) in char_iterator {
|
||||
let current_byte_index = next_byte_index;
|
||||
next_byte_index += character.len_utf8();
|
||||
|
||||
let prevents_soft_wrap_opportunity =
|
||||
char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character);
|
||||
if current_byte_index == 0 && prevents_soft_wrap_opportunity {
|
||||
self.prevent_soft_wrap_opportunity_at_start = true;
|
||||
}
|
||||
self.prevent_soft_wrap_opportunity_at_end = prevents_soft_wrap_opportunity;
|
||||
|
||||
if char_does_not_change_font(character) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(font) =
|
||||
font_group
|
||||
.write()
|
||||
.find_by_codepoint(font_context, character, next_character)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// If the existing segment is compatible with the character, keep going.
|
||||
let script = Script::from(character);
|
||||
if let Some(current) = current.as_mut() {
|
||||
if current.0.update_if_compatible(&font, script, font_cache) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let font_index = add_or_get_font(&font, font_cache);
|
||||
|
||||
// Add the new segment and finish the existing one, if we had one. If the first
|
||||
// characters in the run were control characters we may be creating the first
|
||||
// segment in the middle of the run (ie the start should be 0).
|
||||
let start_byte_index = match current {
|
||||
Some(_) => ByteIndex(current_byte_index as isize),
|
||||
None => ByteIndex(0_isize),
|
||||
};
|
||||
let new = (
|
||||
TextRunSegment::new(font_index, script, start_byte_index),
|
||||
font,
|
||||
);
|
||||
if let Some(mut finished) = current.replace(new) {
|
||||
finished.0.range.extend_to(start_byte_index);
|
||||
results.push(finished);
|
||||
}
|
||||
}
|
||||
|
||||
// Either we have a current segment or we only had control character and whitespace. In both
|
||||
// of those cases, just use the first font.
|
||||
if current.is_none() {
|
||||
current = font_group.write().first(font_context).map(|font| {
|
||||
let font_index = add_or_get_font(&font, font_cache);
|
||||
(
|
||||
TextRunSegment::new(font_index, Script::Common, ByteIndex(0)),
|
||||
font,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Extend the last segment to the end of the string and add it to the results.
|
||||
if let Some(mut last_segment) = current.take() {
|
||||
last_segment
|
||||
.0
|
||||
.range
|
||||
.extend_to(ByteIndex(text_content.len() as isize));
|
||||
results.push(last_segment);
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
pub(super) fn layout_into_line_items(&self, ifc: &mut InlineFormattingContextState) {
|
||||
if self.text_range.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// If we are following replaced content, we should have a soft wrap opportunity, unless the
|
||||
// first character of this `TextRun` prevents that soft wrap opportunity. If we see such a
|
||||
// character it should also override the LineBreaker's indication to break at the start.
|
||||
let have_deferred_soft_wrap_opportunity =
|
||||
mem::replace(&mut ifc.have_deferred_soft_wrap_opportunity, false);
|
||||
let mut soft_wrap_policy = match self.prevent_soft_wrap_opportunity_at_start {
|
||||
true => SegmentStartSoftWrapPolicy::Prevent,
|
||||
false if have_deferred_soft_wrap_opportunity => SegmentStartSoftWrapPolicy::Force,
|
||||
false => SegmentStartSoftWrapPolicy::FollowLinebreaker,
|
||||
};
|
||||
|
||||
for segment in self.shaped_text.iter() {
|
||||
segment.layout_into_line_items(self, soft_wrap_policy, ifc);
|
||||
soft_wrap_policy = SegmentStartSoftWrapPolicy::FollowLinebreaker;
|
||||
}
|
||||
|
||||
ifc.prevent_soft_wrap_opportunity_before_next_atomic =
|
||||
self.prevent_soft_wrap_opportunity_at_end;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether or not this character will rpevent a soft wrap opportunity when it
|
||||
/// comes before or after an atomic inline element.
|
||||
///
|
||||
/// From <https://www.w3.org/TR/css-text-3/#line-break-details>:
|
||||
///
|
||||
/// > For Web-compatibility there is a soft wrap opportunity before and after each
|
||||
/// > replaced element or other atomic inline, even when adjacent to a character that
|
||||
/// > would normally suppress them, including U+00A0 NO-BREAK SPACE. However, with
|
||||
/// > the exception of U+00A0 NO-BREAK SPACE, there must be no soft wrap opportunity
|
||||
/// > between atomic inlines and adjacent characters belonging to the Unicode GL, WJ,
|
||||
/// > or ZWJ line breaking classes.
|
||||
fn char_prevents_soft_wrap_opportunity_when_before_or_after_atomic(character: char) -> bool {
|
||||
if character == '\u{00A0}' {
|
||||
return false;
|
||||
}
|
||||
let class = linebreak_property(character);
|
||||
class == XI_LINE_BREAKING_CLASS_GL ||
|
||||
class == XI_LINE_BREAKING_CLASS_WJ ||
|
||||
class == XI_LINE_BREAKING_CLASS_ZWJ
|
||||
}
|
||||
|
||||
/// Whether or not this character should be able to change the font during segmentation. Certain
|
||||
/// character are not rendered at all, so it doesn't matter what font we use to render them. They
|
||||
/// should just be added to the current segment.
|
||||
fn char_does_not_change_font(character: char) -> bool {
|
||||
if character.is_whitespace() || character.is_control() {
|
||||
return true;
|
||||
}
|
||||
if character == '\u{00A0}' {
|
||||
return true;
|
||||
}
|
||||
let class = linebreak_property(character);
|
||||
class == XI_LINE_BREAKING_CLASS_CM ||
|
||||
class == XI_LINE_BREAKING_CLASS_GL ||
|
||||
class == XI_LINE_BREAKING_CLASS_ZW ||
|
||||
class == XI_LINE_BREAKING_CLASS_WJ ||
|
||||
class == XI_LINE_BREAKING_CLASS_ZWJ
|
||||
}
|
||||
|
||||
pub(super) fn add_or_get_font(font: &FontRef, ifc_fonts: &mut Vec<FontKeyAndMetrics>) -> usize {
|
||||
for (index, ifc_font_info) in ifc_fonts.iter().enumerate() {
|
||||
if ifc_font_info.key == font.font_key && ifc_font_info.pt_size == font.descriptor.pt_size {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
ifc_fonts.push(FontKeyAndMetrics {
|
||||
metrics: font.metrics.clone(),
|
||||
key: font.font_key,
|
||||
pt_size: font.descriptor.pt_size,
|
||||
});
|
||||
ifc_fonts.len() - 1
|
||||
}
|
||||
|
||||
pub(super) fn get_font_for_first_font_for_style(
|
||||
style: &ComputedValues,
|
||||
font_context: &FontContext<FontCacheThread>,
|
||||
) -> Option<FontRef> {
|
||||
let font = font_context
|
||||
.font_group(style.clone_font())
|
||||
.write()
|
||||
.first(font_context);
|
||||
if font.is_none() {
|
||||
warn!("Could not find font for style: {:?}", style.clone_font());
|
||||
}
|
||||
font
|
||||
}
|
||||
pub(crate) struct TwoCharsAtATimeIterator<InputIterator> {
|
||||
/// The input character iterator.
|
||||
iterator: InputIterator,
|
||||
/// The first character to produce in the next run of the iterator.
|
||||
next_character: Option<char>,
|
||||
}
|
||||
|
||||
impl<InputIterator> TwoCharsAtATimeIterator<InputIterator> {
|
||||
fn new(iterator: InputIterator) -> Self {
|
||||
Self {
|
||||
iterator,
|
||||
next_character: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<InputIterator> Iterator for TwoCharsAtATimeIterator<InputIterator>
|
||||
where
|
||||
InputIterator: Iterator<Item = char>,
|
||||
{
|
||||
type Item = (char, Option<char>);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
// If the iterator isn't initialized do that now.
|
||||
if self.next_character.is_none() {
|
||||
self.next_character = self.iterator.next();
|
||||
}
|
||||
|
||||
let Some(character) = self.next_character else {
|
||||
return None;
|
||||
};
|
||||
|
||||
self.next_character = self.iterator.next();
|
||||
Some((character, self.next_character))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn break_and_shape(
|
||||
font: FontRef,
|
||||
text: &str,
|
||||
text_style: &InheritedText,
|
||||
shaping_options: &ShapingOptions,
|
||||
breaker: &mut Option<LineBreakLeafIter>,
|
||||
) -> (Vec<GlyphRun>, bool) {
|
||||
let mut glyphs = vec![];
|
||||
|
||||
if breaker.is_none() {
|
||||
if text.is_empty() {
|
||||
return (glyphs, true);
|
||||
}
|
||||
*breaker = Some(LineBreakLeafIter::new(text, 0));
|
||||
}
|
||||
|
||||
let breaker = breaker.as_mut().unwrap();
|
||||
|
||||
let mut push_range = |range: &Range<usize>, options: &ShapingOptions| {
|
||||
glyphs.push(GlyphRun {
|
||||
glyph_store: font.shape_text(&text[range.clone()], options),
|
||||
range: ServoRange::new(
|
||||
ByteIndex(range.start as isize),
|
||||
ByteIndex(range.len() as isize),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
let can_break_anywhere = text_style.word_break == WordBreak::BreakAll ||
|
||||
text_style.overflow_wrap == OverflowWrap::Anywhere ||
|
||||
text_style.overflow_wrap == OverflowWrap::BreakWord;
|
||||
|
||||
let mut break_at_zero = false;
|
||||
let mut last_slice_end = 0;
|
||||
while last_slice_end != text.len() {
|
||||
let (break_index, _is_hard_break) = breaker.next(text);
|
||||
if break_index == 0 {
|
||||
break_at_zero = true;
|
||||
}
|
||||
|
||||
// Extend the slice to the next UAX#14 line break opportunity.
|
||||
let mut slice = last_slice_end..break_index;
|
||||
let word = &text[slice.clone()];
|
||||
|
||||
// Split off any trailing whitespace into a separate glyph run.
|
||||
let mut whitespace = slice.end..slice.end;
|
||||
let mut rev_char_indices = word.char_indices().rev().peekable();
|
||||
let ends_with_newline = rev_char_indices.peek().map_or(false, |&(_, c)| c == '\n');
|
||||
if let Some((first_white_space_index, first_white_space_character)) = rev_char_indices
|
||||
.take_while(|&(_, c)| char_is_whitespace(c))
|
||||
.last()
|
||||
{
|
||||
whitespace.start = slice.start + first_white_space_index;
|
||||
|
||||
// If line breaking for a piece of text that has `white-space-collapse: break-spaces` there
|
||||
// is a line break opportunity *after* every preserved space, but not before. This means
|
||||
// that we should not split off the first whitespace, unless that white-space is a preserved
|
||||
// newline.
|
||||
//
|
||||
// An exception to this is if the style tells us that we can break in the middle of words.
|
||||
if text_style.white_space_collapse == WhiteSpaceCollapse::BreakSpaces &&
|
||||
first_white_space_character != '\n' &&
|
||||
!can_break_anywhere
|
||||
{
|
||||
whitespace.start += first_white_space_character.len_utf8();
|
||||
}
|
||||
|
||||
slice.end = whitespace.start;
|
||||
}
|
||||
|
||||
// If there's no whitespace and `word-break` is set to `keep-all`, try increasing the slice.
|
||||
// TODO: This should only happen for CJK text.
|
||||
let can_break_anywhere = text_style.word_break == WordBreak::BreakAll ||
|
||||
text_style.overflow_wrap == OverflowWrap::Anywhere ||
|
||||
text_style.overflow_wrap == OverflowWrap::BreakWord;
|
||||
if whitespace.is_empty() &&
|
||||
break_index != text.len() &&
|
||||
text_style.word_break == WordBreak::KeepAll &&
|
||||
!can_break_anywhere
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only advance the last_slice_end if we are not going to try to expand the slice.
|
||||
last_slice_end = break_index;
|
||||
|
||||
// Push the non-whitespace part of the range.
|
||||
if !slice.is_empty() {
|
||||
push_range(&slice, shaping_options);
|
||||
}
|
||||
|
||||
if whitespace.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut options = *shaping_options;
|
||||
options
|
||||
.flags
|
||||
.insert(ShapingFlags::IS_WHITESPACE_SHAPING_FLAG);
|
||||
|
||||
// If `white-space-collapse: break-spaces` is active, insert a line breaking opportunity
|
||||
// between each white space character in the white space that we trimmed off.
|
||||
if text_style.white_space_collapse == WhiteSpaceCollapse::BreakSpaces {
|
||||
let start_index = whitespace.start;
|
||||
for (index, character) in text[whitespace].char_indices() {
|
||||
let index = start_index + index;
|
||||
push_range(&(index..index + character.len_utf8()), &options);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// The breaker breaks after every newline, so either there is none,
|
||||
// or there is exactly one at the very end. In the latter case,
|
||||
// split it into a different run. That's because shaping considers
|
||||
// a newline to have the same advance as a space, but during layout
|
||||
// we want to treat the newline as having no advance.
|
||||
if ends_with_newline && whitespace.len() > 1 {
|
||||
push_range(&(whitespace.start..whitespace.end - 1), &options);
|
||||
push_range(&(whitespace.end - 1..whitespace.end), &options);
|
||||
} else {
|
||||
push_range(&whitespace, &options);
|
||||
}
|
||||
}
|
||||
(glyphs, break_at_zero)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue