use std::num::NonZeroU32;
use std::rc::Rc;
use f_office_paint::{Image, ImageColor, Opacity};
use f_office_units::{Edges, Length, div_round_i128};
use crate::body::{
Content, GapMinimum, GrownMark, InlineDrawing, NoteMark, NumberRef, Paragraph, Run, RunRecord,
StackMark,
};
use crate::character_class::CharacterClass;
use crate::kinsoku::{CharBreak, Kinsoku};
use crate::lines::{Frame, JointGaps, LeadingBreaks, Line, Piece, Shrink, advance, break_lines};
use crate::mode::ModeRules;
use crate::note_setup::NoteLabel;
use crate::numbering::{Label, LabelAlign, Suffix};
use crate::params;
use crate::params::{AUTO_TEXT_DARK_LUMA, LUMA_WEIGHTS};
use crate::picture::{Picture, bullet_natural_size};
use crate::properties::Property;
use crate::props::{
Alignment, BidiLanguageClass, Color, EastAsianScript, HtmlAutoSpacing, ListLevel, ListRef,
MarkChange, ParaProps, RunProps, TabKind, TabStop, Underline, WHITE,
};
use crate::styles::Justification;
use crate::tabs::Tabs;
use crate::text::{FaceIndex, SpaceKind};
use crate::warnings::Feature;
use super::decisions::{self, RevisionReading};
use super::{Layout, Resolved, Within};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum ParagraphDirection {
#[default]
LeftToRight,
RightToLeft,
}
impl ParagraphDirection {
pub(super) const fn is_rtl(self) -> bool {
matches!(self, Self::RightToLeft)
}
}
mod accents;
mod bars;
mod border_boxes;
mod gap_minimums;
mod group_chrs;
mod grown_delimiters;
mod hyphen_points;
mod limits;
mod matrices;
mod radicals;
mod scripts;
mod slashes;
mod structures;
use gap_minimums::Stacked;
pub(super) use gap_minimums::bar_edges;
use grown_delimiters::Grown;
pub(super) use hyphen_points::HyphenRun;
use hyphen_points::WordRules;
use structures::{OpenStructures, last_italic_correction};
pub(super) const JUSTIFIED_SHRINK: Shrink = Shrink {
permille: params::JUSTIFIED_SPACE_SHRINK,
stretch_permille: params::NEXT_WORD_STRETCH_SHARE,
natural: (0, 0),
joints: JointGaps { seen: 0, other: 0 },
};
const KASHIDA_JOINT_GAPS: JointGaps = JointGaps {
seen: params::NEXT_WORD_SEEN_JOINT_GAPS,
other: params::NEXT_WORD_JOINT_GAPS,
};
pub(super) const WORD_PERFECT_SHRINK: Shrink = Shrink {
permille: 0,
stretch_permille: 0,
natural: params::WORDPERFECT_LINE_SHRINK,
joints: JointGaps { seen: 0, other: 0 },
};
const MISSING_BOOKMARK: &str = "Error! Bookmark not defined.";
const MISSING_REFERENCE: &str = "Error! Reference source not found.";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Spacing {
EastAsian,
Digit,
Latin,
Other,
}
fn spacing_class(ch: char) -> Spacing {
match ch {
ch if CharacterClass::EastAsianSpacing.contains(ch) => Spacing::EastAsian,
'0'..='9' => Spacing::Digit,
'A'..='Z' | 'a'..='z' | '\u{00C0}'..='\u{024F}' if ch.is_alphabetic() => Spacing::Latin,
_ => Spacing::Other,
}
}
pub(super) fn shrink(
alignment: Option<Alignment>,
rules: ModeRules,
justification: Justification,
) -> Shrink {
match (
alignment.filter(|&alignment| alignment.justified()),
justification,
) {
(Some(_), _) if rules.shrinks_justified_spaces() => JUSTIFIED_SHRINK,
(Some(Alignment::Both), Justification::WordPerfect) => WORD_PERFECT_SHRINK,
_ => Shrink::default(),
}
}
struct Pending {
props: RunProps,
text: String,
starts: Vec<usize>,
joins: Vec<usize>,
buffer_starts: Vec<usize>,
field_mark: bool,
revisions: [Option<u32>; 3],
reading: RevisionReading,
record: RunRecord,
classes: Vec<(usize, Option<BidiLanguageClass>)>,
class: Option<BidiLanguageClass>,
runs: Vec<(usize, u32)>,
}
fn name_joined_runs(pieces: &mut [Piece], firsts: &[(usize, u32)]) {
let end = pieces.len();
for (at, &(first, run)) in firsts.iter().enumerate() {
let next = firsts.get(at + 1).map_or(end, |&(next, _)| next);
for piece in pieces.get_mut(first..next).unwrap_or_default() {
if let Piece::Glyph(glyph) = piece {
glyph.place.run = Some(run);
}
}
}
}
fn record_off_grid(off_grid: &mut Vec<u32>, index: u32, props: &RunProps) {
if props.snap_to_grid == Some(false) {
off_grid.push(index);
}
}
fn name_runs(pieces: &mut [Piece], from: usize, run: u32) {
for piece in pieces.get_mut(from..).unwrap_or_default() {
if let Piece::Glyph(glyph) = piece
&& glyph.place.run.is_none()
{
glyph.place.run = Some(run);
}
}
}
fn mark_glyphs(pieces: &mut [Piece], indexes: &[usize], mark: impl Fn(&mut crate::text::Glyph)) {
for &index in indexes {
if let Some(Piece::Glyph(glyph)) = pieces.get_mut(index) {
mark(glyph);
}
}
}
fn add_east_asian_space_splits(pieces: &[Piece], firsts: &mut Vec<usize>) {
let mut extra = Vec::new();
for (pos, &run_start) in firsts.iter().enumerate() {
let run_end = firsts.get(pos + 1).copied().unwrap_or(pieces.len());
let Some(Piece::Glyph(first)) = pieces.get(run_start) else {
continue;
};
if !matches!(first.ch, '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}') {
continue;
}
let mut cursor = run_start + 1;
while cursor < run_end {
match pieces.get(cursor) {
Some(Piece::Glyph(glyph)) if ('\u{2000}'..='\u{206F}').contains(&glyph.ch) => {
cursor += 1;
}
_ => break,
}
}
if cursor < run_end {
extra.push(cursor);
}
}
firsts.extend(extra);
}
impl Pending {
fn join(&mut self, text: &str, run: &Run, first: bool) {
let revisions = self.reading.read(run.revisions);
let new_run = run.starts_buffer || self.revisions != revisions || self.record != run.record;
let after_mark = std::mem::take(&mut self.field_mark);
if after_mark || (first && new_run) {
self.starts.push(self.text.len());
}
if first && !self.text.is_empty() {
self.joins.push(self.text.len());
}
if first && run.starts_buffer {
self.buffer_starts.push(self.text.len());
}
self.revisions = revisions;
self.record.clone_from(&run.record);
self.text.push_str(text);
}
fn start_run(&mut self, run: u32) {
self.runs.push((self.text.len(), run));
}
fn start_class(&mut self, class: Option<BidiLanguageClass>) {
if self.class != class {
self.classes.push((self.text.len(), class));
self.class = class;
}
}
fn new(props: &RunProps, text: &str, (run, index): (&Run, u32)) -> Self {
Self {
runs: vec![(0, index)],
revisions: run.revisions,
record: run.record.clone(),
buffer_starts: if run.starts_buffer {
vec![0]
} else {
Vec::new()
},
..Self::alone(props, text.to_owned())
}
}
fn reading(self, reading: RevisionReading) -> Self {
Self {
revisions: reading.read(self.revisions),
reading,
..self
}
}
fn alone(props: &RunProps, text: String) -> Self {
Self {
props: props.clone(),
text,
starts: Vec::new(),
joins: Vec::new(),
buffer_starts: Vec::new(),
field_mark: false,
revisions: [None; 3],
reading: RevisionReading::AS_WRITTEN,
record: RunRecord::default(),
classes: Vec::new(),
class: props.bidi_class,
runs: Vec::new(),
}
}
}
fn set_classes(pieces: &mut [Piece], classes: &[(usize, Option<BidiLanguageClass>)]) {
for &(from, class) in classes {
for piece in pieces.iter_mut().skip(from) {
if let Piece::Glyph(glyph) = piece {
glyph.direction = glyph.direction.with_class(class);
}
}
}
}
fn utf16_length(piece: &Piece) -> u32 {
match piece {
Piece::Glyph(glyph) => u32::try_from(glyph.ch.len_utf16()).unwrap_or(1),
Piece::Shift(_)
| Piece::Advance(_)
| Piece::Bar { .. }
| Piece::Vinculum { .. }
| Piece::Diagonal { .. } => 0,
_ => 1,
}
}
pub(super) struct OpenStack {
bar: Option<(usize, GapMinimum)>,
first: usize,
second: Option<usize>,
centered: bool,
lead: Length,
}
type SpanCorrection<'a> = dyn Fn(&[Piece]) -> Length + 'a;
pub(super) fn stack(
open: &mut Vec<OpenStack>,
pieces: &mut Vec<Piece>,
mark: StackMark,
(face, lead, correction): (Option<FaceIndex>, Length, &SpanCorrection<'_>),
) -> Option<Stacked> {
match mark {
StackMark::Start { bar, centered } => {
let bar = bar.zip(face).map(|(minimum, face)| {
pieces.push(Piece::Bar {
face,
width: Length::ZERO,
});
(pieces.len() - 1, minimum)
});
open.push(OpenStack {
bar,
first: pieces.len(),
second: None,
centered,
lead: Length::ZERO,
});
pieces.push(Piece::Shift(Length::ZERO));
None
}
StackMark::StartBeside(_) => {
open.push(OpenStack {
bar: None,
first: pieces.len(),
second: None,
centered: false,
lead,
});
pieces.push(Piece::Shift(Length::ZERO));
None
}
StackMark::Middle => {
if let Some(stack) = open.last_mut() {
stack.second = Some(pieces.len());
}
pieces.push(Piece::Shift(Length::ZERO));
None
}
StackMark::End => {
let stack = open.pop()?;
let end = pieces.len();
let middle = stack.second.unwrap_or(end);
let parts = end;
let width = |range: std::ops::Range<usize>| -> (Length, Length) {
let span = pieces.get(range).unwrap_or(&[]);
let past = stack.bar.map_or(Length::ZERO, |_| correction(span));
(span.iter().map(advance).sum(), past)
};
let (first, first_past) = width(stack.first + 1..middle);
let (second, second_past) = width((middle + 1).min(end)..end);
let wide = (first + first_past).max(second + second_past);
let before = |part: Length| {
if stack.centered {
(wide - part).div_toward_zero(2)
} else {
Length::ZERO
}
};
let (before_first, before_second) = (
before(first + first_past) - stack.lead,
before(second + second_past),
);
let end = (before_first + first + first_past).max(before_second + second + second_past);
let shift = |at: usize, by: Length, pieces: &mut Vec<Piece>| {
if let Some(piece) = pieces.get_mut(at) {
*piece = Piece::Shift(by);
}
};
shift(stack.first, before_first, pieces);
if let Some(middle) = stack.second {
shift(middle, before_second - before_first - first, pieces);
}
pieces.push(Piece::Shift(end - before_second - second));
if let Some(Piece::Bar { width, .. }) = stack.bar.and_then(|(at, _)| pieces.get_mut(at))
{
*width = end;
}
stack.bar.map(|(bar, minimum)| Stacked {
bar,
minimum,
numerator: stack.first + 1..middle,
denominator: (middle + 1).min(parts)..parts,
})
}
}
}
pub(super) fn spaces_beside_east_asian(pieces: &[Piece]) -> Vec<usize> {
let char_at = |at: usize| match pieces.get(at) {
Some(Piece::Glyph(glyph)) if !glyph.part => Some(glyph.ch),
_ => None,
};
let east = |at: Option<usize>| {
at.and_then(char_at)
.is_some_and(|ch| CharacterClass::EastAsianFont.contains(ch))
};
let mut found = Vec::new();
let mut start = 0;
while start < pieces.len() {
if char_at(start) != Some(' ') {
start += 1;
continue;
}
let end = (start..pieces.len())
.find(|&at| char_at(at) != Some(' '))
.unwrap_or(pieces.len());
if east(start.checked_sub(1)) || east(Some(end)) {
found.extend(start..end);
}
start = end;
}
found
}
pub(super) fn place_in_paragraph(pieces: &mut [Piece]) {
let mut in_paragraph = 0;
for piece in pieces {
let length = utf16_length(piece);
if let Piece::Glyph(glyph) = piece {
glyph.place.in_paragraph = in_paragraph;
}
in_paragraph += length;
}
}
#[derive(Debug, Default)]
pub(super) struct RunFeatures(Vec<(Feature, Rc<f_office_warnings::Name>)>);
impl RunFeatures {
fn add(&mut self, props: &RunProps, draws_text: impl FnOnce() -> bool) {
let mut shown = props.unsupported.shown().peekable();
if shown.peek().is_none() || props.hidden.unwrap_or(false) || !draws_text() {
return;
}
for (feature, part) in shown {
self.push(feature, part);
}
}
fn push(&mut self, feature: Feature, part: &Rc<f_office_warnings::Name>) {
let seen = self
.0
.iter()
.any(|(seen, seen_part)| *seen == feature && seen_part == part);
if !seen {
self.0.push((feature, part.clone()));
}
}
}
impl IntoIterator for RunFeatures {
type Item = (Feature, Rc<f_office_warnings::Name>);
type IntoIter = std::vec::IntoIter<(Feature, Rc<f_office_warnings::Name>)>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
fn draws_text(content: &Content) -> bool {
match content {
Content::Text(text) => !text.is_empty(),
Content::CheckBox(_)
| Content::PageNumber
| Content::PageCount
| Content::Date(_)
| Content::DocProperty(_)
| Content::StyleRef(_)
| Content::PageRef(_)
| Content::NumberRef(_)
| Content::If(_)
| Content::FootnoteReference(..)
| Content::FootnoteMark
| Content::EndnoteReference(..)
| Content::EndnoteMark => true,
Content::Tab
| Content::PositionTab { .. }
| Content::LineBreak
| Content::ClearingBreak
| Content::PageBreak
| Content::ColumnBreak
| Content::FieldBegin
| Content::FieldLock
| Content::DropDown(_)
| Content::FieldCode(_)
| Content::FieldSeparate
| Content::FieldEnd
| Content::FieldMark
| Content::HyperlinkEdge
| Content::ControlEdge
| Content::RemovedEdge
| Content::Bookmark(_)
| Content::CommentAnchor(_)
| Content::CommentMark
| Content::Separator
| Content::ContinuationSeparator
| Content::Stack(_)
| Content::Grown(_)
| Content::Radical(_)
| Content::Accent(_)
| Content::Matrix(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::MathLimit(_)
| Content::GroupChr(_)
| Content::MathBox(_)
| Content::Scripts(_)
| Content::Advance(_)
| Content::Floating(_)
| Content::Object { .. }
| Content::Drawing(_) => false,
}
}
fn automatic_color(props: &mut RunProps, (behind, story): (Option<[u8; 3]>, Option<[u8; 3]>)) {
if !matches!(props.color, None | Some(Color::Auto)) {
return;
}
if let Some(rgb) = story {
props.color = Some(Color::Rgb(rgb));
return;
}
let shading = match props.shading {
Some(Color::Rgb(rgb)) => Some(rgb),
_ => behind,
};
if shading.is_some_and(|rgb| luma(rgb) < AUTO_TEXT_DARK_LUMA) {
props.color = Some(Color::Rgb(WHITE));
}
}
fn luma(rgb: [u8; 3]) -> i64 {
rgb.iter()
.zip(LUMA_WEIGHTS)
.map(|(channel, weight)| i64::from(*channel) * weight)
.sum()
}
impl Layout<'_> {
pub(super) fn resolve(&mut self, paragraph: &Paragraph) -> Resolved {
let (style_props, run) = self.styles.paragraph(
paragraph.props.style.as_deref(),
self.column.cell.as_deref(),
);
let mut props = style_props.clone();
props.apply(¶graph.props);
let list = props.numbering.and_then(ListRef::id);
let ilvl = props.numbering_level.unwrap_or(ListLevel::FIRST).index();
let numbered = list.zip(ilvl);
let label = self.tracked_label(paragraph, numbered);
let level = numbered.and_then(|(num_id, ilvl)| self.numbering.level(num_id, ilvl).cloned());
if let Some(level) = level {
if paragraph.props.numbering.is_some() {
props = style_props;
props.apply(&level.para);
} else {
props = self.styles.paragraph_with_level(
paragraph.props.style.as_deref(),
self.column.cell.as_deref(),
&level.para,
);
}
props.apply(¶graph.props);
}
if let Some(region_align) = self
.column
.cell
.as_deref()
.and_then(|cell| cell.region_alignment)
&& paragraph.props.alignment == Some(Alignment::Start)
&& !self
.styles
.paragraph_style_sets_alignment(paragraph.props.style.as_deref())
{
props.alignment = Some(region_align);
}
decisions::take_border_sides(&self.context.quirks, &mut props);
self.device.read_paragraph_borders(&mut props);
if decisions::drop_between_border(&self.context.quirks, &mut props) {
let part = self.context.main;
self.warn_of_feature(crate::Feature::BetweenBorder, part);
}
let in_cell = self.column.cell.is_some();
decisions::cell_frame(&self.context.quirks, in_cell, &mut props);
if let reading @ HtmlAutoSpacing::Fixed =
decisions::html_auto_spacing(self.settings, &self.context.quirks)
{
props.html_auto_spacing = Some(reading);
}
let line_unit = self
.section
.spacing_line_pitch
.unwrap_or(params::SPACING_LINE_UNIT);
props.resolve_line_spacing(line_unit);
let label_shift = label
.as_ref()
.map_or(Length::ZERO, |label| self.label_shift(label, &run, &props));
Resolved {
props,
run,
label,
label_shift,
}
}
fn tracked_label(
&mut self,
paragraph: &Paragraph,
list: Option<(NonZeroU32, usize)>,
) -> Option<Label> {
let flags = paragraph.props.flags();
if flags.section_end || flags.continuous_end {
return None;
}
let change = paragraph.props.mark_change;
let original_list = match ¶graph.props.original {
Some(original) => {
let props = self
.styles
.paragraph_properties_without_list_level(original, self.column.cell.as_deref());
let ilvl = props.numbering_level.unwrap_or(ListLevel::FIRST).index();
props.numbering.and_then(ListRef::id).zip(ilvl)
}
None => list,
};
let new = list.filter(|_| change != Some(MarkChange::Deleted));
let original = original_list.filter(|_| change != Some(MarkChange::Inserted));
self.numbering.next_label(new, original)
}
pub(super) fn mark_props(&self, run: &RunProps, props: &ParaProps) -> RunProps {
mark_run_props(self.styles, run, props)
}
fn position_stop(&self, kind: TabKind, leader: Option<char>) -> TabStop {
let width = self.column.width;
let position = match kind {
TabKind::Center => width.div_toward_zero(2),
TabKind::Right => width,
_ => Length::ZERO,
};
TabStop {
position,
kind,
leader,
}
}
fn label_shift(&mut self, label: &Label, run: &RunProps, props: &ParaProps) -> Length {
if label.align == LabelAlign::Left {
return Length::ZERO;
}
let mut label_props = self.mark_props(run, props);
label_props.apply(&label.run);
let width = if label.picture {
label
.bullet_image
.as_ref()
.and_then(|image| self.picture_bullet_size(image, label.bullet_size, &label_props))
.map_or(Length::ZERO, |(width, _)| width)
} else {
let mut glyphs = Vec::new();
self.shaper.measure(&label_props, &label.text, &mut glyphs);
glyphs.iter().map(|g| g.advance).sum()
};
if label.align == LabelAlign::Center {
width.div_toward_zero(2)
} else {
width
}
}
fn picture_bullet_size(
&self,
image: &Image,
shape_size: Option<(Length, Length)>,
props: &RunProps,
) -> Option<(Length, Length)> {
let (nat_w, nat_h) = bullet_natural_size(image)?;
let (box_w, box_h) = shape_size
.filter(|(w, h)| *w > Length::ZERO && *h > Length::ZERO)
.unwrap_or((nat_w, nat_h));
let font_size = Length::from_half_points(props.drawn_half_points())?;
let two_pt = Length::from_points(2)?;
let base = (font_size - two_pt).max(two_pt);
let denom = nat_h.max(box_h);
let scale = |side: Length| {
Some(Length::from_units(
i64::try_from(div_round_i128(
i128::from(base.units()) * i128::from(side.units()),
i128::from(denom.units()),
))
.ok()?,
))
};
let dot = Length::from_units(Length::UNITS_PER_DOT);
let width = self.device.snap(scale(box_w)?).max(dot);
let height = self.device.snap(scale(box_h)?).max(dot);
Some((width, height))
}
fn story_text_color(&self) -> Option<[u8; 3]> {
match self.story.as_ref()?.kind {
super::StoryKind::TextBox { text_color, .. } => text_color,
_ => None,
}
}
pub(in crate::layout) fn smartart_text(&self) -> bool {
self.story.as_ref().is_some_and(|story| {
matches!(
story.kind,
super::StoryKind::TextBox {
box_text: crate::floating::BoxText::SmartArt,
..
}
)
})
}
fn text_background(&self, props: &ParaProps) -> Option<[u8; 3]> {
let fill = |color: Option<Color>| match color {
Some(Color::Rgb(rgb)) => Some(rgb),
_ => None,
};
fill(props.shading)
.or_else(|| fill(self.column.cell.as_deref()?.shading))
.or(self.settings.page_color)
}
pub(super) fn prepare(
&mut self,
paragraph: &Paragraph,
resolved: &Resolved,
) -> (Vec<Line>, Option<FaceIndex>, RunFeatures) {
self.prepare_with(paragraph, resolved, None)
}
pub(super) fn prepare_with(
&mut self,
paragraph: &Paragraph,
resolved: &Resolved,
cell_before: Option<&mut ParaProps>,
) -> (Vec<Line>, Option<FaceIndex>, RunFeatures) {
let (pieces, mark_face, features) = self.paragraph_pieces(paragraph, resolved, cell_before);
let frame = self.frame(resolved);
let mut lines = break_lines(&pieces, &frame);
if resolved.props.flags().continuous_break_end
&& self.column.cell.is_none()
&& self.story.is_none()
{
super::paragraph::drop_trailing_empty_break_line(&mut lines);
}
(lines, mark_face, features)
}
pub(super) fn least_width(&mut self, paragraph: &Paragraph, resolved: &Resolved) -> Length {
let (pieces, ..) = self.paragraph_pieces(paragraph, resolved, None);
let frame = self.frame(resolved);
let right = resolved.props.indent_right.unwrap_or(Length::ZERO);
crate::lines::widest_word(&pieces, &frame)
+ frame.start.max(frame.first_start).max(Length::ZERO)
+ right.max(Length::ZERO)
}
pub(super) fn unbroken_width(&mut self, paragraph: &Paragraph, resolved: &Resolved) -> Length {
let (pieces, ..) = self.paragraph_pieces(paragraph, resolved, None);
let mut frame = self.frame(resolved);
let unbounded = Length::from_units(Length::FILE_LIMIT);
frame.first_width += unbounded;
frame.width += unbounded;
frame.area_width += unbounded;
let right = resolved.props.indent_right.unwrap_or(Length::ZERO);
let widest = break_lines(&pieces, &frame)
.iter()
.enumerate()
.map(|(index, line)| {
let start = if index == 0 {
frame.first_start
} else {
frame.start
};
line.fit_width() + start.max(Length::ZERO)
})
.max()
.unwrap_or(Length::ZERO);
widest + right.max(Length::ZERO)
}
fn mark_face_of(
&mut self,
props: &RunProps,
direction: ParagraphDirection,
) -> Option<FaceIndex> {
decisions::mark_face(
&self.context.quirks,
props.uses_complex_formatting(),
direction.is_rtl(),
|kind| match kind {
decisions::MarkFaceKind::Complex => self.shaper.complex_face(props),
decisions::MarkFaceKind::ComplexSize => {
let mut sized = props.clone();
sized.size = props.size_cs;
self.shaper.face(&sized, true)
}
decisions::MarkFaceKind::Ascii => self.shaper.face(props, true),
},
)
}
fn paragraph_pieces(
&mut self,
paragraph: &Paragraph,
resolved: &Resolved,
cell_before: Option<&mut ParaProps>,
) -> (Vec<Piece>, Option<FaceIndex>, RunFeatures) {
let base_run = &resolved.run;
let mark = self.mark_props(base_run, &resolved.props);
let right_to_left = resolved.props.bidi.unwrap_or(false);
let direction = if right_to_left {
ParagraphDirection::RightToLeft
} else {
ParagraphDirection::LeftToRight
};
let mark_face = self.mark_face_of(&mark, direction);
let mut pieces = Vec::new();
let mut features = RunFeatures::default();
let behind = self.text_background(&resolved.props);
if let Some(label) = resolved.label.as_ref() {
self.measure_label(
label,
(&mark, behind, right_to_left),
(&mut pieces, &mut features),
);
}
let previous = self.number_context.take();
self.number_context = resolved.label.as_ref().map(|label| label.reference.clone());
let rules = self.word_rules(&resolved.props);
let outer = std::mem::replace(&mut self.hyphen_runs, rules.map(|_| Vec::new()));
let outer_bidi = std::mem::replace(&mut self.paragraph_bidi, direction);
let offset = pieces.len();
pieces.extend(self.measure(paragraph, base_run, behind, &mut features));
self.paragraph_bidi = outer_bidi;
let runs = std::mem::replace(&mut self.hyphen_runs, outer);
self.number_context = previous;
self.auto_space(&mut pieces, resolved);
self.stretching_no_break_spaces(pieces.get_mut(offset..).unwrap_or_default());
if let (Some(rules), Some(runs)) = (rules, runs) {
pieces = hyphen_points::with_points(pieces, offset, &runs, rules);
}
if self.column.cell.is_some() {
decisions::cell_breaks(&self.context.quirks, &mut pieces, offset, cell_before);
}
let breaking = decisions::line_breaking(&self.context.quirks, self.settings.mode_rules);
label_after_page_breaks(&mut pieces, offset, breaking.leading_breaks);
(pieces, mark_face, features)
}
fn auto_space(&self, pieces: &mut [Piece], resolved: &Resolved) {
let flags = resolved.props.flags();
let (digits, latin) = (flags.auto_space_digits, flags.auto_space_latin);
if (!digits && !latin)
|| !self
.shaper
.names_east_asian_default(self.styles.default_run())
{
return;
}
for index in 1..pieces.len() {
let (Some(Piece::Glyph(a)), Some(Piece::Glyph(b))) =
(pieces.get(index - 1), pieces.get(index))
else {
continue;
};
let spaced = match (spacing_class(a.ch), spacing_class(b.ch)) {
(Spacing::EastAsian, Spacing::Digit) | (Spacing::Digit, Spacing::EastAsian) => {
digits
}
(Spacing::EastAsian, Spacing::Latin) | (Spacing::Latin, Spacing::EastAsian) => {
latin
}
_ => false,
};
let balanced =
self.settings.full_width_spacing == crate::styles::FullWidthSpacing::Twice;
let space = self.shaper.faces().get(a.face).map_or_default(|f| {
decisions::east_asian_auto_space(&self.context.quirks, f.size, &f.metrics, balanced)
});
if let (true, Some(Piece::Glyph(a))) = (spaced, pieces.get_mut(index - 1)) {
a.advance += space.advance;
a.auto_space += space.extra;
a.trailing_auto_space += space.advance;
}
}
}
fn stretching_no_break_spaces(&self, pieces: &mut [Piece]) {
let defaults = self.styles.template_run_defaults()
|| self
.shaper
.names_east_asian_default(self.styles.default_run());
let stretch = decisions::no_break_spaces_stretch(
&self.context.quirks,
self.settings.mode_rules,
defaults,
);
if !stretch {
return;
}
for piece in pieces {
if let Piece::Glyph(glyph) = piece
&& glyph.ch == '\u{a0}'
&& glyph.space == SpaceKind::Free
&& !glyph.starts_run
{
glyph.space = SpaceKind::NoBreak;
}
}
}
fn char_grid(&self, pieces: &mut [Piece], off_grid: &[u32]) {
let Some(pitch) = self.section.char_pitch else {
return;
};
for piece in pieces {
if let Piece::Glyph(glyph) = piece
&& !glyph.place.run.is_some_and(|run| off_grid.contains(&run))
{
glyph.advance += if CharacterClass::FullWidthCell.contains(glyph.ch) {
pitch
} else {
pitch.div_toward_zero(2)
};
}
}
}
fn word_rules(&self, props: &ParaProps) -> Option<WordRules> {
let hyphenation = self.settings.hyphenation?;
decisions::hyphenation(&self.context.quirks, || {
(!props.flags().suppress_auto_hyphens).then(|| WordRules {
least: self.settings.mode_rules.hyphen_least_letters(),
capitals: hyphenation.capitals,
})
})
}
pub(super) fn frame(&self, resolved: &Resolved) -> Frame {
let props = &resolved.props;
let column = self.column.width;
let indent_last = resolved.label.is_some()
&& !self.settings.indent_is_numbering_tab_stop
&& self.settings.mode_rules.reads_numbering_indent_setting();
let left = props.indent_left.unwrap_or(Length::ZERO);
let right = props.indent_right.unwrap_or(Length::ZERO);
let first = props.indent_first.unwrap_or(Length::ZERO) - resolved.label_shift;
let overflow_punct = self.overflow_punct(props);
Frame {
first_width: column - left - right - first,
width: column - left - right,
area_width: column,
first_start: left + first,
start: left,
tabs: {
let indent = (first < Length::ZERO).then_some(left);
let mut tabs = Tabs::new(props.tab_stops(), self.settings.default_tab_stop, indent);
if indent_last {
tabs = tabs.with_indent_after_custom_stops();
}
if self.settings.mode_rules.truncates_negative_default_tabs() {
tabs = tabs.with_truncated_negative_default_tabs();
}
tabs
},
shrink: {
let shrink = shrink(
props.alignment,
self.settings.mode_rules,
decisions::justification(&self.context.quirks, self.settings),
);
if decisions::kashida_joints(&self.context.quirks, self.settings, props.kashidas)
== Some(decisions::KashidaJoints::SeensThenFinals)
{
Shrink {
joints: KASHIDA_JOINT_GAPS,
..shrink
}
} else {
shrink
}
},
thai_keeps_spaces: props.alignment == Some(Alignment::ThaiDistribute),
end_space_fit: decisions::end_space_fit(&self.context.quirks, props.flags().bidi),
kinsoku: self.paragraph_kinsoku(
props,
resolved.run.east_asian_script(),
overflow_punct,
),
joined_spaces: self.settings.mode_rules.joins_space_runs(),
breaking: decisions::line_breaking(&self.context.quirks, self.settings.mode_rules),
limits_past_end: self.settings.mode_rules.limits_text_past_the_line_end(),
punctuation: self.line_punctuation(props),
hyphenation: self
.word_rules(props)
.and(self.settings.hyphenation)
.map(|hyphenation| crate::lines::Hyphenation {
zone: self
.settings
.mode_rules
.hyphenation_zone_holds()
.then_some(hyphenation.zone),
limit: hyphenation.limit,
}),
overflow_punct,
}
}
fn line_punctuation(&self, props: &ParaProps) -> Option<crate::lines::Compression> {
if self.settings.punctuation != crate::styles::Punctuation::Compressed {
return None;
}
let justified = props.alignment.is_some_and(Alignment::justified);
let script = self.east_asian_punctuation_script();
let trailing_trim = if self
.settings
.mode_rules
.trims_trailing_closing_punctuation()
{
match script {
Some(EastAsianScript::Japanese) => crate::lines::TrailingTrim::NonJapaneseCentered,
Some(EastAsianScript::Traditional) => {
crate::lines::TrailingTrim::NonTraditionalCentered
}
_ => crate::lines::TrailingTrim::Closing,
}
} else {
crate::lines::TrailingTrim::None
};
if !justified && trailing_trim == crate::lines::TrailingTrim::None {
return None;
}
Some(crate::lines::Compression {
ratio: if justified {
params::PUNCTUATION_SHRINK_RATIO
} else {
0
},
middle_dot: script == Some(EastAsianScript::Japanese),
trailing_trim,
})
}
fn overflow_punct(&self, props: &ParaProps) -> crate::lines::OverflowPunct {
let flags = props.flags();
if !flags.overflow_punct {
return crate::lines::OverflowPunct::Off;
}
let active = self.column.cell.is_none()
&& !flags.bidi
&& self
.shaper
.names_east_asian_default(self.styles.default_run())
&& (self
.settings
.mode_rules
.hangs_punctuation_on_all_alignments()
|| (props.alignment.is_some_and(Alignment::justified) && flags.kinsoku));
if active {
crate::lines::OverflowPunct::Hang
} else {
crate::lines::OverflowPunct::Warn
}
}
fn paragraph_kinsoku(
&self,
props: &ParaProps,
run_script: Option<EastAsianScript>,
overflow_punct: crate::lines::OverflowPunct,
) -> Option<Kinsoku> {
let flags = props.flags();
let break_words =
!flags.word_wrap && self.settings.mode_rules.breaks_words_when_word_wrap_off();
let sets = |script: EastAsianScript| {
let full = Kinsoku::of(script);
let base = if flags.kinsoku {
full
} else if overflow_punct == crate::lines::OverflowPunct::Hang {
Kinsoku::FREE.with_hanging_of(full)
} else {
Kinsoku::FREE
};
if flags.overflow_punct {
base
} else {
base.without_hanging()
}
};
let non_korean_mode = if break_words {
CharBreak::Any
} else {
CharBreak::CjkNonHangul
};
match (run_script, self.settings.east_asian_script) {
(Some(EastAsianScript::Korean), _) => break_words
.then(|| sets(EastAsianScript::Korean).with_char_break(CharBreak::FullWidth)),
(Some(script), _) => Some(sets(script).with_char_break(non_korean_mode)),
(None, Some(_)) => Some(
Kinsoku::FREE
.with_restricted(flags.kinsoku)
.with_char_break(non_korean_mode),
),
(None, None) => break_words.then(|| {
Kinsoku::FREE
.with_restricted(flags.kinsoku)
.with_char_break(CharBreak::Any)
}),
}
}
fn measure_label(
&mut self,
label: &Label,
(mark, behind, right_to_left): (&RunProps, Option<[u8; 3]>, bool),
(pieces, features): (&mut Vec<Piece>, &mut RunFeatures),
) {
let mut props = self.list_label_props(label, mark, right_to_left);
automatic_color(&mut props, (behind, self.story_text_color()));
self.drawn_effects(&mut props);
features.add(&props, || !label.picture && !label.text.is_empty());
let width = if label.picture {
if let Some(image) = label.bullet_image.as_ref()
&& let Some((width, height)) =
self.picture_bullet_size(image, label.bullet_size, &props)
{
self.output.pictures.push(Picture {
embed: String::new(),
image: Some(image.clone()),
opacity: Opacity::FULL,
color: ImageColor::default(),
left: Length::ZERO,
top: Length::ZERO,
width,
height,
crop: Edges::default(),
turn: None,
drops: false,
line: None,
shadow: None,
soft_edge: None,
glow: None,
reflection: None,
geometry: f_office_drawingml::shape::Geometry::Rect,
scale_steps: None,
on_device_dots: true,
});
pieces.push(Piece::Object {
width,
height,
raised: props.position.unwrap_or(Length::ZERO),
picture: Some(self.output.pictures.len() - 1),
drawing: None,
underlined: false,
run_face: None,
joins_before: false,
});
width
} else {
if !props.hidden.unwrap_or(false) {
features.push(Feature::PictureBullet, self.numbering.part());
}
Length::ZERO
}
} else {
let mut glyphs = Vec::new();
self.shaper.measure_label(&props, &label.text, &mut glyphs);
let width: Length = glyphs.iter().map(|g| g.advance).sum();
pieces.extend(glyphs.into_iter().map(|glyph| {
Piece::Glyph(crate::text::Glyph {
label: true,
..glyph
})
}));
width
};
match label.suffix {
Suffix::Tab => {
let plain = RunProps {
underline: Some(Underline::None),
..props.clone()
};
pieces.push(Piece::Tab(self.shaper.face(&plain, true)));
}
Suffix::Space => self.measure_content(&Content::Text(" ".to_owned()), &props, pieces),
Suffix::Nothing => {}
Suffix::Legacy { space, indent } => pieces.push(Piece::Object {
width: (indent - width).max(space),
height: Length::ZERO,
raised: Length::ZERO,
picture: None,
drawing: None,
underlined: false,
run_face: None,
joins_before: false,
}),
}
if props.snap_to_grid.unwrap_or(true) {
self.char_grid(pieces, &[]);
}
}
fn list_label_props(&self, label: &Label, mark: &RunProps, right_to_left: bool) -> RunProps {
list_label_props(&self.shaper, label, mark, right_to_left)
}
fn measure_stack(
&mut self,
mark: StackMark,
props: &RunProps,
(stacks, pieces): (&mut Vec<OpenStack>, &mut Vec<Piece>),
) {
let face = self.shaper.face(props, true);
let lead = match (mark, face) {
(StackMark::StartBeside(operator), Some(face)) => {
self.shaper.italic_correction(face, operator)
}
_ => Length::ZERO,
};
let correction = |part: &[Piece]| last_italic_correction(&self.shaper, part);
if let Some(stacked) = stack(stacks, pieces, mark, (face, lead, &correction)) {
gap_minimums::keep((&mut self.shaper, self.device), pieces, &stacked);
}
}
fn measure_grown(
&mut self,
mark: GrownMark,
props: &RunProps,
(pending, grown, pieces): (&mut Option<Pending>, &mut Grown, &mut Vec<Piece>),
) {
if !decisions::grows_delimiters(&self.context.quirks) {
if matches!(mark, GrownMark::SpaceBefore | GrownMark::SpaceAfter) {
self.measure_pending(pending.take(), pieces);
let last = pieces.len().checked_sub(1);
grown_delimiters::hide(pieces, last);
}
return;
}
self.measure_pending(pending.take(), pieces);
grown_delimiters::mark(
(&mut self.shaper, self.device),
(grown, pieces),
mark,
props,
);
}
fn drawn_effects(&self, props: &mut RunProps) {
let (shadow, glow, reflection, legacy) = self.shaper.draws_text_effects(props);
if shadow {
props.unsupported.shadow_drawn();
}
if glow {
props.unsupported.glow_drawn();
}
if reflection {
props.unsupported.reflection_drawn();
}
if legacy {
props.unsupported.legacy_effects_drawn();
}
}
fn measure(
&mut self,
paragraph: &Paragraph,
base_run: &RunProps,
behind: Option<[u8; 3]>,
features: &mut RunFeatures,
) -> Vec<Piece> {
let mut pieces = Vec::new();
let mut pending: Option<Pending> = None;
let mut stacks = Vec::new();
let mut grown = Grown::default();
let mut structures = OpenStructures::default();
let mut drawings = 0;
let mut named = 0;
let mut index = 0;
let mut off_grid = Vec::new();
for (place, run) in paragraph.runs.iter().enumerate() {
index = u32::try_from(place).unwrap_or(u32::MAX);
let mut props = self.run_props(run, base_run);
record_off_grid(&mut off_grid, index, &props);
automatic_color(&mut props, (behind, self.story_text_color()));
self.drawn_effects(&mut props);
features.add(&props, || run.content.iter().any(draws_text));
let mut first = true;
for content in &run.content {
match (content, &mut pending) {
(Content::Text(text), Some(joined)) if joined.props.joins(&props) => {
joined.start_class(props.bidi_class);
if first {
joined.start_run(index);
}
joined.join(text, run, first);
}
(Content::Text(text), _) => {
self.measure_pending(pending.take(), &mut pieces);
pending = Some(
Pending::new(&props, text, (run, index))
.reading(RevisionReading::of(&self.context.quirks)),
);
}
(
Content::FieldMark
| Content::HyperlinkEdge
| Content::ControlEdge
| Content::RemovedEdge,
Some(joined),
) => {
joined.field_mark |=
decisions::starts_text_object(&self.context.quirks, content);
}
(Content::Stack(mark), _) => {
self.measure_pending(pending.take(), &mut pieces);
self.measure_stack(*mark, &props, (&mut stacks, &mut pieces));
}
(Content::Grown(mark), _) => {
self.measure_grown(*mark, &props, (&mut pending, &mut grown, &mut pieces));
}
(
Content::Radical(_)
| Content::Accent(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::MathLimit(_)
| Content::GroupChr(_)
| Content::MathBox(_)
| Content::Matrix(_)
| Content::Scripts(_),
_,
) => {
self.measure_pending(pending.take(), &mut pieces);
structures.mark(
(&mut self.shaper, self.device),
&mut pieces,
content,
&props,
);
}
(Content::Floating(drawing), _) => {
self.measure_pending(pending.take(), &mut pieces);
if !pieces.is_empty() && self.marks_anchor(drawing) {
pieces.push(Piece::Anchor(drawings));
}
drawings += 1;
}
_ => self.measure_other(content, &props, (&mut pending, &mut pieces)),
}
first &= !matches!(content, Content::Text(_));
name_runs(&mut pieces, named, index);
named = pieces.len();
}
}
self.measure_pending(pending, &mut pieces);
name_runs(&mut pieces, named, index);
self.balance_spaces(&mut pieces);
self.char_grid(&mut pieces, &off_grid);
place_in_paragraph(&mut pieces);
pieces
}
fn measure_other(
&mut self,
content: &Content,
props: &RunProps,
(pending, pieces): (&mut Option<Pending>, &mut Vec<Piece>),
) {
if decisions::ends_text(&self.context.quirks, content) {
self.measure_pending(pending.take(), pieces);
}
self.measure_content(content, props, pieces);
}
fn balance_spaces(&self, pieces: &mut [Piece]) {
if !self.shaper.balances_spaces() {
return;
}
for at in spaces_beside_east_asian(pieces) {
if let Some(Piece::Glyph(glyph)) = pieces.get_mut(at) {
self.shaper.balance_space(glyph);
}
}
}
fn measure_pending(&mut self, pending: Option<Pending>, pieces: &mut Vec<Piece>) {
let Some(Pending {
props,
text,
starts,
joins,
buffer_starts,
classes,
runs,
..
}) = pending
else {
return;
};
let start = pieces.len();
let glyph_at = |shaper: &mut crate::text::Shaper<'_>, at: usize| {
start + shaper.count(&props, text.get(..at).unwrap_or(""))
};
let mut firsts = vec![start];
for &at in &starts {
firsts.push(glyph_at(&mut self.shaper, at));
}
let buffer_firsts: Vec<usize> = buffer_starts
.iter()
.map(|&at| glyph_at(&mut self.shaper, at))
.collect();
let join_firsts: Vec<usize> = joins
.iter()
.map(|&at| glyph_at(&mut self.shaper, at))
.collect();
let run_firsts: Vec<(usize, u32)> = runs
.iter()
.map(|&(at, run)| (glyph_at(&mut self.shaper, at), run))
.collect();
let classes: Vec<(usize, Option<BidiLanguageClass>)> = classes
.into_iter()
.map(|(at, class)| (glyph_at(&mut self.shaper, at), class))
.collect();
self.measure_content(&Content::Text(text), &props, pieces);
self.correct_italics_at_joins(pieces, &join_firsts);
self.keep_hyphen_run(&props, (start, pieces.len()));
if props.field_rtl.is_none() {
set_classes(pieces, &classes);
}
if props.font_east_asia.is_some() {
add_east_asian_space_splits(pieces, &mut firsts);
}
mark_glyphs(pieces, &firsts, |glyph| glyph.starts_run = true);
name_joined_runs(pieces, &run_firsts);
mark_glyphs(pieces, &buffer_firsts, |glyph| {
glyph.place.starts_buffer = true;
});
let mut in_run = 0;
for (index, piece) in pieces.iter_mut().enumerate().skip(start) {
if firsts.contains(&index) {
in_run = 0;
}
let length = utf16_length(piece);
if let Piece::Glyph(glyph) = piece {
glyph.place.in_run = in_run;
}
in_run += length;
}
}
fn keep_hyphen_run(&mut self, props: &RunProps, (start, end): (usize, usize)) {
if self.hyphen_runs.is_none() || start == end {
return;
}
let Some(language) = props
.lang
.as_deref()
.and_then(|tag| decisions::hyphenation_language(&self.context.quirks, tag))
else {
return;
};
let mut hyphen = Vec::new();
self.shaper.measure(props, "-", &mut hyphen);
if let (Some(&hyphen), Some(runs)) = (hyphen.first(), self.hyphen_runs.as_mut()) {
runs.push(HyphenRun {
start,
end,
language,
hyphen,
});
}
}
fn measure_rule(&mut self, width: Length, props: &RunProps, pieces: &mut Vec<Piece>) {
pieces.extend(
self.shaper
.face(props, true)
.map(|face| Piece::Rule { face, width }),
);
}
fn object_underlined(&mut self, props: &RunProps) -> bool {
self.shaper
.face(props, true)
.and_then(|index| self.shaper.faces().get(index))
.is_some_and(|face| face.lines.under != Underline::None)
}
fn object_run_face(&mut self, props: &RunProps) -> Option<FaceIndex> {
if props.position.is_some() {
let unshifted = RunProps {
position: None,
..props.clone()
};
self.shaper.face(&unshifted, true)
} else {
self.shaper.face(props, true)
}
}
fn measure_object(
&mut self,
(width, height): (Length, Length),
(picture, extent): (Option<&Picture>, Option<Length>),
props: &RunProps,
pieces: &mut Vec<Piece>,
) {
let upright = match self.column.within {
Within::TurnedFrame(..) => decisions::upright_picture(&self.context.quirks, picture),
Within::Page | Within::Cell(_) => None,
};
let (width, height, extent) = if upright.flatten().is_some() {
(height, width, extent.map(|_| width))
} else {
(width, height, extent)
};
let picture = picture.map(|picture| {
self.output.pictures.push(picture.clone());
self.output.pictures.len() - 1
});
let underlined = self.object_underlined(props);
let run_face = self.object_run_face(props);
pieces.push(Piece::Object {
width,
height: self.device.inline_room_height(height, extent),
raised: props.position.unwrap_or(Length::ZERO),
picture,
drawing: None,
underlined,
run_face,
joins_before: false,
});
}
fn measure_drawing(
&mut self,
drawing: &Rc<InlineDrawing>,
props: &RunProps,
pieces: &mut Vec<Piece>,
) {
let index = self.output.add_drawing(Rc::clone(drawing));
let (width, height) = self
.outline_room(drawing)
.unwrap_or((drawing.width, drawing.height));
let underlined = self.object_underlined(props);
let run_face = self.object_run_face(props);
pieces.push(Piece::Object {
width,
height: self.device.inline_room_height(height, drawing.extent),
raised: props.position.unwrap_or(Length::ZERO),
picture: None,
drawing: Some(index),
underlined,
run_face,
joins_before: drawing.drops && drawing.shape.parts.is_empty(),
});
}
fn measure_content(&mut self, content: &Content, props: &RunProps, pieces: &mut Vec<Piece>) {
match content {
Content::Text(text) => self.measure_text(text, props, pieces),
Content::Tab => pieces.push(Piece::Tab(self.shaper.face(props, true))),
Content::PositionTab { kind, leader } => {
let stop = self.position_stop(*kind, *leader);
pieces.push(Piece::PositionTab(self.shaper.face(props, true), stop));
}
Content::Separator => self.measure_rule(self.separator_rule_width(), props, pieces),
Content::ContinuationSeparator => {
self.measure_rule(self.continuation_rule_width(), props, pieces);
}
Content::LineBreak => {
let face = self.mark_face_of(props, self.paragraph_bidi);
pieces.push(Piece::LineBreak(face));
}
Content::ClearingBreak => {
let face = self.mark_face_of(props, self.paragraph_bidi);
pieces.push(Piece::LineBreak(face));
pieces.push(Piece::Clear);
}
Content::PageBreak => pieces.push(Piece::PageBreak),
Content::ColumnBreak => {
if self.settings.mode_rules.column_break_line_has_height() {
pieces.extend(self.shaper.face(props, true).map(Piece::Strut));
}
pieces.push(Piece::ColumnBreak);
}
Content::PageNumber
| Content::PageCount
| Content::Date(_)
| Content::DocProperty(_)
| Content::StyleRef(_)
| Content::PageRef(_)
| Content::NumberRef(_)
| Content::If(_) => {
let text = self.field_text(content);
if matches!(content, Content::StyleRef(_)) && text.contains(['\t', '\n']) {
self.measure_style_ref(&text, props, pieces);
} else {
self.measure_pending(Some(Pending::alone(props, text)), pieces);
}
}
Content::Object {
width,
height,
picture,
extent,
} => self.measure_object(
(*width, *height),
(picture.as_deref(), *extent),
props,
pieces,
),
Content::Drawing(drawing) => self.measure_drawing(drawing, props, pieces),
Content::Advance(by) => pieces.push(Piece::Advance(*by)),
Content::FootnoteReference(_, _)
| Content::FootnoteMark
| Content::EndnoteReference(_, _)
| Content::EndnoteMark => self.measure_note_content(content, props, pieces),
Content::CheckBox(check_box) => self.measure_check_box(*check_box, props, pieces),
Content::CommentMark => pieces.extend(self.shaper.face(props, true).map(Piece::Strut)),
Content::CommentAnchor(id) => {
pieces.extend(self.comment_markup.index(id).map(Piece::Comment));
}
Content::Floating(_)
| Content::Stack(_)
| Content::Grown(_)
| Content::Radical(_)
| Content::Accent(_)
| Content::Matrix(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::MathLimit(_)
| Content::GroupChr(_)
| Content::MathBox(_)
| Content::Scripts(_)
| Content::Bookmark(_)
| Content::FieldMark
| Content::HyperlinkEdge
| Content::ControlEdge
| Content::RemovedEdge
| Content::FieldBegin
| Content::FieldLock
| Content::DropDown(_)
| Content::FieldCode(_)
| Content::FieldSeparate
| Content::FieldEnd => {}
}
}
fn measure_note_content(
&mut self,
content: &Content,
props: &RunProps,
pieces: &mut Vec<Piece>,
) {
match content {
Content::FootnoteReference(id, mark) => {
let number = self.note_number(*id, *mark);
if *mark == NoteMark::Number {
let label = self.note_label(number);
self.measure_content(&Content::Text(label.to_string()), props, pieces);
}
pieces.push(Piece::Note(number));
}
Content::FootnoteMark => {
let label = self.footnote_label().unwrap_or(NoteLabel::FIRST);
self.measure_content(&Content::Text(label.to_string()), props, pieces);
pieces.push(Piece::NoteMarkEnd);
}
Content::EndnoteReference(id, mark) => {
let label = self.endnote_label(Some((*id, *mark)));
if *mark == NoteMark::Number {
let before = pieces.len();
self.measure_content(&Content::Text(label.to_string()), props, pieces);
if let Ok(count) = u16::try_from(pieces.len().saturating_sub(before))
&& count > 0
{
pieces.push(Piece::Endnote(count));
}
}
}
Content::EndnoteMark => {
let label = self.endnote_label(None);
let before = pieces.len();
self.measure_content(&Content::Text(label.to_string()), props, pieces);
let count = u16::try_from(pieces.len().saturating_sub(before)).unwrap_or(0);
pieces.push(Piece::EndnoteMarkEnd(count));
}
_ => {}
}
}
fn separator_rule_width(&self) -> Length {
if self.settings.mode_rules.notes_in_reference_column() {
params::NOTE_SEPARATOR_WIDTH.min(self.column.width)
} else {
params::NOTE_SEPARATOR_WIDTH
}
}
fn continuation_rule_width(&self) -> Length {
let endnotes = self
.story
.as_ref()
.is_some_and(|story| story.kind == super::StoryKind::EndnoteContinuation);
if self.settings.mode_rules.shortens_continuation_rule() && !endnotes {
params::NOTE_SEPARATOR_WIDTH
} else {
self.column.width
}
}
fn measure_text(&mut self, text: &str, props: &RunProps, pieces: &mut Vec<Piece>) {
let mut glyphs = Vec::new();
self.shaper.measure(props, text, &mut glyphs);
let joined = glyphs
.first()
.filter(|first| {
crate::text::is_selector(first)
&& pieces.iter().any(|piece| matches!(piece, Piece::Glyph(_)))
})
.map(|first| Piece::Strut(first.face));
let mut glyphs: Vec<_> = glyphs
.into_iter()
.skip(usize::from(joined.is_some()))
.collect();
let before = pieces
.iter_mut()
.rev()
.find(|piece| !matches!(piece, Piece::Glyph(g) if g.part));
if let (Some(Piece::Glyph(left)), Some(right)) = (before, glyphs.first_mut()) {
self.shaper.kern_across(left, right);
self.shaper.correct_italic(left, right);
}
pieces.extend(joined);
pieces.extend(glyphs.into_iter().map(Piece::Glyph));
}
fn correct_italics_at_joins(&self, pieces: &mut [Piece], firsts: &[usize]) {
for &first in firsts {
let Some((before, after)) = pieces.split_at_mut_checked(first) else {
continue;
};
let left = before
.iter_mut()
.rev()
.find(|piece| !matches!(piece, Piece::Glyph(g) if g.part));
if let (Some(Piece::Glyph(left)), Some(Piece::Glyph(right))) = (left, after.first()) {
self.shaper.correct_italic_at_join(left, right);
}
}
}
fn measure_check_box(
&mut self,
check_box: crate::body::CheckBox,
props: &RunProps,
pieces: &mut Vec<Piece>,
) {
let mut props = props.clone();
if check_box.size.is_some() {
props.size = check_box.size;
}
if let Some(face) = self.shaper.face(&props, true) {
let width = self
.shaper
.faces()
.get(face)
.map_or(Length::ZERO, crate::text::Face::line_height);
pieces.push(Piece::CheckBox { face, width });
}
}
fn measure_style_ref(&mut self, text: &str, props: &RunProps, pieces: &mut Vec<Piece>) {
let mut rest = text;
loop {
let end = rest.find(['\t', '\n']).unwrap_or(rest.len());
if end > 0 {
let stretch = Pending::alone(props, rest[..end].to_owned());
self.measure_pending(Some(stretch), pieces);
}
match rest[end..].chars().next() {
Some('\t') => pieces.push(Piece::Tab(self.shaper.face(props, true))),
Some('\n') => {
let face = self.mark_face_of(props, self.paragraph_bidi);
pieces.push(Piece::LineBreak(face));
}
_ => break,
}
rest = &rest[end + 1..];
}
}
fn page_text(&self, content: &Content) -> String {
let (number, count) = self.story_pages().unwrap_or_else(|| {
let number = self.page_number(self.output.pages.len());
(number, self.context.earlier.page_count.unwrap_or(number))
});
if *content == Content::PageNumber {
self.chapter_prefix().unwrap_or_default() + &self.section.page_number(number)
} else {
count.to_string()
}
}
fn run_props(&self, run: &Run, base_run: &RunProps) -> RunProps {
let mut props = base_run.clone();
if let Some((style, direct)) = self.error_format(run) {
if let Some(style) = style {
self.styles.apply_character(&mut props, style);
}
props.apply(direct);
props.bold = Some(!props.bold.unwrap_or(false));
props.bold_cs = Some(!props.bold_cs.unwrap_or(false));
} else {
let (style, direct) = decisions::run_format(&self.context.quirks, run);
if let Some(style) = style {
self.styles.apply_character(&mut props, style);
}
props.apply(&direct);
}
props.math_script = props
.math_script
.map(|script| script.at_paragraph_size(base_run.drawn_half_points()));
props
}
fn error_format<'r>(&self, run: &'r Run) -> Option<(&'r Option<String>, &'r RunProps)> {
run.content.iter().find_map(|content| {
let code = match content {
Content::PageRef(field) => field.code.as_ref(),
Content::NumberRef(field) => field.code.as_ref(),
_ => return None,
};
let text = self.field_text(content);
(text == MISSING_BOOKMARK || text == MISSING_REFERENCE)
.then(|| code.map_or((&run.style, &run.props), |code| (&code.style, &code.props)))
})
}
pub(super) fn field_text(&self, content: &Content) -> String {
match content {
Content::Date(field) => self
.context
.now
.map_or_else(|| field.stored.clone(), |now| now.write(&field.picture)),
Content::DocProperty(field) if field.name.eq_ignore_ascii_case("LastSavedTime") => {
let picture = field.picture.clone().unwrap_or_else(|| {
format!(
"{} {}",
crate::dates::DATE_PICTURE,
crate::dates::TIME_PICTURE
)
});
self.context
.now
.map_or_else(|| field.stored.clone(), |now| now.write(&picture))
}
Content::DocProperty(field) => {
match (self.context.properties.get(&field.name), &field.picture) {
(Some(Property::Text(text)), None) => text.clone(),
(Some(Property::Date(date)), picture) => decisions::property_date(
&self.context.quirks,
self.context.zone_minutes,
*date,
picture.as_deref(),
)
.unwrap_or_else(|| field.stored.clone()),
(Some(Property::Text(text)), Some(picture)) => {
crate::dates::DateTime::parse_text(text)
.map_or_else(|| field.stored.clone(), |date| date.write(picture))
}
_ => field.stored.clone(),
}
}
Content::StyleRef(field) => self.style_ref_text(field),
Content::PageRef(field) => match &self.context.earlier.bookmarks {
Some(pages) => pages
.get(&field.bookmark)
.cloned()
.unwrap_or_else(|| MISSING_BOOKMARK.to_owned()),
None => field.stored.clone(),
},
Content::NumberRef(field) => self.number_ref_text(field),
Content::If(field) => self.if_text(field),
Content::PageNumber | Content::PageCount => self.page_text(content),
_ => String::new(),
}
}
fn number_ref_text(&self, field: &NumberRef) -> String {
let earlier = &self.context.earlier;
let Some(bookmarks) = earlier
.bookmarks
.as_ref()
.filter(|_| !earlier.stored_number_refs)
else {
return field.stored.clone();
};
if !bookmarks.contains_key(&field.bookmark) {
return MISSING_REFERENCE.to_owned();
}
let Some(kind) = field.kind else {
return field.stored.clone();
};
self.context
.earlier
.bookmark_numbers
.get(&field.bookmark)
.map_or_else(
|| "0".to_owned(),
|number| {
number
.reference(kind, self.number_context.as_ref())
.unwrap_or_else(|| field.stored.clone())
},
)
}
}
pub(crate) fn mark_run_props(
styles: &crate::styles::Styles,
run: &RunProps,
props: &ParaProps,
) -> RunProps {
let mut mark = run.clone();
if let Some(style) = &props.mark_style {
styles.apply_character(&mut mark, style);
}
mark.apply(&props.mark);
mark
}
pub(crate) fn list_label_props(
shaper: &crate::text::Shaper<'_>,
label: &Label,
mark: &RunProps,
right_to_left: bool,
) -> RunProps {
let mut props = RunProps {
underline: None,
rtl: None,
..mark.clone()
};
props.apply(&label.run);
if shaper.names_symbol_font(&props) {
symbol_label_style(&mut props, &label.run);
} else if right_to_left {
props.rtl = Some(true);
}
props
}
fn symbol_label_style(props: &mut RunProps, level: &RunProps) {
if level.bold.is_none() {
props.bold = Some(false);
}
if level.italic.is_none() {
props.italic = Some(false);
}
}
fn label_after_page_breaks(pieces: &mut [Piece], label: usize, breaks: LeadingBreaks) {
let leading = pieces
.get(label..)
.unwrap_or_default()
.iter()
.take_while(|piece| matches!(piece, Piece::PageBreak))
.count();
let before = breaks.before_first_line(leading);
if label > 0
&& before > 0
&& label + leading < pieces.len()
&& let Some(lead) = pieces.get_mut(..label + before)
{
lead.rotate_right(before);
}
}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use f_office_xml::{Document, Limits};
use super::Pending;
#[test]
fn moves_a_list_label_after_the_page_breaks_that_start_its_paragraph() {
use crate::lines::{LeadingBreaks, Piece};
use crate::text::{FaceIndex, Glyph};
let glyph = |ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch));
let moved = |mut pieces: Vec<Piece>, label, breaks| {
super::label_after_page_breaks(&mut pieces, label, breaks);
pieces
};
let label = [glyph('1'), Piece::Tab(None)];
let (text, page) = (glyph('a'), Piece::PageBreak);
let mut pieces = label.to_vec();
pieces.extend([page, page, text]);
let mut all = vec![page, page];
all.extend(label);
all.push(text);
assert_eq!(moved(pieces.clone(), 2, LeadingBreaks::All), all);
let mut first = vec![page];
first.extend(label);
first.extend([page, text]);
assert_eq!(moved(pieces.clone(), 2, LeadingBreaks::First), first);
assert_eq!(moved(pieces.clone(), 2, LeadingBreaks::None), pieces);
for (pieces, label) in [
(vec![label[0], label[1], page], 2),
(vec![label[0], label[1], page, page], 2),
(vec![page, text], 0),
(vec![label[0], label[1], text, page, text], 2),
] {
for breaks in [LeadingBreaks::First, LeadingBreaks::All] {
assert_eq!(moved(pieces.clone(), label, breaks), pieces);
}
}
}
#[test]
fn a_symbol_label_takes_bold_and_italic_from_its_level_only() {
let mark = RunProps {
bold: Some(true),
italic: Some(true),
..RunProps::default()
};
let mut props = mark.clone();
super::symbol_label_style(&mut props, &RunProps::default());
assert_eq!((props.bold, props.italic), (Some(false), Some(false)));
let level = RunProps {
italic: Some(true),
..RunProps::default()
};
let mut props = mark.clone();
props.apply(&level);
super::symbol_label_style(&mut props, &level);
assert_eq!((props.bold, props.italic), (Some(false), Some(true)));
}
#[test]
fn automatic_spacing_is_fixed_where_the_option_and_the_target_say_so() {
use crate::props::HtmlAutoSpacing;
use crate::quirks::FixedAutoSpacing;
let set = crate::styles::Settings {
html_auto_spacing: HtmlAutoSpacing::Fixed,
..crate::styles::Settings::default()
};
let unset = crate::styles::Settings::default();
let quirks = |variant| crate::layout::testing::on_base_with(|p| p.with_variant(variant)).1;
let followed = quirks(FixedAutoSpacing::OptionFollowed);
let ignored = quirks(FixedAutoSpacing::Ignored);
let reading = super::decisions::html_auto_spacing;
assert_eq!(reading(&set, &followed), HtmlAutoSpacing::Fixed);
assert_eq!(reading(&set, &ignored), HtmlAutoSpacing::Html);
assert_eq!(reading(&unset, &followed), HtmlAutoSpacing::Html);
assert_eq!(reading(&unset, &ignored), HtmlAutoSpacing::Html);
}
#[test]
fn automatic_text_takes_the_story_color_before_the_white_of_dark_shading() {
use crate::props::Color;
let colored = |color, (behind, story)| {
let mut props = RunProps {
color,
..RunProps::default()
};
super::automatic_color(&mut props, (behind, story));
props.color
};
let (dark, orange) = (Some([0, 0, 0x80]), Some([0xED, 0x7D, 0x31]));
let rgb = |rgb: Option<[u8; 3]>| rgb.map(Color::Rgb);
assert_eq!(colored(None, (None, orange)), rgb(orange));
assert_eq!(colored(Some(Color::Auto), (dark, orange)), rgb(orange));
assert_eq!(colored(None, (dark, None)), rgb(Some([255; 3])));
assert_eq!(colored(None, (None, None)), None);
let blue = rgb(Some([0, 0, 255]));
assert_eq!(colored(blue, (dark, orange)), blue);
}
use crate::body::{Block, Content, Run, Section, Sections, read_story};
use crate::layout::testing::{Fake, base_context};
use crate::layout::{Layout, SectionLayout};
use crate::lines::Piece;
use crate::ns::{V, W};
use crate::props::{BidiLanguageClass, RunProps};
use crate::reader::PartReader;
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::text::{Shaper, ShaperSettings};
#[test]
fn shares_the_inline_drawing_of_a_paragraph_measured_twice() {
let xml = format!(
r#"<w:hdr xmlns:w="{W}" xmlns:v="{V}"><w:p><w:r><w:pict><v:rect style="width:20pt;height:20pt"><v:textbox><w:txbxContent><w:p><w:r><w:t>a</w:t></w:r></w:p></w:txbxContent></v:textbox></v:rect></w:pict></w:r></w:p></w:hdr>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
let Some(Block::Paragraph(paragraph)) = blocks.first() else {
panic!("no paragraph");
};
let Some(Content::Drawing(drawing)) =
paragraph.runs.first().and_then(|r| r.content.first())
else {
panic!("no inline drawing");
};
assert_eq!(drawing.shape.blocks.len(), 1);
let (styles, settings) = (Styles::default(), Settings::default());
let (theme, fonts) = (Theme::default(), FontTable::default());
let context = base_context(&styles, &settings);
let stories = context.for_stories();
let sections = Sections::one(SectionLayout::plain(&Section::default(), blocks.len()));
let mut layout = Layout::new(
(&context, &stories),
§ions,
Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
);
for _ in 0..2 {
layout.measure(
paragraph,
&RunProps::default(),
None,
&mut super::RunFeatures::default(),
);
}
assert_eq!(layout.output.drawings.len(), 2);
assert!(
layout
.output
.drawings
.iter()
.all(|measured| Rc::ptr_eq(measured, drawing))
);
}
fn glyph_starts(paragraph_xml: &str) -> Vec<(bool, u32)> {
glyph_starts_with(paragraph_xml, crate::profile::Profile::clone)
}
fn glyph_starts_with(
paragraph_xml: &str,
adjust: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
) -> Vec<(bool, u32)> {
let xml = format!(r#"<w:hdr xmlns:w="{W}">{paragraph_xml}</w:hdr>"#);
measured(&xml, &Fake, adjust, |_, pieces| {
pieces
.iter()
.filter_map(|piece| match piece {
Piece::Glyph(glyph) => Some((glyph.starts_run, glyph.place.in_run)),
_ => None,
})
.collect()
})
}
pub(super) fn measured<T>(
xml: &str,
fonts: &dyn crate::Fonts,
change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
read: impl FnOnce(&Layout<'_>, &[Piece]) -> T,
) -> T {
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
let Some(Block::Paragraph(paragraph)) = blocks.first() else {
panic!("no paragraph");
};
let (styles, settings) = (Styles::default(), Settings::default());
let (theme, table) = (Theme::default(), FontTable::default());
let mut context = base_context(&styles, &settings);
(context.device, context.quirks) = crate::layout::testing::on_base_with(change);
let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
let stories = context.for_stories();
let sections = Sections::one(SectionLayout::plain(&Section::default(), blocks.len()));
let mut layout = Layout::new(
(&context, &stories),
§ions,
Shaper::new(fonts, &theme, &table, &shaper),
);
let pieces = layout.measure(
paragraph,
&RunProps::default(),
None,
&mut super::RunFeatures::default(),
);
read(&layout, &pieces)
}
#[test]
fn starts_a_text_object_where_the_run_record_changes() {
let objects = |first: &str, second: &str| {
glyph_starts(&format!(
"<w:p><w:r><w:rPr>{first}</w:rPr><w:t>ab</w:t></w:r><w:r><w:rPr>{second}</w:rPr><w:t>cd</w:t></w:r></w:p>"
))
};
let snap_off = r#"<w:snapToGrid w:val="0"/>"#;
let cut = [(true, 0), (false, 1), (true, 0), (false, 1)];
let joined = [(true, 0), (false, 1), (false, 2), (false, 3)];
assert_eq!(objects("", "<w:noProof/>"), cut);
assert_eq!(objects("", r#"<w:snapToGrid w:val="1"/>"#), cut);
let swapped = (
format!("<w:noProof/>{snap_off}"),
format!("{snap_off}<w:noProof/>"),
);
assert_eq!(objects(&swapped.0, &swapped.1), joined);
assert_eq!(objects("<w:b/>", r#"<w:b w:val="1"/>"#), joined);
assert_eq!(objects("", ""), joined);
}
#[test]
fn starts_a_text_object_at_field_results_and_after_field_ends() {
let field = |code: &str| {
format!(
r#"<w:fldChar w:fldCharType="begin"/><w:instrText xml:space="preserve"> {code} </w:instrText><w:fldChar w:fldCharType="separate"/><w:t>cd</w:t><w:fldChar w:fldCharType="end"/>"#
)
};
let starts = [
(true, 0),
(false, 1),
(true, 0),
(false, 1),
(true, 0),
(false, 1),
];
let stored = field("TITLE");
assert_eq!(
glyph_starts(&format!(
"<w:p><w:r><w:t>ab</w:t>{stored}<w:t>ef</w:t></w:r></w:p>"
)),
starts
);
let date = field(r#"DATE \@ "d""#);
assert_eq!(
glyph_starts(&format!(
"<w:p><w:r><w:t>ab</w:t>{date}<w:t>ef</w:t></w:r></w:p>"
)),
starts
);
assert_eq!(
glyph_starts("<w:p><w:r><w:t>abcdef</w:t></w:r></w:p>"),
[0, 1, 2, 3, 4, 5].map(|count| (count == 0, count))
);
}
#[test]
fn starts_a_text_object_at_control_edges_and_after_removed_text_as_the_quirks_say() {
let control = "<w:p><w:r><w:t>ab</w:t></w:r><w:sdt><w:sdtContent><w:r><w:t>cd</w:t></w:r></w:sdtContent></w:sdt><w:r><w:t>ef</w:t></w:r></w:p>";
let removed = format!(
r#"<w:p><w:r><w:t>ab</w:t></w:r><w:r xmlns:n="{}" n:buffered="1" n:removed="1"><w:t>cd</w:t></w:r></w:p>"#,
crate::ns::NOTE
);
let objects = |count: usize, every: usize| -> Vec<(bool, u32)> {
(0..count)
.map(|at| (at % every == 0, u32::try_from(at % every).unwrap()))
.collect()
};
let at_controls = |value| glyph_starts_with(control, |p| p.with_variant(value));
assert_eq!(
at_controls(crate::quirks::ControlObjects::StartsObject),
objects(6, 2)
);
assert_eq!(
at_controls(crate::quirks::ControlObjects::Joins),
objects(6, 6)
);
let after_removed = |value| glyph_starts_with(&removed, |p| p.with_variant(value));
assert_eq!(
after_removed(crate::quirks::RemovedTextObjects::StartsObject),
objects(4, 2)
);
assert_eq!(
after_removed(crate::quirks::RemovedTextObjects::Joins),
objects(4, 4)
);
}
#[test]
fn starts_a_text_object_at_the_edges_of_a_hyperlink_as_the_quirk_says() {
let paragraph = "<w:p><w:r><w:t>ab</w:t></w:r><w:hyperlink><w:r><w:t>cd</w:t></w:r></w:hyperlink><w:r><w:t>ef</w:t></w:r></w:p>";
let starts = |objects| glyph_starts_with(paragraph, |p| p.with_variant(objects));
assert_eq!(
starts(crate::quirks::HyperlinkObjects::StartsObject),
[
(true, 0),
(false, 1),
(true, 0),
(false, 1),
(true, 0),
(false, 1)
]
);
assert_eq!(
starts(crate::quirks::HyperlinkObjects::Joins),
[0, 1, 2, 3, 4, 5].map(|count| (count == 0, count))
);
}
#[test]
fn ends_the_measured_text_at_a_bookmark_start_as_the_quirk_says() {
let paragraph = r#"<w:p><w:r><w:t>ab</w:t></w:r><w:bookmarkStart w:id="1" w:name="m"/><w:bookmarkEnd w:id="1"/><w:r><w:t>cd</w:t></w:r></w:p>"#;
let starts = |text| glyph_starts_with(paragraph, |p| p.with_variant(text));
assert_eq!(
starts(crate::quirks::BookmarkText::Splits),
[(true, 0), (false, 1), (true, 0), (false, 1)]
);
assert_eq!(
starts(crate::quirks::BookmarkText::Joins),
[0, 1, 2, 3].map(|count| (count == 0, count))
);
}
#[test]
fn keeps_the_class_of_each_run_of_a_joined_text() {
let persian = Some(BidiLanguageClass::OtherRightToLeft);
let run = Run::default();
let mut pending = Pending::new(&RunProps::default(), "ab", (&run, 0));
pending.start_class(None);
pending.join("cd", &run, true);
pending.start_class(persian);
pending.join("ef", &run, true);
pending.start_class(None);
pending.join("g", &run, true);
assert_eq!(pending.text, "abcdefg");
assert_eq!(pending.classes, [(4, persian), (6, None)]);
assert_eq!(pending.starts, [] as [usize; 0]);
}
#[test]
fn reads_a_revision_id_of_zero_as_the_quirk_says() {
let without = Run::default();
let zero = Run {
revisions: [Some(0), Some(0), None],
..Run::default()
};
let other = Run {
revisions: [Some(0x00A1_1111), None, None],
..Run::default()
};
let cases: [(crate::quirks::ZeroRevision, &[usize]); 2] = [
(crate::quirks::ZeroRevision::AnId, &[2, 4]),
(crate::quirks::ZeroRevision::NoId, &[4]),
];
for (zero_revision, starts) in cases {
let mut pending = Pending::new(&RunProps::default(), "ab", (&without, 0))
.reading(super::RevisionReading::with(zero_revision));
pending.join("cd", &zero, true);
pending.join("ef", &other, true);
assert_eq!(pending.starts, starts);
}
}
#[test]
fn keeps_where_each_run_that_starts_a_text_buffer_starts() {
let run = Run::default();
let buffer = Run {
starts_buffer: true,
..Run::default()
};
let mut pending = Pending::new(&RunProps::default(), "ab", (&buffer, 0));
pending.join("cd", &run, true);
pending.join("ef", &buffer, true);
pending.join("g", &buffer, false);
assert_eq!(pending.buffer_starts, [0, 4]);
assert_eq!(pending.starts, [4]);
}
#[test]
fn run_snap_to_grid_controls_character_pitch_independently_of_paragraph_snap() {
let xml = format!(
concat!(
r#"<w:hdr xmlns:w="{W}"><w:p><w:pPr><w:snapToGrid w:val="0"/></w:pPr>"#,
r#"<w:r><w:t>a</w:t></w:r>"#,
r#"<w:r><w:rPr><w:snapToGrid w:val="0"/></w:rPr><w:t>a</w:t></w:r>"#,
r#"<w:r><w:rPr><w:snapToGrid w:val="1"/></w:rPr><w:t>a</w:t></w:r>"#,
r#"</w:p></w:hdr>"#,
),
W = W
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
let Some(Block::Paragraph(paragraph)) = blocks.first() else {
panic!("no paragraph");
};
let (styles, settings) = (Styles::default(), Settings::default());
let (theme, table) = (Theme::default(), FontTable::default());
let context = base_context(&styles, &settings);
let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
let stories = context.for_stories();
let pitch = f_office_units::Length::from_points(2).unwrap();
let section = Section {
char_pitch: Some(pitch),
..Section::default()
};
let sections = Sections::one(SectionLayout::plain(§ion, blocks.len()));
let mut layout = Layout::new(
(&context, &stories),
§ions,
Shaper::new(&Fake, &theme, &table, &shaper),
);
let pieces = layout.measure(
paragraph,
&RunProps::default(),
None,
&mut super::RunFeatures::default(),
);
let advances: Vec<f_office_units::Length> = pieces
.iter()
.filter_map(|piece| match piece {
Piece::Glyph(glyph) => Some(glyph.advance),
_ => None,
})
.collect();
let [a0, a1, a2] = advances.as_slice() else {
panic!("expected 3 glyphs, got {}", advances.len());
};
assert_eq!(a0, a2);
assert_eq!(*a0 - *a1, pitch.div_toward_zero(2));
}
#[test]
fn east_asian_run_splits_after_leading_general_punctuation_space() {
let run = |text: &str, east_asia: bool| {
let ea = if east_asia {
r#" w:eastAsia="Calibri""#
} else {
""
};
let xml = format!(
r#"<w:hdr xmlns:w="{W}"><w:p><w:r><w:rPr><w:rFonts w:ascii="Calibri"{ea}/></w:rPr><w:t xml:space="preserve">{text}</w:t></w:r></w:p></w:hdr>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let blocks = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
let Block::Paragraph(paragraph) = &blocks[0] else {
panic!("no paragraph");
};
let (styles, settings) = (Styles::default(), Settings::default());
let (theme, table) = (Theme::default(), FontTable::default());
let context = base_context(&styles, &settings);
let shaper = ShaperSettings::of(&settings, &context.quirks, context.device.dot_size());
let stories = context.for_stories();
let sections = Sections::one(SectionLayout::plain(&Section::default(), blocks.len()));
let mut layout = Layout::new(
(&context, &stories),
§ions,
Shaper::new(&Fake, &theme, &table, &shaper),
);
layout
.measure(
paragraph,
&RunProps::default(),
None,
&mut super::RunFeatures::default(),
)
.into_iter()
.filter_map(|p| match p {
Piece::Glyph(g) => Some((g.starts_run, g.place.in_run)),
_ => None,
})
.collect::<Vec<_>>()
};
assert_eq!(run("\u{202F}A", true), [(true, 0), (true, 0)]);
assert_eq!(
run("\u{202F}\u{201C}W", true),
[(true, 0), (false, 1), (true, 0)]
);
assert_eq!(
run("\u{202F}\u{00B7}K", true),
[(true, 0), (true, 0), (false, 1)]
);
assert_eq!(run("a\u{202F}b", true), [(true, 0), (false, 1), (false, 2)]);
assert_eq!(
run("\u{202F}\u{201C}W", false),
[(true, 0), (false, 1), (false, 2)]
);
}
}