use f_office_drawingml::color::on_white;
use f_office_paint::{
FillRule, Glyph as PaintGlyph, GlyphRun, Item, Join, Outline, PathItem, Point, Rect, Turn,
};
use f_office_units::Length;
use f_office_units::scale::THOUSANDTHS;
use super::Origin;
use super::aligned_tabs::TabTexts;
use super::rules;
use super::shadow_path::{self, DevicePlace};
use super::shift::{inner_mark_shrink_before, spread_gap};
use crate::character_class::CharacterClass;
use crate::grid::{self, Device, Rounding};
use crate::layout::floating::Size;
use crate::layout::metafile::PictureCut;
use crate::layout::table::after;
use crate::layout::{Layout, TurnedGlyphs, Within, decisions};
use crate::lines::{Line, Piece, Placed, Step, is_space, stretches};
use crate::params;
use crate::props::TabKind;
use crate::text::{
DrawnTextFill, Face, FaceIndex, FontSide, LINE_END_HYPHEN, NON_BREAKING_HYPHEN, TextRelief,
};
#[derive(Clone, Copy)]
pub(super) struct VisualOrder<'a> {
pub(super) rtl: &'a [bool],
pub(super) written: usize,
pub(super) logical: &'a [usize],
pub(super) stretched_bounds: (usize, Option<usize>),
}
impl VisualOrder<'_> {
pub(super) fn ltr(line: &Line) -> Self {
Self {
rtl: &[],
written: line.written(),
logical: &[],
stretched_bounds: (line.first_stretched(), line.last_visible()),
}
}
fn logical_index(self, visual_index: usize) -> usize {
self.logical
.get(visual_index)
.copied()
.unwrap_or(visual_index)
}
fn is_stretched(self, piece: &Piece, visual_index: usize) -> bool {
stretched_space(
piece,
self.logical_index(visual_index),
self.stretched_bounds,
)
}
}
impl Layout<'_> {
fn starts_piece(&self, place: crate::text::TextPlace, from: u32) -> bool {
let numbered = self.section.line_numbers.is_some() && self.column.cell.is_none();
!numbered && place.starts_piece(from, self.settings.mode_rules.text_piece_length())
}
fn starts_text(&self, glyph: &crate::text::Glyph, from: u32) -> bool {
self.device.writer_run_start(
glyph.starts_run || self.starts_piece(glyph.place, from),
glyph.left_out_before,
)
}
pub(super) fn emit_visual(
&mut self,
line: &Line,
origin: Origin,
) -> (DrawnSteps, Option<Length>) {
let stretched_bounds = (line.first_stretched(), line.last_visible());
let visual = crate::layout::bidi::visual(line, origin.right_to_left.is_some());
let order = VisualOrder {
rtl: &visual.right_to_left,
written: visual.written,
logical: &visual.order,
stretched_bounds,
};
let (mut drawn, end) = self.emit(&visual.line, order, origin);
drawn.order = visual.order;
(drawn, end)
}
pub(super) fn emit(
&mut self,
line: &Line,
order: VisualOrder<'_>,
origin: Origin,
) -> (DrawnSteps, Option<Length>) {
let tabs = self.tab_texts(line, order, origin);
let (drawn, end, _) = self.emit_with(line, order, origin, tabs);
(drawn, end)
}
pub(super) fn emit_with(
&mut self,
line: &Line,
order: VisualOrder<'_>,
origin: Origin,
tabs: TabTexts,
) -> (DrawnSteps, Option<Length>, TabTexts) {
let (rtl, written) = (order.rtl, order.written);
self.east_asian_axis = self.east_asian_axis(line);
let spanned = line.written();
let mut run: Option<RunBuilder> = None;
let mut drawn: Option<Drawn> = None;
let mut objects = grid::TextObjects::default();
let mut edge_steps = EdgeGlyphs::of_line(&self.device, (&origin, line, order), tabs);
let (mut steps, mut parts) = (Steps::default(), LigatureParts::default());
let departures = self.width_departures(line, order, origin.space_extra);
let exact = exact_places(line, order, origin, &departures);
let trailing = self.trailing_space(line, (&exact, rtl), &origin);
let stretches = self.right_to_left_stretches(line, &exact, rtl, origin.mark);
let marks = self.object_marks(line, (rtl, &stretches), &origin, &edge_steps);
let mut stretches = stretches.into_iter().peekable();
let mut from_right = RightToLeftPlaces::of(line.placed.len());
self.glyph_places.clear();
let mut before: Option<(bool, bool)> = None;
for (index, (placed, &(x, stretch))) in line.placed.iter().zip(&exact).enumerate() {
steps.piece(
placed,
origin.space_extra != Length::ZERO && order.is_stretched(&placed.piece, index),
);
self.tab(
(placed, x),
origin.baseline,
(&mut edge_steps, &mut steps),
&mut run,
);
self.picture(placed.piece, x, origin);
self.inline_drawing(placed.piece, x, origin);
self.draw_lines_of(placed.piece, x, origin.baseline);
let Some(glyph) = self.drawn_glyph(placed.piece) else {
drawn = None;
objects.restart();
edge_steps.gap(&self.device, (index, placed, &origin), run.as_mut());
continue;
};
edge_steps.after_label = glyph.label;
if parts.take(&glyph, rtl.get(index) == Some(&true), run.as_mut()) {
continue;
}
if run.as_ref().is_some_and(|r| r.face != glyph.face) {
edge_steps.finish(run.as_mut());
self.flush(run.take(), origin.baseline);
drawn = None;
}
let (size, em, stand_in) = self.face_numbers(&glyph);
let off_grid = self.device.snap(size) != size;
let text_start = self.starts_text(&glyph, origin.text_from);
let right_to_left = edge_steps.numbers.is_some() && rtl.get(index) == Some(&true);
let starts = run.is_none() || visual_start(text_start, right_to_left, before);
before = Some((right_to_left, text_start));
marks.tell(index, &mut objects, &mut edge_steps.objects);
if self.starts_object(&mut objects, &mut steps, &glyph, (starts, run.is_none())) {
drawn = None;
}
if let Some(stretch) =
stretches.next_if(|s| s.glyphs.first().is_some_and(|g| g.piece == index))
{
edge_steps.place_stretch(&self.device, &stretch, &mut from_right);
}
let previous = drawn.filter(|_| !stand_in || !off_grid);
let stepped = edge_steps.numbers.is_some() && from_right.place(index).is_none();
let pdf_steps = drawn_x(&self.device, previous, (x, placed.advance), (size, em));
if from_right.place(index).is_none() {
edge_steps.tell(self.device_step(&glyph, size), index);
}
edge_steps.last_glyph = steps.trailing(&glyph, index, trailing);
edge_steps.nominal_steps = self.steps_at_nominal_size(&glyph);
let at = edge_steps
.place(
&self.device,
(x, placed.advance, size, stretch),
(
glyph.ch,
glyph.side,
starts,
glyph.written,
self.steps_extra(&glyph),
),
(index, from_right.place(index), marks.is_off_baseline(index)),
run.as_mut(),
)
.unwrap_or(pdf_steps.at);
let records = edge_steps.records(stepped, from_right.take_check(index));
drawn = Some(Drawn { at, ..pdf_steps });
if stepped {
steps.placed(edge_steps.edge.started(), glyph.ch.is_whitespace());
}
steps.glyph(&glyph, (x, at), records);
let builder = run.get_or_insert_with(|| RunBuilder::new(glyph.face));
edge_steps.after_written(index >= written, at);
let glyph_of_piece = (glyph.ch, glyph.id, Some(index));
builder.push(glyph_of_piece, at, placed, index >= spanned);
builder.shift_last(self.placement(&glyph, (placed.advance, size), right_to_left));
parts.join_to(builder);
}
let closed = self.close_line(line, &exact, run, (steps, edge_steps), origin, written);
self.east_asian_axis = None;
closed
}
fn close_line(
&mut self,
line: &Line,
exact: &[(Length, Length)],
mut run: Option<RunBuilder>,
(mut steps, mut edge_steps): (Steps, EdgeGlyphs),
origin: Origin,
written: usize,
) -> (DrawnSteps, Option<Length>, TabTexts) {
edge_steps.finish(run.as_mut());
self.flush(run, origin.baseline);
edge_steps.tabs.close(&self.device, &edge_steps.edge);
let end = edge_steps.end(&self.device, written_end(line, exact, (origin.x, written)));
steps.drawn.edges = piece_edges(line, exact, std::mem::take(&mut self.glyph_places));
(steps.drawn, end, edge_steps.tabs)
}
fn face_numbers(&self, glyph: &crate::text::Glyph) -> (Length, i64, bool) {
self.shaper
.faces()
.get(glyph.face)
.map_or((Length::ZERO, 1, false), |face| {
(
face.size,
i64::from(face.metrics.units_per_em),
face.standing.font,
)
})
}
fn placement(
&self,
glyph: &crate::text::Glyph,
(advance, size): (Length, Length),
right_to_left: bool,
) -> (Length, Length) {
let placed = grid::PlacedGlyph {
right_to_left,
advance,
own: self.shaper.own_advance(glyph).unwrap_or(Length::ZERO),
size,
};
self.device.placement(glyph.offset, placed)
}
fn steps_at_nominal_size(&self, glyph: &crate::text::Glyph) -> bool {
let scale = self
.shaper
.faces()
.get(glyph.face)
.and_then(|face| face.scale);
decisions::nominal_steps(&self.context.quirks, scale)
.is_some_and(|percent| percent > 0 && percent != f_office_units::scale::PERCENT)
}
fn steps_extra(&self, glyph: &crate::text::Glyph) -> Length {
glyph.spacing + self.shaper.kerning_on_its_own(glyph) + glyph.auto_space
}
pub(super) fn alone_width(&self, glyphs: &[crate::text::Glyph]) -> Length {
let bias = match self.device.advances() {
crate::grid::Advances::RightEdge { bias, .. } => bias,
crate::grid::Advances::PdfSteps => Length::ZERO,
};
glyphs.iter().fold(Length::ZERO, |width, glyph| {
let (size, _, _) = self.face_numbers(glyph);
let step = self.device_step(glyph, size);
let bias = if step.without_bias {
Length::ZERO
} else {
bias
};
let measured = step.measured.map(|(dots, _)| dots);
width + grid::EdgeSteps::alone_step(&self.device, (size, glyph.advance), measured, bias)
})
}
fn device_step(&self, glyph: &crate::text::Glyph, size: Length) -> DeviceStep {
let per_em = self.device.count(size, Rounding::HalfUp);
let measured = self
.shaper
.device_width(
glyph.face,
self.shaper.width_glyph(glyph),
(size.units(), per_em),
)
.map(|(dots, advance)| (dots, Length::from_units(advance)));
let counted_extra = self.shaper.bold_counted_extra(glyph);
DeviceStep {
size,
measured,
without_bias: self.shaper.steps_without_bias(glyph.face),
rounding: self.shaper.advance_rounding(glyph),
spacing: glyph.spacing,
counted_extra,
short_ease: if counted_extra.is_some() {
self.device.dots(1)
} else {
Length::ZERO
},
}
}
fn width_departures(&self, line: &Line, order: VisualOrder<'_>, each: Length) -> Vec<Length> {
if !self.settings.mode_rules.shares_stretched_spaces_by_quirk() {
return Vec::new();
}
decisions::width_first_share(&self.context.quirks, || width_departures(line, order, each))
.unwrap_or_default()
}
fn trailing_space(
&self,
line: &Line,
(exact, rtl): (&[(Length, Length)], &[bool]),
origin: &Origin,
) -> Option<(usize, TrailingSpace)> {
let justified = origin.space_extra != Length::ZERO && origin.right_to_left.is_none();
let index = self
.device
.last_glyph_to_move(line.last_visible())
.filter(|_| justified)?;
let in_rtl = |at: usize| rtl.get(at) == Some(&true);
let last = line
.placed
.get(index)
.filter(|_| !in_rtl(index) && !in_rtl(index + 1))?;
self.drawn_glyph(last.piece)
.filter(|glyph| glyph.spacing == Length::ZERO)?;
let next = line.placed.get(index + 1).filter(|p| is_space(&p.piece))?;
let space = self.drawn_glyph(next.piece).filter(|space| !space.part)?;
let &(x, _) = exact.get(index + 1)?;
let step = self.device_step(&space, self.size_of(&space));
Some((
index,
TrailingSpace {
x,
end: x + origin.space_rest,
edge: origin.edge,
advance: next.advance,
spacing: space.spacing,
step,
},
))
}
fn size_of(&self, glyph: &crate::text::Glyph) -> Length {
self.shaper
.faces()
.get(glyph.face)
.map_or(Length::ZERO, |face| face.size)
}
fn right_to_left_object_marks(
&self,
line: &Line,
stretches: &[Stretch],
from: u32,
) -> RtlObjectMarks {
let mut marks = RtlObjectMarks::of(line.placed.len());
for stretch in stretches {
let drawn: Vec<Option<crate::text::Glyph>> = stretch
.glyphs
.iter()
.map(|g| {
line.placed
.get(g.piece)
.and_then(|placed| self.drawn_glyph(placed.piece))
})
.collect();
let glyphs: Vec<(char, FontSide, bool)> = drawn
.iter()
.enumerate()
.map(|(at, glyph)| {
let Some(glyph) = glyph else {
return ('\0', FontSide::Open, false);
};
let face_change = drawn
.get(at + 1)
.and_then(|next| next.as_ref())
.is_some_and(|next| next.face != glyph.face);
(
self.device.writer_char(glyph.ch),
self.device.writer_side(glyph.side),
face_change || self.starts_text(glyph, from),
)
})
.collect();
let starts = self.device.right_to_left_object_starts(&glyphs);
if !starts.reading_order {
continue;
}
for ((g, full), after_spaces) in stretch
.glyphs
.iter()
.zip(starts.full)
.zip(starts.after_spaces)
{
if let Some(mark) = marks.reading_order.get_mut(g.piece) {
*mark = true;
}
if full && let Some(mark) = marks.full.get_mut(g.piece) {
*mark = true;
}
if after_spaces && let Some(mark) = marks.after_spaces.get_mut(g.piece) {
*mark = true;
}
}
}
marks
}
fn object_marks(
&self,
line: &Line,
(rtl, stretches): (&[bool], &[Stretch]),
origin: &Origin,
edge_steps: &EdgeGlyphs,
) -> ObjectMarks {
let rtl_marks = self.right_to_left_object_marks(line, stretches, origin.text_from);
let steps = edge_steps.numbers.is_some();
let pieces: Vec<ObjectPiece> = (line.placed.iter().enumerate())
.map(|(index, placed)| {
let glyph = self.drawn_glyph(placed.piece);
match (placed.piece, glyph) {
(Piece::Tab(Some(_)) | Piece::PositionTab(Some(_), _), _) => ObjectPiece::Tab,
(_, None) => ObjectPiece::Gap,
(_, Some(glyph)) => {
let in_rtl = rtl.get(index) == Some(&true);
let right_to_left = steps && in_rtl;
let (size, _, _) = self.face_numbers(&glyph);
let facts = ObjectGlyph {
face: glyph.face,
ch: self.device.writer_char(glyph.ch),
side: self.device.writer_side(glyph.side),
right_to_left,
text_start: self.starts_text(&glyph, origin.text_from),
off: (self.device).object_per_glyph(
glyph.offset.1,
size,
right_to_left,
),
};
if glyph.part {
ObjectPiece::Part {
in_rtl,
glyph: facts,
}
} else {
ObjectPiece::Glyph(facts)
}
}
}
})
.collect();
let off_baseline = off_baseline_marks(&pieces, &rtl_marks);
ObjectMarks {
rtl: rtl_marks,
off_baseline,
}
}
fn right_to_left_stretches(
&self,
line: &Line,
exact: &[(Length, Length)],
rtl: &[bool],
mark: bool,
) -> Vec<Stretch> {
let mut stretches: Vec<Stretch> = Vec::new();
let mut open = false;
let pieces = line.placed.iter().zip(exact).zip(rtl).enumerate();
for (index, ((placed, &(x, stretch)), &right_to_left)) in pieces {
let glyph = self.drawn_glyph(placed.piece);
let advance = placed.advance + stretch;
let gap = glyph.is_none() && placed.advance != Length::ZERO;
if !right_to_left || gap {
if let Some(last) = stretches.last_mut().filter(|_| open) {
last.next = glyph.filter(|g| !g.part).map_or(After::Other, |g| {
After::Glyph(advance, self.device_step(&g, self.size_of(&g)))
});
}
open = false;
continue;
}
let Some(glyph) = glyph.filter(|glyph| !glyph.part) else {
continue;
};
let glyph = StretchGlyph {
piece: index,
x,
advance,
stretch,
device: self.device_step(&glyph, self.size_of(&glyph)),
};
match stretches.last_mut() {
Some(last) if open => last.glyphs.push(glyph),
_ => stretches.push(Stretch {
glyphs: vec![glyph],
next: if mark { After::Mark } else { After::Other },
}),
}
open = true;
}
stretches
}
fn starts_object(
&self,
objects: &mut crate::grid::TextObjects,
steps: &mut Steps,
glyph: &crate::text::Glyph,
(starts, glyph_run): (bool, bool),
) -> bool {
let started = objects.starts(
self.device.writer_char(glyph.ch),
self.device.writer_side(glyph.side),
starts,
);
if started {
steps.object_started(objects.reason(), glyph_run, glyph);
}
started
}
fn drawn_glyph(&self, piece: Piece) -> Option<crate::text::Glyph> {
let Piece::Glyph(glyph) = piece else {
return None;
};
let phantom = self
.shaper
.faces()
.get(glyph.face)
.is_some_and(|face| face.math.phantom);
(!phantom).then_some(glyph)
}
fn picture(&mut self, piece: Piece, x: Length, origin: Origin) {
let Piece::Object {
width,
height,
raised,
picture: Some(index),
..
} = piece
else {
return;
};
let Some(picture) = self.output.pictures.get(index).cloned() else {
return;
};
let drop = if picture.drops {
origin.drop
} else {
Length::ZERO
};
let top = origin.unrounded_baseline + drop - height - raised;
let exact_x = x + origin.grid_shift;
let upright = match self.column.within {
Within::TurnedFrame(_, turn, _) => {
decisions::upright_picture(&self.context.quirks, turn)
}
Within::Page | Within::Cell(_) => None,
};
let line_band = self.line_band;
let story = self.story.as_ref().map(|story| &story.kind);
let band = decisions::inline_picture_cut(&self.context.quirks, || match story {
Some(
crate::layout::StoryKind::TextBox { inside, .. }
| crate::layout::StoryKind::Frame { inside },
) => inside.map(PictureCut::Box),
_ => line_band.map(|(top, bottom)| PictureCut::Line(top, bottom)),
});
let items = match upright {
Some(turn) => self.upright_picture(&picture, (exact_x, top, width, height), turn),
None if picture.lies_on_device_dots() => {
let bottom = origin.baseline + drop - raised;
self.picture_on_dots(&picture, (x, bottom), (top, band))
}
None => self.picture_items_in(&picture, exact_x, top, band),
};
self.items.extend(items);
}
fn picture_on_dots(
&mut self,
picture: &crate::picture::Picture,
(x, bottom): (Length, Length),
(exact_top, band): (Length, Option<PictureCut>),
) -> Vec<Item> {
let device = self.device;
let (left, bottom) = (device.snap(x), device.snap(bottom));
let (right, top) = (
left + device.snap(picture.width),
bottom - device.snap(picture.height),
);
let [left, top, right, bottom] =
[left, top, right, bottom].map(|edge| edge.nearest_whole(Length::UNITS_PER_TWIP));
let mut drawn = picture.clone();
(drawn.width, drawn.height) = (right - left, bottom - top);
let exact_top = exact_top + picture.top;
let exact_bottom = exact_top + picture.height;
let band = band.map(|band| band.moved((top - exact_top, bottom - exact_bottom)));
self.picture_items_in(&drawn, left - picture.left, top - picture.top, band)
}
fn upright_picture(
&mut self,
picture: &crate::picture::Picture,
(x, top, width, height): (Length, Length, Length, Length),
turn: f_office_paint::Turn,
) -> Vec<Item> {
let half = |length: Length| length.div_toward_zero(2);
let along = x + half(width);
let along = if turn == crate::layout::table::UP {
self.column.left + self.column.left + self.column.width - along
} else {
along
};
self.picture_items(
picture,
along - half(height),
top + half(height) - half(width),
)
}
fn inline_drawing(&mut self, piece: Piece, x: Length, origin: Origin) {
let Piece::Object {
height,
raised,
drawing: Some(index),
..
} = piece
else {
return;
};
let Some(drawing) = self.output.drawing(index).cloned() else {
return;
};
let drop = if drawing.drops {
origin.drop
} else {
Length::ZERO
};
let size = Size::of(&drawing.shape);
let (left, top, size) = if let Some((bottom, room)) = origin
.anchor_bottom
.filter(|_| drawing.anchor_locked)
.and_then(|bottom| self.anchor_room(index).map(|room| (bottom, room)))
{
(
x + room.above,
bottom.nearest_whole(Length::UNITS_PER_TWIP) - room.below,
size.with_height(room.height),
)
} else {
(
x + drawing.left,
origin.baseline + drop - height - raised + drawing.top,
size,
)
};
let items = self.draw_sized((&drawing.shape, size), left, top);
self.items.extend(items);
}
fn tab(
&mut self,
(placed, x): (&Placed, Length),
baseline: Length,
(edge_steps, steps): (&mut EdgeGlyphs, &mut Steps),
run: &mut Option<RunBuilder>,
) {
let (Piece::Tab(Some(face)) | Piece::PositionTab(Some(face), _)) = placed.piece else {
return;
};
let span = (x, placed.advance);
if let Some(ch) = placed.leader {
edge_steps.finish(run.as_mut());
self.flush(run.take(), baseline);
self.leader(face, ch, span, (baseline, steps));
}
edge_steps.finish(run.as_mut());
self.flush(run.take(), baseline);
self.tab_marks(face, span, baseline);
}
fn leader(
&mut self,
face: FaceIndex,
ch: char,
(x, width): (Length, Length),
(baseline, steps): (Length, &mut Steps),
) {
let Some(glyph) = self.shaper.glyph(face, ch) else {
return;
};
let step = self.device.leader_step(glyph.advance);
if step <= Length::ZERO {
return;
}
let edge = Length::ZERO;
let first = ((x - edge + step).units() - 1).div_euclid(step.units());
let last = (x + width - edge).units().div_euclid(step.units());
let count = (last - first).max(0);
let start = edge + step * first;
let (size, em, stand_in) =
self.shaper
.faces()
.get(face)
.map_or((Length::ZERO, 1, false), |face| {
(
face.size,
i64::from(face.metrics.units_per_em),
face.standing.font,
)
});
let exact_places = stand_in && self.device.snap(size) != size;
let mut builder = RunBuilder::new(face);
let mut drawn: Option<Drawn> = None;
let mut edge_steps = EdgeGlyphs::new(&self.device);
for (index, exact) in (0..count).map(|i| start + step * i).enumerate() {
let placed = Placed {
piece: Piece::Glyph(glyph),
x: Length::ZERO,
advance: glyph.advance,
leader: None,
tab: None,
};
let starts = index % params::LEADER_OBJECT_GLYPHS == 0;
let previous = drawn.filter(|_| !starts && !exact_places);
let pdf_steps = drawn_x(&self.device, previous, (exact, step), (size, em));
let at = edge_steps
.place_leader(
&self.device,
(exact, step, size),
(starts, glyph.written),
Some(&mut builder),
)
.unwrap_or(pdf_steps.at);
drawn = Some(Drawn { at, ..pdf_steps });
steps.leader(exact, at);
builder.push((ch, glyph.id, None), at, &placed, false);
builder.shift_last(glyph.offset);
}
edge_steps.finish(Some(&mut builder));
self.flush(Some(builder), baseline);
}
fn flush(&mut self, run: Option<RunBuilder>, baseline: Length) {
let Some(mut run) = run else {
return;
};
let Some(face) = self.shaper.faces().get(run.face).copied() else {
return;
};
let baseline = baseline
+ self
.centered_middle
.map_or(Length::ZERO, |middle| self.device.snap(middle.shift(&face)));
if let (Some(color), Some((start, end))) = (face.background, run.span()) {
self.items.push(Item::Rect(Rect {
x: start,
y: baseline - face.ascent(),
width: end - start,
height: face.ascent() + face.descent(),
color,
}));
}
let span = run.span().unwrap_or((Length::ZERO, Length::ZERO));
let lines = rules::run_lines(&self.device, &face, (span, &run.words), baseline);
self.items.extend(lines.into_iter().map(Item::Rect));
let needs_outlines = face.shadow.is_some()
|| face.glow.is_some()
|| face.reflection.is_some()
|| face.relief.is_some()
|| matches!(
face.text_fill,
DrawnTextFill::White | DrawnTextFill::Gradient(_) | DrawnTextFill::Translucent(_)
);
let outline_inputs = needs_outlines.then(|| {
let places = run.device_places(&self.device, &face, baseline);
let size = self.device.snap(face.size);
let turn = (self.device).glyph_turn(
size,
&face.metrics,
face.scale,
face.standing.synthetic_italic,
);
(places, size, turn)
});
if let Some((places, size, turn)) = outline_inputs.as_ref() {
self.emit_run_effects(&face, (*size, *turn), baseline, places);
}
let (filled, emit_glyphs) =
self.emit_special_text_fill(&face, span, baseline, outline_inputs.as_ref());
let pieces = std::mem::take(&mut run.pieces);
let mut glyphs = run.finish(&self.device, &face, baseline, filled);
let places = pieces.into_iter().zip(&glyphs.glyphs);
self.glyph_places
.extend(places.filter_map(|(piece, glyph)| piece.map(|piece| (piece, glyph.x))));
apply_relief_shift(&mut glyphs, &face);
if emit_glyphs {
match (self.east_asian_axis, self.column.within) {
(Some(axis), Within::TurnedFrame(_, turn, _)) => self.items.extend(
upright_east_asian(glyphs, (face.win_top(), axis), turn)
.into_iter()
.map(Item::Glyphs),
),
_ => self.items.push(Item::Glyphs(glyphs)),
}
}
}
fn emit_run_effects(
&mut self,
face: &Face,
(size, turn): (Length, Option<Turn>),
baseline: Length,
places: &[DevicePlace],
) {
let glyphs = (self.shaper.fonts(), face, size, turn);
if let Some(reflection) = face.reflection {
let y = baseline - self.device.shift_dots(face.rise);
self.items
.extend(shadow_path::reflection_item(glyphs, reflection, y, places));
}
match (face.shadow, face.glow) {
(Some(shadow), Some(glow)) => {
self.items
.extend(shadow_path::shadow_with_glow(glyphs, shadow, glow, places));
self.items
.extend(shadow_path::glow_item(glyphs, glow, places));
}
(Some(shadow), None) => {
self.items.extend(shadow_path::item(glyphs, shadow, places));
}
(None, Some(glow)) => {
self.items
.extend(shadow_path::glow_item(glyphs, glow, places));
}
(None, None) => {}
}
if let Some(relief) = face.relief {
self.emit_text_relief(glyphs, relief, places);
}
}
fn emit_text_relief(
&mut self,
glyphs: (&dyn crate::Fonts, &Face, Length, Option<Turn>),
relief: TextRelief,
places: &[DevicePlace],
) {
let offset = crate::text::legacy_offset(glyphs.1.size);
let two = offset * 2;
let gray = params::LEGACY_TEXT_RELIEF_GRAY;
let relief_gray = f_office_paint::Rgb {
r: gray,
g: gray,
b: gray,
};
let passes = match relief {
TextRelief::Emboss => [
((Length::ZERO, Length::ZERO), relief_gray),
((-two, -two), f_office_paint::Rgb::BLACK),
],
TextRelief::Imprint => [
((two, two), f_office_paint::Rgb::BLACK),
((Length::ZERO, Length::ZERO), relief_gray),
],
};
for (shift, color) in passes {
let commands = shadow_path::glyph_outlines(glyphs, shift, places);
if !commands.is_empty() {
self.items.push(Item::Path(PathItem {
commands,
color,
fill_rule: FillRule::NonZero,
}));
}
}
}
fn emit_special_text_fill(
&mut self,
face: &Face,
span: (Length, Length),
baseline: Length,
outline_inputs: Option<&(Vec<DevicePlace>, Length, Option<Turn>)>,
) -> (bool, bool) {
match face.text_fill {
DrawnTextFill::Solid => (true, true),
DrawnTextFill::None => {
let has_stroke = face.outline.is_some() || face.standing.synthetic_bold;
(false, has_stroke)
}
DrawnTextFill::White => {
if let Some((places, size, turn)) = outline_inputs {
let commands = shadow_path::glyph_outlines(
(self.shaper.fonts(), face, *size, *turn),
(Length::ZERO, Length::ZERO),
places,
);
if !commands.is_empty() {
self.items.push(Item::Path(PathItem {
commands,
color: f_office_paint::Rgb::WHITE,
fill_rule: FillRule::NonZero,
}));
}
}
(false, face.outline.is_some())
}
DrawnTextFill::Translucent(opacity) => {
if let Some((places, size, turn)) = outline_inputs {
let commands = shadow_path::glyph_outlines(
(self.shaper.fonts(), face, *size, *turn),
(Length::ZERO, Length::ZERO),
places,
);
if !commands.is_empty() {
self.items.push(Item::Path(PathItem {
commands,
color: on_white(face.color, opacity),
fill_rule: FillRule::NonZero,
}));
}
}
(false, face.outline.is_some())
}
DrawnTextFill::Gradient(index) => {
let drawn = outline_inputs.and_then(|(places, size, turn)| {
let gradient = self.shaper.text_gradient(index)?;
let commands = shadow_path::glyph_outlines(
(self.shaper.fonts(), face, *size, *turn),
(Length::ZERO, Length::ZERO),
places,
);
if commands.is_empty() {
return None;
}
let corners = (
Point {
x: span.0,
y: baseline - face.ascent(),
},
Point {
x: span.1,
y: baseline + face.descent(),
},
);
gradient.fill_path(
commands,
FillRule::EvenOdd,
corners,
&self.shaper.theme().shapes.colors,
)
});
if let Some(item) = drawn {
self.items.push(Item::Gradient(item));
(false, true)
} else {
(true, true)
}
}
}
}
fn east_asian_axis(&self, line: &Line) -> Option<Length> {
let Within::TurnedFrame(_, _, TurnedGlyphs::EastAsianUpright) = self.column.within else {
return None;
};
let faces = line.placed.iter().filter_map(|placed| match placed.piece {
Piece::Glyph(glyph) => self.shaper.faces().get(glyph.face),
_ => None,
});
let (top, bottom) = faces.fold((Length::ZERO, Length::ZERO), |(top, bottom), face| {
let descent = face.scale(i64::from(face.metrics.descent));
(top.max(face.win_top()), bottom.max(descent))
});
Some((top - bottom).div_toward_zero(2))
}
}
fn apply_relief_shift(glyphs: &mut GlyphRun, face: &Face) {
let Some(relief) = face.relief else {
return;
};
let offset = crate::text::legacy_offset(face.size);
let delta = match relief {
TextRelief::Emboss => -offset,
TextRelief::Imprint => offset,
};
for glyph in &mut glyphs.glyphs {
glyph.x += delta;
glyph.y += delta;
}
}
fn upright_east_asian(run: GlyphRun, (top, axis): (Length, Length), turn: Turn) -> Vec<GlyphRun> {
let upright = |glyph: &PaintGlyph| {
run.glyph_text(glyph)
.and_then(|text| text.chars().next())
.is_some_and(|ch| CharacterClass::EastAsianFont.contains(ch))
};
if !run.glyphs.iter().any(upright) {
return vec![run];
}
let back = Turn {
xx: turn.xx,
yx: turn.xy,
xy: turn.yx,
yy: turn.yy,
};
let shift = (top, run.size.div_toward_zero(2) - axis);
let stood = Some(run.turn.map_or(back, |own| after(back, own)));
let template = GlyphRun {
text: String::new(),
glyphs: Vec::new(),
..run.clone()
};
run.glyphs
.chunk_by(|a, b| upright(a) == upright(b))
.map(|row| {
let start = row.iter().map(|g| g.text_start).min().unwrap_or(0);
let end = row.iter().map(|g| g.text_end).max().unwrap_or(start);
let text = usize::try_from(start)
.ok()
.zip(usize::try_from(end).ok())
.and_then(|(start, end)| run.text.get(start..end))
.unwrap_or_default()
.to_owned();
let stands = row.first().is_some_and(upright);
let glyphs = row
.iter()
.map(|glyph| PaintGlyph {
x: glyph.x + if stands { shift.0 } else { Length::ZERO },
y: glyph.y + if stands { shift.1 } else { Length::ZERO },
text_start: glyph.text_start - start,
text_end: glyph.text_end - start,
..*glyph
})
.collect();
GlyphRun {
text,
glyphs,
turn: if stands { stood } else { run.turn },
..template.clone()
}
})
.collect()
}
const GAP_ORDER: &[Step] = &[Step::Space, Step::Stretched, Step::Object, Step::Tab];
fn piece_edges(
line: &Line,
exact: &[(Length, Length)],
drawn: Vec<(usize, Length)>,
) -> Vec<(Length, Length)> {
let mut lefts: Vec<Length> = exact.iter().map(|&(x, _)| x).collect();
for (index, x) in drawn {
if let Some(left) = lefts.get_mut(index) {
*left = x;
}
}
let last = line
.placed
.last()
.zip(exact.last())
.map(|(placed, &(x, stretch))| x + placed.advance + stretch);
lefts
.iter()
.enumerate()
.map(|(index, &left)| {
let right = lefts.get(index + 1).copied().or(last).unwrap_or(left);
(left, right.max(left))
})
.collect()
}
#[derive(Clone, Debug, Default)]
pub(in crate::layout) struct DrawnSteps {
pub(in crate::layout) steps: Vec<Step>,
pub(in crate::layout) glyphs: Vec<crate::layout::DrawnGlyph>,
pub(in crate::layout) edges: Vec<(Length, Length)>,
pub(in crate::layout) order: Vec<usize>,
}
#[derive(Clone, Debug, Default)]
struct Steps {
drawn: DrawnSteps,
spaces: u32,
started: crate::layout::StepsStart,
object_start: Option<crate::grid::ObjectStart>,
gap: Option<Step>,
previous: Option<bool>,
}
impl Steps {
fn piece(&mut self, placed: &Placed, stretches: bool) {
let piece = placed.piece;
let step = match piece {
Piece::Tab(_) | Piece::PositionTab(..) => match placed.tab {
Some(TabKind::Center | TabKind::Right | TabKind::Decimal) => Step::AlignedTab,
Some(TabKind::Left) | None => Step::Tab,
},
Piece::Object { .. } => Step::Object,
Piece::Glyph(glyph) if glyph.ch.is_whitespace() => {
self.spaces += 1;
if stretches && crate::lines::stretches(&piece) {
Step::Stretched
} else {
Step::Space
}
}
_ => return,
};
let rank = |step: Step| {
let step = if step == Step::AlignedTab {
Step::Tab
} else {
step
};
GAP_ORDER.iter().position(|s| *s == step)
};
let tab = rank(step) == rank(Step::Tab);
if self.gap.is_none_or(|gap| tab || rank(step) > rank(gap)) {
self.gap = Some(step);
}
}
fn object_started(
&mut self,
reason: Option<crate::grid::ObjectStart>,
glyph_run: bool,
glyph: &crate::text::Glyph,
) {
use crate::grid::ObjectStart;
let reason = match reason {
Some(ObjectStart::Run) if glyph.place.starts_buffer => Some(ObjectStart::Buffer),
Some(ObjectStart::Run) if glyph_run => Some(ObjectStart::GlyphRun),
Some(ObjectStart::Run) if !glyph.starts_run => Some(ObjectStart::Piece),
reason => reason,
};
self.object_start = self.object_start.or(reason);
}
fn placed(&mut self, started: bool, space: bool) {
if started {
self.started = if space {
crate::layout::StepsStart::Space(self.spaces)
} else {
crate::layout::StepsStart::Glyph
};
}
}
fn leader(&mut self, x: Length, place: Length) {
self.drawn.steps.push(Step::Leader);
self.drawn.glyphs.push(crate::layout::DrawnGlyph {
spacing: Length::ZERO,
x,
place,
spaces: 0,
started: crate::layout::StepsStart::Stepped,
checked: None,
object_start: None,
start_place: None,
});
}
fn trailing(
&self,
glyph: &crate::text::Glyph,
index: usize,
trailing: Option<(usize, TrailingSpace)>,
) -> Option<LastGlyph> {
let (_, space) = trailing.filter(|&(at, _)| at == index)?;
match self.next_step(glyph) {
Step::Glyph => Some(LastGlyph::AfterGlyph(space)),
Step::Stretched => Some(LastGlyph::AfterStretched),
_ => None,
}
}
fn next_step(&self, glyph: &crate::text::Glyph) -> Step {
match (self.previous, self.gap) {
(None, _) if glyph.label => Step::Label,
(None, Some(tab @ (Step::Tab | Step::AlignedTab))) => tab,
(None, _) => Step::Start,
(Some(true), _) if !glyph.label => Step::AfterLabel,
(Some(_), gap) => gap.unwrap_or(Step::Glyph),
}
}
fn glyph(
&mut self,
glyph: &crate::text::Glyph,
(x, place): (Length, Length),
(checked, start_place): (Option<crate::grid::EdgeCheck>, Option<Length>),
) {
if glyph.ch.is_whitespace() {
return;
}
let step = self.next_step(glyph);
self.gap = None;
self.drawn.steps.push(step);
self.drawn.glyphs.push(crate::layout::DrawnGlyph {
spacing: glyph.spacing,
x,
place,
spaces: std::mem::take(&mut self.spaces),
started: std::mem::take(&mut self.started),
object_start: self.object_start.take(),
checked,
start_place,
});
self.previous = Some(glyph.label);
}
}
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct Drawn {
pub(in crate::layout) exact: Length,
pub(in crate::layout) at: Length,
pub(in crate::layout) advance: Length,
pub(in crate::layout) spacing: Option<i64>,
}
pub(in crate::layout) fn drawn_x(
device: &Device,
previous: Option<Drawn>,
(x, advance): (Length, Length),
(size, units_per_em): (Length, i64),
) -> Drawn {
let drawn = device.snap(size);
let steps = params::PDF_ADVANCE_STEPS;
let per_step = steps / THOUSANDTHS;
let em = units_per_em.max(1);
let units =
|advance: Length| f_office_units::div_round(advance.units() * em, size.units().max(1));
let width =
|advance: Length| f_office_units::div_round(units(advance) * THOUSANDTHS, em) * per_step;
let at = |at, spacing| Drawn {
exact: x,
at,
advance,
spacing,
};
let Some(p) = previous else {
return at(x, None);
};
let kern = x - p.exact - p.advance;
if drawn == size {
let tenths = f_office_units::div_round(p.advance.units() * steps, size.units());
return at(p.at + (size * tenths).div_round(steps) + kern, None);
}
let excess = f_office_units::div_round(
(units(p.advance) * size.units() + kern.units() * em) * steps,
em * drawn.units().max(1),
) - width(p.advance);
let spacing = p.spacing.unwrap_or(excess);
let ideal = spacing - excess;
let correction = ideal.signum() * f_office_units::div_round(ideal.abs(), per_step) * per_step;
let step = width(p.advance) + spacing - correction;
at(p.at + (drawn * step).div_round(steps), Some(spacing))
}
fn note_mark_starts(line: &Line) -> Vec<bool> {
let glyph_at = |k: usize| match line.placed.get(k) {
Some(Placed {
piece: Piece::Glyph(glyph),
..
}) => Some(*glyph),
_ => None,
};
let mut starts = vec![false; line.placed.len()];
for (index, placed) in line.placed.iter().enumerate() {
if !matches!(placed.piece, Piece::Note(_)) {
continue;
}
let Some(last) = index.checked_sub(1).filter(|&k| glyph_at(k).is_some()) else {
continue;
};
let face = glyph_at(last).map(|glyph| glyph.face);
let mut first = last;
while let Some(before) = first.checked_sub(1) {
if glyph_at(before).map(|glyph| glyph.face) != face {
break;
}
first = before;
}
if let Some(start) = starts.get_mut(first) {
*start = true;
}
}
starts
}
#[derive(Default)]
struct LigatureParts(Vec<char>);
impl LigatureParts {
fn take(
&mut self,
glyph: &crate::text::Glyph,
right_to_left: bool,
run: Option<&mut RunBuilder>,
) -> bool {
if !glyph.part {
return false;
}
if right_to_left {
self.0.push(glyph.ch);
return true;
}
run.map(|builder| builder.join(glyph.ch)).is_some()
}
fn join_to(&mut self, builder: &mut RunBuilder) {
for ch in self.0.drain(..).rev() {
builder.join(ch);
}
}
}
struct RunBuilder {
face: FaceIndex,
text: String,
glyphs: Vec<PaintGlyph>,
device_xs: Vec<Length>,
rights: Vec<Length>,
extent: Option<(Length, Length)>,
words: Vec<(Length, Length)>,
in_word: bool,
pieces: Vec<Option<usize>>,
}
impl RunBuilder {
fn new(face: FaceIndex) -> Self {
Self {
face,
text: String::new(),
glyphs: Vec::new(),
device_xs: Vec::new(),
rights: Vec::new(),
extent: None,
words: Vec::new(),
in_word: false,
pieces: Vec::new(),
}
}
fn span(&self) -> Option<(Length, Length)> {
self.extent.filter(|(start, end)| end > start)
}
fn push(
&mut self,
(ch, id, piece): (char, u32, Option<usize>),
x: Length,
placed: &Placed,
trailing: bool,
) {
self.pieces.push(piece);
self.device_xs.push(x);
let text_start = u32::try_from(self.text.len()).unwrap_or(u32::MAX);
self.text.push(match ch {
NON_BREAKING_HYPHEN | LINE_END_HYPHEN => '-',
_ => ch,
});
let text_end = u32::try_from(self.text.len()).unwrap_or(u32::MAX);
self.glyphs.push(PaintGlyph {
id,
x,
y: Length::ZERO,
text_start,
text_end,
});
self.rights.push(Length::ZERO);
if !trailing {
let end = x + placed.advance;
self.extent = Some(
self.extent
.map_or((x, end), |(first, last)| (first.min(x), last.max(end))),
);
match self.words.last_mut() {
_ if ch.is_whitespace() => {}
Some((first, last)) if self.in_word => {
*first = (*first).min(x);
*last = (*last).max(end);
}
_ => self.words.push((x, end)),
}
}
self.in_word = !ch.is_whitespace();
}
fn redraw_last(&mut self, xs: &[Length]) {
let start = self.glyphs.len().saturating_sub(xs.len());
for (glyph, &x) in self.glyphs.iter_mut().skip(start).zip(xs) {
glyph.x = x;
}
}
fn shift_last(&mut self, (right, up): (Length, Length)) {
if let (Some(last), Some(move_right)) = (self.glyphs.last_mut(), self.rights.last_mut()) {
*move_right = right;
last.y = -up;
}
}
fn join(&mut self, ch: char) {
self.text.push(ch);
let end = u32::try_from(self.text.len()).unwrap_or(u32::MAX);
if let Some(last) = self.glyphs.last_mut() {
last.text_end = end;
}
}
fn settle(&mut self, y: Length) {
for (glyph, &right) in self.glyphs.iter_mut().zip(&self.rights) {
glyph.x += right;
glyph.y = y + glyph.y;
}
}
fn device_places(&self, device: &Device, face: &Face, baseline: Length) -> Vec<DevicePlace> {
let y = baseline - device.shift_dots(face.rise);
(self.glyphs.iter().zip(&self.device_xs).zip(&self.rights))
.map(|((glyph, &x), &right)| DevicePlace {
glyph: glyph.id,
x: x + right,
y: y + glyph.y,
})
.collect()
}
fn finish(mut self, device: &Device, face: &Face, baseline: Length, filled: bool) -> GlyphRun {
self.settle(baseline - device.shift_dots(face.rise));
let size = device.snap(face.size);
let bold_stroke = face
.standing
.synthetic_bold
.then(|| device.bold_stroke(size))
.flatten()
.map(|width| Outline {
width,
color: face.color,
join: Join::Miter,
});
GlyphRun {
font: face.font,
size,
color: face.color,
text: self.text,
glyphs: self.glyphs,
outline: face.outline.or(bold_stroke),
filled,
effect: face.effect,
turn: device.glyph_turn(
size,
&face.metrics,
face.scale,
face.standing.synthetic_italic,
),
}
}
}
const fn visual_start(starts: bool, rtl: bool, before: Option<(bool, bool)>) -> bool {
match before {
Some((true, before_starts)) if rtl => before_starts,
Some((before_rtl, _)) if before_rtl != rtl => true,
_ if rtl => false,
_ => starts,
}
}
fn stop_nudge(device: &Device, start: (Length, Length), placed: &Placed) -> Length {
if !matches!(placed.piece, Piece::Tab(_)) || placed.tab != Some(TabKind::Left) {
return Length::ZERO;
}
device.stop_halves(start, placed.x + placed.advance)
}
fn written_end(
line: &Line,
exact: &[(Length, Length)],
(start, written): (Length, usize),
) -> Length {
written
.checked_sub(1)
.and_then(|last| line.placed.get(last).zip(exact.get(last)))
.map_or(start, |(placed, &(x, stretch))| {
x + placed.advance + stretch
})
}
fn exact_places(
line: &Line,
order: VisualOrder<'_>,
origin: Origin,
departures: &[Length],
) -> Vec<(Length, Length)> {
let mut extra = Length::ZERO;
line.placed
.iter()
.enumerate()
.map(|(index, placed)| {
extra += inner_mark_shrink_before(line, index, origin.mark_shrink, origin.mark_sides)
+ origin.gap_extra * i64::from(spread_gap(line, index));
let x = origin.x + placed.x + extra;
let mut stretch = origin.narrowing.map_or(Length::ZERO, |narrowing| {
narrowing.at(order.logical_index(index))
});
if order.is_stretched(&placed.piece, index) {
stretch += origin.space_extra + departures.get(index).copied().unwrap_or_default();
}
extra += stretch;
(x, stretch)
})
.collect()
}
fn width_departures(line: &Line, order: VisualOrder<'_>, each: Length) -> Vec<Length> {
if each == Length::ZERO {
return Vec::new();
}
let widths: Vec<(usize, i128)> = line
.placed
.iter()
.enumerate()
.filter(|&(index, placed)| order.is_stretched(&placed.piece, index))
.map(|(index, placed)| (index, i128::from(placed.advance.units())))
.collect();
let count = i128::try_from(widths.len()).unwrap_or(0);
let total: i128 = widths.iter().map(|&(_, width)| width).sum();
if count == 0 || total <= 0 {
return Vec::new();
}
let (part, whole) = params::STRETCH_BY_WIDTH;
let cap = total * i128::from(part);
let by_width = (count * i128::from(each.units()) * i128::from(whole)).clamp(-cap, cap);
let denominator = count * total * i128::from(whole);
let mut departures = vec![Length::ZERO; line.placed.len()];
let (mut summed, mut before) = (0_i128, 0_i128);
for (index, width) in widths {
summed += count * width - total;
let up_to = f_office_units::div_round_i128(by_width * summed, denominator);
if let Some(slot) = departures.get_mut(index) {
*slot = i64::try_from(up_to - before).map_or(Length::ZERO, Length::from_units);
}
before = up_to;
}
departures
}
fn stretched_space(piece: &Piece, index: usize, (first, visible): (usize, Option<usize>)) -> bool {
stretches(piece) && index >= first && visible.is_some_and(|v| index <= v)
}
fn counted_share_excesses(
line: &Line,
order: VisualOrder<'_>,
origin: &Origin,
) -> Vec<Option<(i128, i128)>> {
let Some(shares) = origin.counted_shares else {
return Vec::new();
};
let mut k = 0;
line.placed
.iter()
.enumerate()
.map(|(index, placed)| {
order.is_stretched(&placed.piece, index).then(|| {
k += 1;
shares.excess(k)
})
})
.collect()
}
struct Stretch {
glyphs: Vec<StretchGlyph>,
next: After,
}
#[derive(Clone, Copy)]
enum After {
Glyph(Length, DeviceStep),
Mark,
Other,
}
struct StretchGlyph {
piece: usize,
x: Length,
advance: Length,
stretch: Length,
device: DeviceStep,
}
#[derive(Clone, Copy)]
struct DeviceStep {
size: Length,
measured: Option<(i64, Length)>,
without_bias: bool,
rounding: Option<(i64, i64)>,
spacing: Length,
counted_extra: Option<(i64, i64)>,
short_ease: Length,
}
impl DeviceStep {
fn tell(self, edge: &mut grid::EdgeSteps) {
edge.with_device_width(self.measured);
edge.without_bias(self.without_bias);
edge.with_advance_rounding(self.rounding);
edge.with_character_spacing(self.spacing);
edge.with_counted_extra(self.counted_extra);
edge.with_short_ease(self.short_ease);
}
fn widens(self, device: &Device, bias: Length) -> Length {
self.measured.map_or(Length::ZERO, |(width, alone)| {
device.dots(width) - device.snap(alone + bias)
})
}
fn place(
self,
edge: &mut grid::EdgeSteps,
device: &Device,
numbers: (Length, Length, Length),
(x, advance): (Length, Length),
) -> Length {
edge.at_size(self.size, device.snap(self.size));
self.tell(edge);
edge.place(device, numbers, x, advance)
}
}
#[derive(Clone, Copy)]
enum LastGlyph {
AfterGlyph(TrailingSpace),
AfterStretched,
}
#[derive(Clone, Copy)]
struct TrailingSpace {
x: Length,
end: Length,
edge: Length,
advance: Length,
spacing: Length,
step: DeviceStep,
}
struct RightToLeftPlaces {
places: Vec<Option<Length>>,
checks: Vec<Option<crate::grid::EdgeCheck>>,
}
impl RightToLeftPlaces {
fn of(count: usize) -> Self {
Self {
places: vec![None; count],
checks: vec![None; count],
}
}
fn place(&self, index: usize) -> Option<Length> {
self.places.get(index).copied().flatten()
}
fn take_check(&mut self, index: usize) -> Option<crate::grid::EdgeCheck> {
self.checks.get_mut(index).and_then(Option::take)
}
fn place_at(&mut self, index: usize, at: Length) {
if let Some(place) = self.places.get_mut(index) {
*place = Some(at);
}
}
fn check(&mut self, index: usize, check: Option<crate::grid::EdgeCheck>) {
if let Some(slot) = self.checks.get_mut(index) {
*slot = check;
}
}
}
#[derive(Default)]
struct EdgeGlyphs {
numbers: Option<(Length, Length, Length)>,
edge: crate::grid::EdgeSteps,
objects: crate::grid::TextObjects,
object: crate::grid::TextObject,
shift: Length,
trails_at: Option<Length>,
last_glyph: Option<LastGlyph>,
after_label: bool,
after_tab: bool,
tabs: TabTexts,
note_marks: Vec<bool>,
share_excesses: Vec<Option<(i128, i128)>>,
nominal_steps: bool,
scaled_start: Option<(Length, Length)>,
}
impl EdgeGlyphs {
fn of_line(
device: &Device,
(origin, line, order): (&Origin, &Line, VisualOrder<'_>),
tabs: TabTexts,
) -> Self {
let mut edge_steps = Self::new(device).right_to_left(origin.right_to_left);
edge_steps.tabs = tabs;
edge_steps.note_marks = note_mark_starts(line);
edge_steps.share_excesses = counted_share_excesses(line, order, origin);
edge_steps.edge.hands_on_start(origin.starts_at_indent);
if origin.steps_alone {
let unchecked = Length::from_units(Length::FILE_LIMIT);
edge_steps.numbers = edge_steps
.numbers
.map(|(bias, _, _)| (bias, unchecked, unchecked));
}
edge_steps
}
fn tell(&mut self, step: DeviceStep, index: usize) {
step.tell(&mut self.edge);
self.edge
.with_counted_share(self.share_excesses.get(index).copied().flatten());
}
fn note_mark(&mut self, device: &Device, index: usize) {
if self.note_marks.get(index) != Some(&true) {
return;
}
self.edge.at_note_mark(device);
}
fn after_written(&mut self, after: bool, at: Length) {
if after && self.trails_at.is_none() {
self.trails_at = Some(at);
}
}
fn end(&self, device: &Device, written: Length) -> Option<Length> {
self.numbers?;
self.trails_at.or_else(|| {
let end = self
.edge
.end(device, written)
.or_else(|| self.tab_end(device, written))?;
Some(end + self.shift)
})
}
fn tab_end(&self, device: &Device, written: Length) -> Option<Length> {
if !self.after_tab {
return None;
}
self.edge.tab_end(device, written)
}
fn new(device: &Device) -> Self {
let numbers = match device.advances() {
crate::grid::Advances::RightEdge {
bias,
limit,
segment,
..
} => Some((bias, limit, segment)),
crate::grid::Advances::PdfSteps => None,
};
Self {
numbers,
object: crate::grid::TextObject::of(device),
..Self::default()
}
}
fn right_to_left(self, shift: Option<Length>) -> Self {
Self {
shift: shift.unwrap_or(Length::ZERO),
..self
}
}
fn gap(
&mut self,
device: &Device,
(index, placed, origin): (usize, &Placed, &Origin),
run: Option<&mut RunBuilder>,
) {
self.tabs.at_piece(placed.piece, device, &self.edge);
if placed.advance != Length::ZERO {
let label = std::mem::take(&mut self.after_label);
self.after_tab =
label || matches!(placed.piece, Piece::Tab(_) | Piece::PositionTab(..));
if self.after_tab {
self.edge.tab();
self.edge.with_stop_nudge(
stop_nudge(device, (origin.start, origin.own), placed) + origin.segment_rest,
);
} else {
self.edge.gap(device);
}
self.objects.restart();
self.finish(run);
self.tabs.after_gap(index, placed);
} else if placed.piece == Piece::NoteMarkEnd {
self.edge.after_note_mark(device);
}
}
fn finish(&mut self, run: Option<&mut RunBuilder>) {
if self.object.is_empty() {
return;
}
let drawn = self.object.draw();
if let Some(run) = run {
run.redraw_last(&drawn);
}
}
fn place(
&mut self,
device: &Device,
(x, advance, size, stretch): (Length, Length, Length, Length),
(ch, glyph_side, starts, written, spacing): (char, FontSide, bool, Option<u16>, Length),
(index, from_right, per_glyph): (usize, Option<Length>, bool),
run: Option<&mut RunBuilder>,
) -> Option<Length> {
let last = self.last_glyph.take();
self.after_tab = false;
let numbers = self.numbers?;
self.note_mark(device, index);
let drawn = device.snap(size);
self.edge
.at_size(size, if self.nominal_steps { size } else { drawn });
let place = if let Some(place) = from_right {
place
} else {
let extra = crate::grid::GlyphExtra::of(stretch, spacing);
self.edge.with_extra(extra);
if let Some(dot) = self.tabs.take_start() {
self.edge.with_stop_nudge(dot - x);
}
let place = self.edge.place(device, numbers, x, advance + stretch);
if extra.length() != Length::ZERO {
self.edge.after_extra(extra);
}
let place = self.scaled_place(device, place, x);
place + self.end_move(device, numbers, last, place - x)
} + self.shift;
self.tabs.glyph(place, (x, advance), ch == ' ');
if self.objects.starts(
device.writer_char(ch),
device.writer_side(glyph_side),
starts,
) {
self.finish(run);
}
if per_glyph {
self.object.set_per_glyph();
}
self.object.push_at(place, advance, (size, drawn), written);
Some(place)
}
fn scaled_place(&mut self, device: &Device, place: Length, x: Length) -> Length {
if !self.nominal_steps {
self.scaled_start = None;
return place;
}
if let Some((first, first_x)) = self.scaled_start {
first + device.floor(x - first_x)
} else {
self.scaled_start = Some((place, x));
place
}
}
fn end_move(
&self,
device: &Device,
numbers: (Length, Length, Length),
last: Option<LastGlyph>,
past: Length,
) -> Length {
let space = match last {
Some(LastGlyph::AfterGlyph(space)) => space,
Some(LastGlyph::AfterStretched) => return device.spaced_end_move(past, numbers.1),
None => return Length::ZERO,
};
let at = || {
let mut ahead = self.edge;
ahead.with_extra(crate::grid::GlyphExtra::Spacing(space.spacing));
(space.step).place(&mut ahead, device, numbers, (space.x, space.advance))
};
device.trailing_space_move(at, (space.x, space.end, space.edge), self.edge.started())
}
fn place_stretch(&mut self, device: &Device, stretch: &Stretch, out: &mut RightToLeftPlaces) {
let glyphs = &stretch.glyphs;
let (Some(numbers), Some(first)) = (self.numbers, glyphs.first()) else {
return;
};
let step = |advance: Length| device.snap(advance + numbers.0);
let own_steps = device.ends_right_to_left_at_edge();
let moved = self
.edge
.when_starting(device.right_to_left_origin(first.x) - first.x);
let mut read = first.x + moved;
let mut stepped = Vec::with_capacity(glyphs.len());
for glyph in glyphs.iter().rev() {
let spanned = if own_steps {
glyph.advance - glyph.stretch
} else {
glyph.advance
};
let own = step(spanned) + glyph.device.widens(device, numbers.0);
let mut stepped_device = glyph.device;
(stepped_device.measured, stepped_device.without_bias) = device.right_to_left_step(
&mut self.edge,
(glyph.device.measured, glyph.device.without_bias),
);
let at = stepped_device.place(&mut self.edge, device, numbers, (read, glyph.advance));
out.check(glyph.piece, self.edge.take_checked());
if glyph.stretch != Length::ZERO {
self.edge
.after_extra(crate::grid::GlyphExtra::Justified(glyph.stretch));
}
read += glyph.advance;
stepped.push((glyph.piece, at, own));
}
self.edge.move_exact(Length::ZERO - moved);
read -= moved;
let (Some(&(_, start, _)), Some(&(_, last, width))) = (stepped.first(), stepped.last())
else {
return;
};
let end = match stretch.next {
After::Glyph(advance, after) => {
let mut ahead = self.edge;
after.place(&mut ahead, device, numbers, (read, advance))
}
After::Mark => device.snap(read),
After::Other => last + width + self.edge.pending_extra(device),
};
for (piece, at, own) in stepped {
out.place_at(piece, start + end - at - own);
}
}
fn records(
&mut self,
stepped: bool,
right: Option<crate::grid::EdgeCheck>,
) -> (Option<crate::grid::EdgeCheck>, Option<Length>) {
let checked = self.edge.take_checked().filter(|_| stepped).or(right);
(checked, self.edge.take_start_place().filter(|_| stepped))
}
fn place_leader(
&mut self,
device: &Device,
(x, advance, size): (Length, Length, Length),
(starts, written): (bool, Option<u16>),
run: Option<&mut RunBuilder>,
) -> Option<Length> {
let numbers = self.numbers?;
let drawn = device.snap(size);
self.edge.at_size(size, drawn);
let place = self.edge.place(device, numbers, x, advance) + self.shift;
if starts {
self.finish(run);
}
self.object.push_at(place, advance, (size, drawn), written);
Some(place)
}
}
struct RtlObjectMarks {
reading_order: Vec<bool>,
full: Vec<bool>,
after_spaces: Vec<bool>,
}
impl RtlObjectMarks {
fn of(len: usize) -> Self {
Self {
reading_order: vec![false; len],
full: vec![false; len],
after_spaces: vec![false; len],
}
}
fn tell(&self, index: usize, objects: &mut grid::TextObjects) {
if self.reading_order.get(index) == Some(&true) {
objects.reading_order_spaces();
}
if self.full.get(index) == Some(&true) {
objects.fill();
}
if self.after_spaces.get(index) == Some(&true) {
objects.after_spaces();
}
}
}
struct ObjectMarks {
rtl: RtlObjectMarks,
off_baseline: Vec<bool>,
}
impl ObjectMarks {
fn is_off_baseline(&self, index: usize) -> bool {
self.off_baseline.get(index) == Some(&true)
}
fn tell(&self, index: usize, trace: &mut grid::TextObjects, drawn: &mut grid::TextObjects) {
self.rtl.tell(index, trace);
self.rtl.tell(index, drawn);
if self.is_off_baseline(index) {
trace.alone_off_baseline();
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ObjectPiece {
Tab,
Gap,
Glyph(ObjectGlyph),
Part { in_rtl: bool, glyph: ObjectGlyph },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ObjectGlyph {
face: FaceIndex,
ch: char,
side: FontSide,
right_to_left: bool,
text_start: bool,
off: bool,
}
fn off_baseline_marks(pieces: &[ObjectPiece], rtl_marks: &RtlObjectMarks) -> Vec<bool> {
let mut marks = vec![false; pieces.len()];
let mut objects = grid::TextObjects::default();
let mut object: Vec<usize> = Vec::new();
let mut off = false;
let mut face = None;
let mut before: Option<(bool, bool)> = None;
for (index, piece) in pieces.iter().enumerate() {
let glyph = match *piece {
ObjectPiece::Tab => {
face = None;
objects.restart();
continue;
}
ObjectPiece::Gap => {
objects.restart();
continue;
}
ObjectPiece::Part { in_rtl, glyph } if in_rtl || face.is_some() => {
off |= glyph.off;
continue;
}
ObjectPiece::Glyph(glyph) | ObjectPiece::Part { glyph, .. } => glyph,
};
if face.is_some_and(|open| open != glyph.face) {
face = None;
}
let starts = face.is_none() || visual_start(glyph.text_start, glyph.right_to_left, before);
before = Some((glyph.right_to_left, glyph.text_start));
rtl_marks.tell(index, &mut objects);
if objects.starts(glyph.ch, glyph.side, starts) {
mark_object(&mut marks, &mut object, std::mem::take(&mut off));
}
face = Some(glyph.face);
object.push(index);
off |= glyph.off;
}
mark_object(&mut marks, &mut object, off);
marks
}
fn mark_object(marks: &mut [bool], object: &mut Vec<usize>, off: bool) {
for index in object.drain(..) {
if let Some(mark) = marks.get_mut(index).filter(|_| off) {
*mark = true;
}
}
}
#[cfg(test)]
mod tests {
use f_office_units::Length;
use super::{EdgeGlyphs, RunBuilder, stop_nudge};
use crate::grid::Device;
use crate::lines::{Piece, Placed};
use crate::text::{FaceIndex, SpaceKind};
#[test]
fn scaled_run_glyphs_lie_on_the_floor_of_their_exact_distance() {
let device = Device::per_inch(600).unwrap();
let dot = device.dots(1);
let mut glyphs = EdgeGlyphs {
nominal_steps: true,
..EdgeGlyphs::default()
};
let first = Length::from_units(10 * dot.units());
let exact = first + Length::from_units(dot.units() / 3);
assert_eq!(glyphs.scaled_place(&device, first, exact), first);
let later = exact + Length::from_units(dot.units() * 29 / 10);
let steps = first + Length::from_units(4 * dot.units());
assert_eq!(
glyphs.scaled_place(&device, steps, later),
first + Length::from_units(2 * dot.units())
);
glyphs.nominal_steps = false;
assert_eq!(glyphs.scaled_place(&device, steps, later), steps);
glyphs.nominal_steps = true;
assert_eq!(glyphs.scaled_place(&device, steps, later), steps);
}
fn spaced_line(widths: [i64; 5]) -> crate::lines::Line {
crate::lines::Line {
placed: "a b c d e "
.chars()
.enumerate()
.map(|(index, ch)| Placed {
piece: Piece::Glyph(crate::text::Glyph::plain(FaceIndex::nth(0), ch)),
x: Length::ZERO,
advance: Length::from_units(if ch == ' ' {
widths.get(index / 2).copied().unwrap_or(0)
} else {
50
}),
leader: None,
tab: None,
})
.collect(),
..crate::lines::Line::default()
}
}
fn space_departures(
line: &crate::lines::Line,
each: i64,
share: crate::quirks::StretchedSpaceShare,
) -> Vec<i64> {
let quirks = crate::profile::Profile::base().with_variant(share).quirks();
let found = crate::layout::decisions::width_first_share(&quirks, || {
super::width_departures(
line,
super::VisualOrder::ltr(line),
Length::from_units(each),
)
})
.unwrap_or_default();
(0..line.placed.len())
.filter(|index| index % 2 == 1)
.map(|index| found.get(index).map_or(0, |d| d.units()))
.collect()
}
#[test]
fn shares_the_free_space_by_the_widths_of_the_stretched_spaces_up_to_half_of_each() {
use crate::quirks::StretchedSpaceShare::{Equal, WidthFirst};
let two = spaced_line([100, 200, 100, 200, 200]);
assert_eq!(
space_departures(&two, 30, WidthFirst),
[-10, 10, -10, 10, 0]
);
assert_eq!(
space_departures(&two, 300, WidthFirst),
[-25, 25, -25, 25, 0]
);
let paired = spaced_line([100, 100, 200, 200, 200]);
assert_eq!(space_departures(&paired, 7, WidthFirst), [-2, -3, 3, 2, 0]);
assert_eq!(space_departures(&two, 300, Equal), [0; 5]);
assert_eq!(
space_departures(&two, -30, WidthFirst),
[10, -10, 10, -10, 0]
);
assert_eq!(
space_departures(&two, -300, WidthFirst),
[25, -25, 25, -25, 0]
);
let one = spaced_line([150, 150, 150, 150, 150]);
assert_eq!(space_departures(&one, 300, WidthFirst), [0; 5]);
}
#[test]
fn a_footnote_mark_starts_at_the_first_glyph_of_the_marks_face_before_the_note() {
use crate::lines::{Line, NoteNumber};
use crate::text::Glyph;
let pieces = [
Piece::Glyph(Glyph::plain(FaceIndex::nth(0), 'a')),
Piece::Glyph(Glyph::plain(FaceIndex::nth(0), 'b')),
Piece::Glyph(Glyph::plain(FaceIndex::nth(1), '1')),
Piece::Glyph(Glyph::plain(FaceIndex::nth(1), '2')),
Piece::Note(NoteNumber::of_index(0)),
Piece::Glyph(Glyph::plain(FaceIndex::nth(0), 'c')),
Piece::Note(NoteNumber::of_index(1)),
];
let line = Line {
placed: pieces
.iter()
.map(|&piece| Placed {
piece,
x: Length::ZERO,
advance: Length::ZERO,
leader: None,
tab: None,
})
.collect(),
..Line::default()
};
let starts = super::note_mark_starts(&line);
assert_eq!(starts, [false, false, true, false, false, true, false]);
}
#[test]
fn the_text_after_a_left_tab_lands_on_the_dot_of_its_stop_past_the_column_edge() {
use crate::props::TabKind;
use crate::quirks::LineStartHalves;
let plain = Device::per_inch(600).unwrap();
let device = Device::per_inch_with(600, |p| p.with_variant(LineStartHalves::FixedPoint));
let twips = |t: i64| Length::from_twips(t).unwrap();
let size = device.dots(1).units();
let landed = |device: Device, kind, (start, from, to): (i64, i64, i64)| {
let start = twips(start);
let tab = Placed {
piece: Piece::Tab(None),
x: twips(from - start.units() / 1_270),
advance: twips(to - from),
leader: None,
tab: Some(kind),
};
let exact = device.line_start(start) + tab.x + tab.advance;
device
.snap(exact + stop_nudge(&device, (start, Length::ZERO), &tab))
.units()
/ size
};
assert_eq!(landed(device, TabKind::Left, (0, 300, 1_458)), 607);
assert_eq!(landed(plain, TabKind::Left, (0, 300, 1_458)), 608);
assert_eq!(landed(device, TabKind::Left, (18, 300, 1_458)), 607);
assert_eq!(landed(device, TabKind::Left, (18, 300, 1_464)), 610);
assert_eq!(landed(device, TabKind::Right, (0, 300, 1_458)), 608);
}
fn end_move_device() -> (Device, (Length, Length, Length), super::DeviceStep) {
end_move_device_with(crate::profile::Profile::clone)
}
fn end_move_device_with(
change: impl FnOnce(&crate::profile::Profile) -> crate::profile::Profile,
) -> (Device, (Length, Length, Length), super::DeviceStep) {
let u = Length::from_units;
let numbers = (u(127), u(4_572), u(1_024 * 3_048));
let advances = crate::grid::Advances::RightEdge {
bias: numbers.0,
limit: numbers.1,
segment: numbers.2,
point_steps: std::num::NonZeroU32::new(1_024),
start: f_office_paint::WriterOffset::NONE,
};
let device = Device::per_inch_with(600, |p| {
change(&p.with_variant(crate::quirks::AlignedEnds::OnDots))
})
.with_advances(advances);
let step = super::DeviceStep {
size: Length::from_points(12).unwrap(),
measured: None,
without_bias: false,
rounding: None,
spacing: Length::ZERO,
counted_extra: None,
short_ease: Length::ZERO,
};
(device, numbers, step)
}
fn trailing_space(x: Length, end: Length, step: super::DeviceStep) -> super::TrailingSpace {
super::TrailingSpace {
x,
end,
edge: Length::ZERO,
advance: Length::from_units(7_000),
spacing: Length::ZERO,
step,
}
}
#[test]
fn moves_the_last_glyph_by_the_place_that_the_steps_give_its_trailing_space() {
let u = Length::from_units;
let (device, numbers, step) = end_move_device();
let dot = device.dots(1);
let mut found = std::collections::BTreeSet::new();
for start in [dot * 328 + u(1_494), dot * 328 + u(1_554)] {
for advance in (20_000..60_000).step_by(97).map(u) {
let mut glyphs = super::EdgeGlyphs::new(&device);
for k in 0..6 {
glyphs
.edge
.place(&device, numbers, start + advance * k, advance);
}
let x = start + advance * 6;
let space = trailing_space(x, x, step);
let last = Some(super::LastGlyph::AfterGlyph(space));
let moved = glyphs.end_move(&device, numbers, last, Length::ZERO);
let at = step.place(&mut glyphs.edge, &device, numbers, (space.x, space.advance));
assert_eq!(moved, device.justified_end_move(at, space.x));
found.insert(moved);
}
}
assert_eq!(
found.into_iter().collect::<Vec<_>>(),
[-dot, Length::ZERO, dot]
);
let glyphs = super::EdgeGlyphs::new(&device);
assert_eq!(
glyphs.end_move(&device, numbers, None, Length::ZERO),
Length::ZERO
);
}
#[test]
fn moves_the_last_glyph_after_stretched_spaces_within_the_limit_of_its_exact_place() {
use crate::quirks::SpacedLastGlyph;
let (limited, numbers, _) =
end_move_device_with(|p| p.with_variant(SpacedLastGlyph::EdgeLimit));
let stepped = end_move_device_with(|p| p.with_variant(SpacedLastGlyph::StepsPlace)).0;
let glyphs = super::EdgeGlyphs::new(&limited);
let (dot, limit, unit) = (limited.dots(1), numbers.1, Length::from_units(1));
let last = Some(super::LastGlyph::AfterStretched);
let moved = |past: Length| glyphs.end_move(&limited, numbers, last, past);
assert_eq!(moved(limit), Length::ZERO);
assert_eq!(moved(limit + unit), -dot);
assert_eq!(moved(limit + dot), -dot);
assert_eq!(moved(limit + dot + unit), -dot * 2);
assert_eq!(moved(-limit - dot * 2), Length::ZERO);
assert_eq!(
glyphs.end_move(&stepped, numbers, last, limit + dot),
Length::ZERO
);
}
#[test]
fn moves_a_restarted_last_glyph_by_the_line_right_edge() {
let u = Length::from_units;
let (device, numbers, step) = end_move_device();
let dot = device.dots(1);
let half = dot.div_round(2);
let mut state: u64 = 1;
let mut advances = std::iter::repeat_with(move || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
u(20_000 + i64::try_from((state >> 33) % 60_000).unwrap())
});
let mut after_restart = std::collections::BTreeSet::new();
let mut from_edge = 0;
for _ in 0..400 {
let (glyphs, x) = restarted_line(&device, numbers, &mut advances);
for end in [x, device.snap_half_down(x) + half] {
let space = trailing_space(x, end, step);
let last = Some(super::LastGlyph::AfterGlyph(space));
let moved = glyphs.end_move(&device, numbers, last, Length::ZERO);
let mut ahead = glyphs.edge;
let at = step.place(&mut ahead, &device, numbers, (space.x, space.advance));
assert_eq!(moved, device.restarted_end_move(at, end, Length::ZERO));
from_edge += i32::from(moved != device.justified_end_move(at, x));
after_restart.insert((end == x, moved));
}
}
assert!(after_restart.contains(&(true, -dot)));
assert!(from_edge > 0);
}
fn restarted_line(
device: &Device,
numbers: (Length, Length, Length),
advances: &mut impl Iterator<Item = Length>,
) -> (super::EdgeGlyphs, Length) {
let dot = device.dots(1);
let mut glyphs = super::EdgeGlyphs::new(device);
glyphs.edge.hands_on_start(true);
let mut x = dot * 328 + Length::from_units(1_494);
let mut restarts = 0;
while restarts < 8 {
let advance = advances.next().unwrap();
glyphs.edge.place(device, numbers, x, advance);
x += advance;
restarts += i32::from(glyphs.edge.started() && x > dot * 400);
}
(glyphs, x)
}
#[test]
fn a_restarted_last_glyph_takes_the_upper_dot_of_an_edge_on_a_half_dot() {
let (device, _, _) = end_move_device();
let dot = device.dots(1);
let edge = dot * 500 + dot.div_round(2);
assert_eq!(
device.restarted_end_move(dot * 502, edge, Length::ZERO),
Length::ZERO
);
assert_eq!(device.justified_end_move(dot * 502, edge), -dot);
assert_eq!(
device.restarted_end_move(dot * 503, edge, Length::ZERO),
-dot
);
}
fn test_glyph(ch: char) -> crate::text::Glyph {
crate::text::Glyph {
face: FaceIndex::nth(0),
ch,
id: 1,
advance: Length::from_units(100),
offset: (Length::ZERO, Length::ZERO),
spacing: Length::ZERO,
kerning: Length::ZERO,
auto_space: Length::ZERO,
counted: Length::ZERO,
written: None,
part: false,
label: false,
space: SpaceKind::Free,
starts_run: false,
left_out_before: crate::text::LeftOutBefore::Nothing,
direction: crate::text::RunDirection::default(),
side: crate::text::FontSide::Open,
place: crate::text::TextPlace::default(),
sizing: crate::text::LineSizing::ByFace,
}
}
#[test]
fn records_the_place_of_each_drawn_glyph_and_the_spaces_before_it() {
use crate::layout::StepsStart;
use crate::lines::Step;
let mut steps = super::Steps::default();
for (x, ch) in (0..).step_by(100).zip(['a', ' ', ' ', 'b', ' ', 'c']) {
let glyph = test_glyph(ch);
let placed = Placed {
piece: Piece::Glyph(glyph),
x: Length::ZERO,
advance: glyph.advance,
leader: None,
tab: None,
};
steps.piece(&placed, true);
steps.placed(x == 0 || x == 200, ch == ' ');
steps.glyph(
&glyph,
(Length::from_units(x), Length::from_units(x + 7)),
(None, None),
);
}
let records: Vec<(i64, i64, u32, StepsStart)> = (steps.drawn.glyphs.iter())
.map(|drawn| {
(
drawn.x.units(),
drawn.place.units(),
drawn.spaces,
drawn.started,
)
})
.collect();
assert_eq!(
records,
[
(0, 7, 0, StepsStart::Glyph),
(300, 307, 2, StepsStart::Space(2)),
(500, 507, 1, StepsStart::Stepped)
]
);
assert_eq!(
steps.drawn.steps,
[Step::Start, Step::Stretched, Step::Stretched]
);
}
#[test]
fn records_each_character_of_a_leader_and_leaves_the_glyph_after_it_its_step() {
use crate::lines::Step;
let glyph = test_glyph('a');
let space = test_glyph(' ');
let mut steps = super::Steps::default();
steps.piece(
&Placed {
piece: Piece::Glyph(space),
x: Length::ZERO,
advance: space.advance,
leader: None,
tab: None,
},
false,
);
for x in [300, 400] {
steps.leader(Length::from_units(x), Length::from_units(x + 5));
}
steps.glyph(
&glyph,
(Length::from_units(900), Length::from_units(906)),
(None, None),
);
assert_eq!(steps.drawn.steps, [Step::Leader, Step::Leader, Step::Start]);
let records: Vec<(i64, i64, u32)> = (steps.drawn.glyphs.iter())
.map(|drawn| (drawn.x.units(), drawn.place.units(), drawn.spaces))
.collect();
assert_eq!(records, [(300, 305, 0), (400, 405, 0), (900, 906, 1)]);
}
#[test]
fn writes_glyph_by_glyph_only_the_objects_that_hold_a_glyph_off_the_baseline() {
use super::{ObjectGlyph, ObjectPiece, RtlObjectMarks, off_baseline_marks};
let glyph = |ch, off, text_start| {
ObjectPiece::Glyph(ObjectGlyph {
face: FaceIndex::nth(0),
ch,
side: crate::text::FontSide::Open,
right_to_left: true,
text_start,
off,
})
};
let ba = |off, text_start| glyph('\u{0628}', off, text_start);
let line = [
ba(false, false),
ba(true, false),
ba(false, true),
ba(false, false),
ba(false, false),
];
assert_eq!(
off_baseline_marks(&line, &RtlObjectMarks::of(5)),
[true, true, true, false, false]
);
let joined = [line[0], line[1], ba(false, false), line[3], line[4]];
assert_eq!(
off_baseline_marks(&joined, &RtlObjectMarks::of(5)),
[true; 5]
);
let gap = [line[0], line[1], ObjectPiece::Gap, line[3], line[4]];
assert_eq!(
off_baseline_marks(&gap, &RtlObjectMarks::of(5)),
[true, true, false, false, false]
);
let ObjectPiece::Glyph(facts) = line[3] else {
unreachable!("the fourth piece is a glyph")
};
let part = ObjectPiece::Part {
in_rtl: true,
glyph: facts,
};
let joined_part = [line[0], line[1], part, line[2], line[3], line[4]];
assert_eq!(
off_baseline_marks(&joined_part, &RtlObjectMarks::of(6)),
[true, true, false, true, false, false]
);
let plain = [line[0], line[0], line[2], line[3], line[4]];
assert_eq!(
off_baseline_marks(&plain, &RtlObjectMarks::of(5)),
[false; 5]
);
let trailing_and_leading = [
glyph(' ', false, false),
ba(true, false),
ba(false, false),
glyph(' ', false, true),
];
let rtl_marks = RtlObjectMarks {
reading_order: vec![true; 4],
full: vec![false; 4],
after_spaces: vec![false, false, false, true],
};
assert_eq!(
off_baseline_marks(&trailing_and_leading, &rtl_marks),
[true, true, true, false]
);
}
#[test]
fn a_glyph_keeps_the_move_of_the_layout_tables_when_its_text_object_is_redrawn() {
let placed = Placed {
piece: Piece::Tab(None),
x: Length::ZERO,
advance: Length::from_units(100),
leader: None,
tab: None,
};
let mut run = RunBuilder::new(FaceIndex::nth(0));
run.push(('a', 1, None), Length::from_units(1000), &placed, false);
run.push(('b', 2, None), Length::from_units(1100), &placed, false);
run.shift_last((Length::from_units(-40), Length::from_units(30)));
run.redraw_last(&[Length::from_units(1004), Length::from_units(1108)]);
run.settle(Length::from_units(5000));
let drawn: Vec<(i64, i64)> = run
.glyphs
.iter()
.map(|glyph| (glyph.x.units(), glyph.y.units()))
.collect();
assert_eq!(drawn, [(1004, 5000), (1068, 4970)]);
}
#[test]
fn stretches_logical_post_tab_spaces_on_bidi_reordered_rtl_lines() {
use super::{Origin, VisualOrder, exact_places};
use crate::lines::Line;
use crate::props::TabKind;
let glyph = |ch| Placed {
piece: Piece::Glyph(crate::text::Glyph::plain(FaceIndex::nth(0), ch)),
x: Length::ZERO,
advance: Length::from_units(100),
leader: None,
tab: None,
};
let tab = Placed {
piece: Piece::Tab(None),
x: Length::ZERO,
advance: Length::from_units(200),
leader: None,
tab: Some(TabKind::Left),
};
let visual_line = Line {
placed: vec![
glyph('\u{05D1}'),
glyph(' '),
glyph('\u{05D0}'),
glyph(' '),
tab,
glyph('\u{05D2}'),
glyph(' '),
glyph('\u{05D3}'),
],
..Line::default()
};
let logical = [7, 6, 5, 4, 3, 2, 1, 0];
let order = VisualOrder {
rtl: &[true; 8],
written: 8,
logical: &logical,
stretched_bounds: (5, Some(7)),
};
let origin = Origin {
x: Length::ZERO,
edge: Length::ZERO,
start: Length::ZERO,
own: Length::ZERO,
baseline: Length::ZERO,
unrounded_baseline: Length::ZERO,
grid_shift: Length::ZERO,
space_extra: Length::from_units(50),
space_rest: Length::ZERO,
counted_shares: None,
mark_shrink: Length::ZERO,
mark_sides: crate::layout::line::MarkSides::BlankHalf,
gap_extra: Length::ZERO,
narrowing: None,
drop: Length::ZERO,
anchor_bottom: None,
text_from: 0,
mark: false,
right_to_left: Some(Length::ZERO),
starts_at_indent: false,
segment_rest: Length::ZERO,
steps_alone: false,
};
let stretches: Vec<i64> = exact_places(&visual_line, order, origin, &[])
.into_iter()
.map(|(_, stretch)| stretch.units())
.collect();
assert_eq!(stretches, [0, 50, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn drops_an_inline_vml_shape_on_an_empty_line_of_multiple_spacing() {
use crate::layout::testing::{NORMAL, lay_out, shape_top};
let shape = |line: i64, rule: &str| {
let body = format!(
r##"<w:p><w:pPr><w:spacing w:line="{line}" w:lineRule="auto" w:after="0"/></w:pPr><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><v:rect style="width:100pt;height:1pt" fillcolor="#000000" stroked="f" {rule}/></w:pict></w:r></w:p>"##
);
shape_top(&lay_out(&body, NORMAL, None))
};
assert_eq!(shape(240, ""), shape(240, r#"o:hr="t""#));
assert_eq!(
shape(360, "") - shape(360, r#"o:hr="t""#),
100 * Length::UNITS_PER_TWIP
);
}
}