use f_office_units::scale::THOUSANDTHS;
use f_office_units::{Length, count_factor};
use crate::character_class::CharacterClass;
use crate::kinsoku::{Kinsoku, breaks_between};
use crate::props::{TabKind, TabStop};
use crate::tabs::Tabs;
use crate::text::{AUTOMATIC_HYPHEN, FaceIndex, Glyph, LINE_END_HYPHEN, SOFT_HYPHEN, SpaceKind};
pub(crate) mod joints;
use joints::JointCounts;
const NO_BREAK_SPACE: char = '\u{a0}';
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Piece {
Glyph(Glyph),
Tab(Option<FaceIndex>),
PositionTab(Option<FaceIndex>, TabStop),
LineBreak(Option<FaceIndex>),
PageBreak,
ColumnBreak,
Note(NoteNumber),
NoteMarkEnd,
Comment(CommentIndex),
Anchor(usize),
Strut(FaceIndex),
Clear,
Rule {
face: FaceIndex,
width: Length,
},
CheckBox {
face: FaceIndex,
width: Length,
},
Shift(Length),
Advance(Length),
Bar {
face: FaceIndex,
width: Length,
},
Vinculum {
face: FaceIndex,
width: Length,
top: Length,
thickness: Length,
beyond: (Length, Length),
clear: Length,
},
Diagonal {
face: FaceIndex,
width: Length,
bottom: Length,
top: Length,
thickness: Length,
rising: bool,
},
Object {
width: Length,
height: Length,
raised: Length,
picture: Option<usize>,
drawing: Option<DrawingIndex>,
underlined: bool,
run_face: Option<FaceIndex>,
joins_before: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DrawingIndex(usize);
impl DrawingIndex {
pub(crate) const fn new(index: usize) -> Self {
Self(index)
}
pub(crate) const fn get(self) -> usize {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CommentIndex(usize);
impl CommentIndex {
pub(crate) const fn new(index: usize) -> Self {
Self(index)
}
pub(crate) const fn get(self) -> usize {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NoteNumber(usize);
impl NoteNumber {
pub(crate) const fn of_index(index: usize) -> Self {
Self(index)
}
pub(crate) const fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Placed {
pub piece: Piece,
pub x: Length,
pub advance: Length,
pub leader: Option<char>,
pub tab: Option<TabKind>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineEnd {
#[default]
Wrap,
Split,
Break(Option<FaceIndex>),
PageBreak,
ColumnBreak,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Line {
pub placed: Vec<Placed>,
pub end: LineEnd,
pub kept: Option<Fit>,
pub wrapped: Option<Fit>,
pub would_hang: bool,
pub anchors: Vec<LineAnchor>,
pub hyphen: Option<EndHyphen>,
pub written_end_spaces: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EndHyphen {
Automatic,
Soft,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineAnchor {
pub at: usize,
pub drawing: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Step {
Start,
Label,
AfterLabel,
Tab,
AlignedTab,
Stretched,
Space,
Object,
Leader,
Glyph,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Fit {
pub width: Length,
pub end: Length,
pub word: Length,
pub spaces: Length,
pub space: Length,
pub space_count: usize,
pub last_space_count: usize,
pub room: Length,
pub over: Length,
pub shrinks: bool,
}
impl Line {
#[must_use]
pub fn pieces(lines: &[Self]) -> Vec<Piece> {
let mut pieces = Vec::new();
for line in lines {
let mut marks = line.anchors.iter().peekable();
for (index, placed) in line.placed.iter().enumerate() {
while let Some(mark) = marks.next_if(|mark| mark.at <= index) {
pieces.push(Piece::Anchor(mark.drawing));
}
pieces.push(placed.piece);
}
pieces.extend(marks.map(|mark| Piece::Anchor(mark.drawing)));
match line.end {
LineEnd::PageBreak => pieces.push(Piece::PageBreak),
LineEnd::ColumnBreak => pieces.push(Piece::ColumnBreak),
LineEnd::Break(face) => pieces.push(Piece::LineBreak(face)),
LineEnd::Wrap | LineEnd::Split => {}
}
}
pieces
}
#[must_use]
pub fn starts_with_page_break(&self, index: usize, last: bool) -> bool {
index == 0 && !last && self.holds_only_page_break()
}
#[must_use]
pub fn holds_only_page_break(&self) -> bool {
self.placed.is_empty() && self.end == LineEnd::PageBreak
}
#[must_use]
pub fn first_index(lines: &[Self], breaks: LeadingBreaks) -> usize {
let leading = lines
.iter()
.take_while(|line| line.holds_only_page_break())
.count();
if leading == lines.len() {
return 0;
}
breaks.before_first_line(leading)
}
#[must_use]
pub const fn breaks_page_or_column(&self) -> bool {
matches!(self.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
}
}
impl Line {
#[must_use]
pub fn width(&self) -> Length {
self.end_of(self.written())
}
#[must_use]
pub fn fit_width(&self) -> Length {
let written = self.placed.get(..self.written()).unwrap_or_default();
self.width() + written.iter().map(|p| counted(&p.piece)).sum()
}
#[must_use]
pub fn written(&self) -> usize {
self.last_visible().map_or(0, |last| last + 1)
}
#[must_use]
pub fn end_of(&self, pieces: usize) -> Length {
pieces
.checked_sub(1)
.and_then(|last| self.placed.get(last))
.map_or(Length::ZERO, |p| p.x + p.advance)
}
#[must_use]
pub fn holds_left_to_right_text(&self) -> bool {
self.placed
.iter()
.any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(false))
}
#[must_use]
pub fn last_visible(&self) -> Option<usize> {
let last = self
.placed
.iter()
.rposition(|p| !is_space(&p.piece) && !is_operator_space(&p.piece))?;
let spaces = self.placed.len() - 1 - last;
Some(last + self.written_end_spaces.min(spaces))
}
#[must_use]
pub fn first_stretched(&self) -> usize {
let after_tab = self
.placed
.iter()
.rposition(|p| matches!(p.piece, Piece::Tab(_) | Piece::PositionTab(..)))
.map_or(0, |i| i + 1);
let rest = self.placed.get(after_tab..).unwrap_or(&[]);
after_tab
+ rest
.iter()
.position(|p| !is_space(&p.piece))
.unwrap_or(rest.len())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThaiText {
None,
InWord,
OnLine,
}
fn is_thai(piece: &Piece) -> bool {
matches!(piece, Piece::Glyph(glyph) if CharacterClass::Thai.contains(glyph.ch))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Frame {
pub first_width: Length,
pub width: Length,
pub area_width: Length,
pub first_start: Length,
pub start: Length,
pub tabs: Tabs,
pub shrink: Shrink,
pub thai_keeps_spaces: bool,
pub end_space_fit: EndSpaceFit,
pub kinsoku: Option<Kinsoku>,
pub joined_spaces: bool,
pub breaking: LineBreaking,
pub limits_past_end: bool,
pub punctuation: Option<Compression>,
pub hyphenation: Option<Hyphenation>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EndSpaceFit {
#[default]
WithoutSpaces,
WithRightToLeftSpaces,
}
impl EndSpaceFit {
fn between_letters(self, line: &Line) -> bool {
self == Self::WithRightToLeftSpaces
&& line
.placed
.iter()
.filter_map(|p| run_glyph(&p.piece))
.any(|glyph| left_to_right(glyph.ch))
}
}
#[derive(Clone, Copy, Debug, Default)]
struct EndSpaces {
width: Length,
count: usize,
shrink: Length,
starts_right_to_left: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Hyphenation {
pub zone: Option<Length>,
pub limit: Option<std::num::NonZeroUsize>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LineBreaking {
pub ends_aligned_text: bool,
pub note_reference_in_word: bool,
pub left_stops_to_line_end: bool,
pub leading_breaks: LeadingBreaks,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LeadingBreaks {
#[default]
None,
First,
All,
}
impl LeadingBreaks {
#[must_use]
pub fn before_first_line(self, leading: usize) -> usize {
match self {
Self::None => 0,
Self::First => leading.min(1),
Self::All => leading,
}
}
}
impl Frame {
#[must_use]
pub fn on_page(&self, first: bool, column: Length, right_to_left: bool) -> (Length, Length) {
let (start, width) = if first {
(self.first_start, self.first_width)
} else {
(self.start, self.width)
};
if right_to_left {
(column - start - width, width)
} else {
(start, width)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Compression {
pub ratio: i64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Halves {
pub count: usize,
pub em: Length,
}
impl Halves {
fn of(pieces: &[Piece]) -> Self {
pieces
.iter()
.fold(Self::default(), |halves, piece| match piece {
Piece::Glyph(g) if closing_mark(g.ch) || opening_mark(g.ch) => Self {
count: halves.count + 1,
em: halves.em.max(g.advance),
},
_ => halves,
})
}
fn and(self, other: Self) -> Self {
Self {
count: self.count + other.count,
em: self.em.max(other.em),
}
}
}
impl Compression {
#[must_use]
pub fn over(self, halves: Halves, (room, gaps): (Length, i64)) -> Length {
if halves.count == 0 || gaps <= 0 || room <= Length::ZERO {
return Length::ZERO;
}
let count = count_factor(halves.count);
(room * (self.ratio * count))
.div_toward_zero(gaps)
.min((halves.em * count).div_toward_zero(2))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct JointGaps {
pub seen: i64,
pub other: i64,
}
impl JointGaps {
#[must_use]
pub fn of(self, joints: JointCounts) -> i64 {
self.seen * count_factor(joints.seen) + self.other * count_factor(joints.other)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Shrink {
pub permille: i64,
pub stretch_permille: i64,
pub natural: (i64, i64),
pub joints: JointGaps,
}
impl Shrink {
#[must_use]
pub fn of_natural(self, end: Length) -> Option<Length> {
let (part, whole) = self.natural;
(whole > 0).then(|| {
end - (end * (whole - part))
.div_round(whole)
.nearest_whole(Length::UNITS_PER_TWIP)
})
}
#[must_use]
pub fn of(self, advance: Length) -> Length {
(advance * self.permille).div_toward_zero(THOUSANDTHS)
}
#[must_use]
pub fn over(
self,
spaces: Length,
(space, word): (Length, Length),
(count, last): (usize, usize),
joints: JointCounts,
) -> Length {
if self.stretch_permille == 0 || count == 0 {
return spaces;
}
let (count, last) = (count_factor(count), count_factor(last));
let gaps = count - last + self.joints.of(joints);
let share = self.stretch_permille * count;
spaces.min(((space + word) * share).div_toward_zero(THOUSANDTHS * gaps + share))
}
}
#[must_use]
pub fn break_lines(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
if !pieces.iter().any(|piece| matches!(piece, Piece::Anchor(_))) {
return break_pieces(pieces, frame);
}
let mut marks = Vec::new();
let mut rest = Vec::with_capacity(pieces.len());
for piece in pieces {
match piece {
Piece::Anchor(drawing) => marks.push((rest.len(), *drawing)),
other => rest.push(*other),
}
}
let mut lines = break_pieces(&rest, frame);
give_marks(&mut lines, &rest, &marks);
lines
}
fn give_marks(lines: &mut [Line], pieces: &[Piece], marks: &[(usize, usize)]) {
let mut next = 0;
let mut spans: Vec<(Vec<usize>, usize)> = Vec::with_capacity(lines.len());
for line in lines.iter() {
let mut find = |found: &dyn Fn(&Piece) -> bool| {
while pieces.get(next).is_some_and(|piece| !found(piece)) {
next += 1;
}
next += 1;
next - 1
};
let placed = line
.placed
.iter()
.map(|placed| find(&|piece| same_piece(piece, &placed.piece)))
.collect();
if line.end != LineEnd::Wrap && line.end != LineEnd::Split {
find(&|piece| {
matches!(
piece,
Piece::LineBreak(_) | Piece::PageBreak | Piece::ColumnBreak
)
});
}
spans.push((placed, next));
}
for &(before, drawing) in marks {
let index = spans
.iter()
.position(|(_, end)| *end > before)
.unwrap_or(spans.len().saturating_sub(1));
let at = spans.get(index).map_or(0, |(placed, _)| {
placed.iter().filter(|&&at| at < before).count()
});
if let Some(line) = lines.get_mut(index) {
line.anchors.push(LineAnchor { at, drawing });
}
}
}
fn same_piece(piece: &Piece, placed: &Piece) -> bool {
match (piece, placed) {
(Piece::Glyph(glyph), Piece::Glyph(shown)) if is_hyphen_point(glyph.ch) => {
Glyph {
ch: shown.ch,
..*glyph
} == *shown
}
_ => piece == placed,
}
}
fn break_pieces(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
let mut breaker = Breaker {
frame,
thai: ThaiText::None,
lines: Vec::new(),
line: Line::default(),
x: Length::ZERO,
shrink: Length::ZERO,
spaces: Length::ZERO,
space_count: 0,
stretching: false,
counted: Length::ZERO,
room: Length::ZERO,
blank: Halves::default(),
hyphen_lines: 0,
ends_at_point: false,
};
let mut i = 0;
while i < pieces.len() {
i = breaker.step(pieces, i);
}
let after_page_break = breaker
.lines
.last()
.is_some_and(|line| line.end == LineEnd::PageBreak);
if !(after_page_break && breaker.line.placed.is_empty()) {
settle_soft_hyphens(&mut breaker.line, false);
breaker.lines.push(breaker.line);
}
breaker.lines
}
struct Breaker<'a> {
frame: &'a Frame,
thai: ThaiText,
lines: Vec<Line>,
line: Line,
x: Length,
shrink: Length,
spaces: Length,
space_count: usize,
stretching: bool,
counted: Length,
room: Length,
blank: Halves,
hyphen_lines: usize,
ends_at_point: bool,
}
impl Breaker<'_> {
fn step(&mut self, pieces: &[Piece], i: usize) -> usize {
match pieces.get(i) {
Some(Piece::LineBreak(face)) => {
self.finish(LineEnd::Break(*face));
i + 1
}
Some(Piece::PageBreak) => {
self.finish(LineEnd::PageBreak);
i + 1
}
Some(Piece::ColumnBreak) => {
self.finish(LineEnd::ColumnBreak);
i + 1
}
Some(piece @ (Piece::Tab(_) | Piece::PositionTab(..))) => {
if matches!(piece, Piece::Tab(_)) && self.stop_past_end() {
self.finish(LineEnd::Wrap);
}
self.place_tab(*piece, pieces.get(i + 1..).unwrap_or(&[]));
i + 1
}
Some(
piece @ (Piece::Note(_)
| Piece::NoteMarkEnd
| Piece::Comment(_)
| Piece::Strut(_)
| Piece::Clear),
) => {
self.push(*piece, Length::ZERO);
i + 1
}
Some(
Piece::Glyph(_)
| Piece::Shift(_)
| Piece::Advance(_)
| Piece::Bar { .. }
| Piece::Vinculum { .. }
| Piece::Diagonal { .. }
| Piece::Object { .. }
| Piece::Rule { .. }
| Piece::CheckBox { .. },
) => self.place_word(pieces, i),
Some(Piece::Anchor(_)) | None => i + 1,
}
}
fn finish(&mut self, end: LineEnd) {
let mut line = std::mem::take(&mut self.line);
settle_soft_hyphens(&mut line, false);
line.end = end;
self.lines.push(line);
self.x = Length::ZERO;
self.thai = ThaiText::None;
self.shrink = Length::ZERO;
self.spaces = Length::ZERO;
self.space_count = 0;
self.stretching = false;
self.counted = Length::ZERO;
self.room = Length::ZERO;
self.blank = Halves::default();
self.hyphen_lines = if std::mem::take(&mut self.ends_at_point) {
self.hyphen_lines + 1
} else {
0
};
}
fn width(&self) -> Length {
if self.on_first_line() {
self.frame.first_width
} else {
self.frame.width
}
}
fn start(&self) -> Length {
if self.on_first_line() {
self.frame.first_start
} else {
self.frame.start
}
}
fn on_first_line(&self) -> bool {
let before = self
.frame
.breaking
.leading_breaks
.before_first_line(self.lines.len());
self.lines.len() == before && self.lines.iter().all(Line::holds_only_page_break)
}
fn stop_past_end(&self) -> bool {
let absolute = self.start() + self.x;
let end = self.start() + self.width();
let (stop, default) = self.frame.tabs.next_stop(absolute);
let past = if absolute <= end {
stop.position > end
} else {
self.room == Length::ZERO
};
let moves = default || self.left_stop_to_line_end(stop);
moves && !self.line.placed.is_empty() && past
}
fn stop_or_line_end(&self, piece: &Piece, stop: TabStop, end: Length) -> TabStop {
if matches!(piece, Piece::Tab(_)) && stop.position > end && self.left_stop_to_line_end(stop)
{
TabStop {
position: end,
..stop
}
} else {
stop
}
}
fn left_stop_to_line_end(&self, stop: TabStop) -> bool {
stop.kind == TabKind::Left
&& self.frame.tabs.is_custom(stop)
&& self.frame.breaking.left_stops_to_line_end
}
fn place_tab(&mut self, piece: Piece, after: &[Piece]) {
let absolute = self.start() + self.x;
let stop = match piece {
Piece::PositionTab(_, stop) => stop,
_ => self.frame.tabs.next(absolute),
};
let end = self.start() + self.width();
let stop = self.stop_or_line_end(&piece, stop, end);
let gap = stop.position - absolute;
self.room = self.room.max(stop.position - end);
let at_stop = match stop.kind {
TabKind::Right => gap - following_width(after, None),
TabKind::Center => gap - following_width(after, None).div_toward_zero(2),
TabKind::Decimal => gap - following_width(after, Some('.')),
TabKind::Left => gap,
};
let advance = match stop.kind {
TabKind::Right | TabKind::Center | TabKind::Decimal
if self.frame.breaking.ends_aligned_text =>
{
let width = following_width(after, None);
if stop.position >= end && !self.frame.limits_past_end {
let advance = at_stop.max(Length::ZERO);
self.room = self.room.max(absolute + advance + width - end);
advance
} else {
let limit = if stop.position > end && stop.position <= self.frame.area_width {
self.frame.area_width
} else {
end
};
let advance = at_stop.min(limit - absolute - width).max(Length::ZERO);
self.room = self.room.max((absolute + advance + width).min(limit) - end);
advance
}
}
_ => at_stop,
};
self.push(piece, advance.max(Length::ZERO));
if let Some(placed) = self.line.placed.last_mut() {
placed.leader = stop.leader;
placed.tab = Some(stop.kind);
}
}
fn place_word(&mut self, pieces: &[Piece], i: usize) -> usize {
let end = word_end(pieces, i, self.frame);
let word = pieces.get(i..end).unwrap_or(&[]);
let (_, visible) = widths(word);
let ends = self.fitted_end_spaces(word, pieces.get(end));
let visible = visible + ends.width;
if self.thai != ThaiText::OnLine {
self.thai = if word.iter().any(is_thai) {
ThaiText::InWord
} else {
ThaiText::None
};
}
let fit = self.fit_ending(visible, self.punctuation_over(word), ends);
let room = self
.shrink
.max(self.frame.shrink.of_natural(self.x).unwrap_or(Length::ZERO));
let spaces = word.iter().all(is_space) && self.x <= self.width() + room;
if fit.end > fit.width + fit.over
&& !spaces
&& let Some(point) = self.hyphen_point(word)
{
return i + self.place_to_point(word, point, fit);
}
if fit.end > fit.width + fit.over && !self.line.placed.is_empty() && !spaces {
let tabs = self.take_trailing_tabs();
settle_soft_hyphens(&mut self.line, tabs.is_empty());
self.line.wrapped = Some(fit);
self.line.would_hang = tabs.is_empty() && self.would_hang(word);
self.finish(LineEnd::Wrap);
for tab in tabs {
self.place_tab(tab, pieces.get(i..).unwrap_or(&[]));
}
}
if self.x + visible > self.width() && self.line.placed.is_empty() {
return i + self.place_split(word);
}
self.line.kept = Some(self.fit(visible));
for piece in word {
self.push(*piece, advance(piece));
}
end
}
fn fitted_end_spaces(&self, word: &[Piece], next: Option<&Piece>) -> EndSpaces {
if self.frame.end_space_fit == EndSpaceFit::WithoutSpaces
|| !self.line.holds_left_to_right_text()
{
return EndSpaces::default();
}
let Some(last) = word.iter().rposition(|piece| !is_space(piece)) else {
return EndSpaces::default();
};
let letter = |piece: Option<&Piece>| {
piece
.and_then(run_glyph)
.is_some_and(|glyph| right_to_left(glyph.ch))
};
let between = self.frame.end_space_fit.between_letters(&self.line)
&& letter(word.get(last))
&& letter(next);
let start = EndSpaces {
starts_right_to_left: letter(word.first()),
..EndSpaces::default()
};
word.iter()
.skip(last + 1)
.take_while(|piece| is_space(piece) && (between || run_rtl(piece) == Some(true)))
.fold(start, |ends, piece| EndSpaces {
width: ends.width + advance(piece) + counted(piece),
count: ends.count + 1,
shrink: ends.shrink + self.frame.shrink.of(advance(piece)),
..ends
})
}
fn hyphen_point(&self, word: &[Piece]) -> Option<usize> {
let rules = self.frame.hyphenation?;
if rules
.limit
.is_some_and(|limit| self.hyphen_lines >= limit.get())
{
return None;
}
if rules.zone.is_some_and(|zone| self.width() - self.x <= zone) {
return None;
}
(0..word.len()).rev().find(|&k| {
let Some(part) = word.get(..=k).filter(
|part| matches!(part.last(), Some(Piece::Glyph(g)) if g.ch == AUTOMATIC_HYPHEN),
) else {
return false;
};
let (_, visible) = widths(part);
let fit = self.fit_with(visible, self.punctuation_over(part));
fit.end <= fit.width + fit.over
})
}
fn place_to_point(&mut self, word: &[Piece], point: usize, wrapped: Fit) -> usize {
let part = word.get(..=point).unwrap_or(&[]);
let (_, visible) = widths(part);
self.line.kept = Some(self.fit_with(visible, self.punctuation_over(part)));
for piece in part {
self.push(*piece, advance(piece));
}
settle_soft_hyphens(&mut self.line, true);
self.line.wrapped = Some(wrapped);
self.ends_at_point = true;
self.finish(LineEnd::Wrap);
part.len()
}
fn would_hang(&self, word: &[Piece]) -> bool {
let Some(kinsoku) = self.frame.kinsoku else {
return false;
};
let Some(last) = word.iter().rposition(|piece| !is_space(piece)) else {
return false;
};
let (Some(Piece::Glyph(mark)), Some(rest)) = (word.get(last), word.get(..last)) else {
return false;
};
if !kinsoku.hangs(mark.ch) {
return false;
}
let (_, visible) = widths(rest);
let fit = self.fit_with(visible, self.punctuation_over(rest));
fit.end <= fit.width + fit.over
}
fn fit(&self, word: Length) -> Fit {
self.fit_with(word, Length::ZERO)
}
fn punctuation_over(&self, word: &[Piece]) -> Length {
let Some(compression) = self.frame.punctuation else {
return Length::ZERO;
};
compression.over(self.blank.and(Halves::of(word)), self.stretch())
}
fn stretch(&self) -> (Length, i64) {
let placed = &self.line.placed;
let count = |pick: fn(&Piece) -> bool| {
i64::try_from(placed.iter().filter(|p| pick(&p.piece)).count()).unwrap_or(0)
};
let spaces = count(is_space);
let gaps = if spaces > 0 {
spaces
} else {
count(|p| matches!(p, Piece::Glyph(_))) - 1
};
(self.width() - self.x, gaps)
}
fn fit_with(&self, word: Length, punctuation: Length) -> Fit {
self.fit_ending(word, punctuation, EndSpaces::default())
}
fn fit_ending(&self, word: Length, punctuation: Length, ends: EndSpaces) -> Fit {
let last: Vec<&Placed> = self
.line
.placed
.iter()
.rev()
.take_while(|p| self.stretching && (is_space(&p.piece) || is_operator_space(&p.piece)))
.collect();
let space: Length = last.iter().map(|p| p.advance).sum();
let last_space_count = last.iter().filter(|p| is_space(&p.piece)).count();
let end = self.x + self.counted + word;
let kept = self.frame.thai_keeps_spaces && self.thai != ThaiText::None;
let over = if kept {
Length::ZERO
} else {
self.frame
.shrink
.of_natural(end)
.unwrap_or_else(|| self.shrink_over(&last, (space, word), last_space_count, ends))
};
Fit {
width: self.width(),
end,
word,
spaces: self.spaces,
space,
space_count: self.space_count,
last_space_count,
room: self.room,
over: over + self.room + punctuation,
shrinks: !kept && (self.frame.shrink.permille > 0 || self.frame.shrink.natural.1 > 0),
}
}
fn shrink_over(
&self,
last: &[&Placed],
(space, word): (Length, Length),
last_count: usize,
ends: EndSpaces,
) -> Length {
let rtl_before = last.iter().all(|p| run_rtl(&p.piece) == Some(true));
let letters_before = self.frame.end_space_fit.between_letters(&self.line)
&& ends.starts_right_to_left
&& self
.line
.placed
.iter()
.rev()
.find(|p| !is_space(&p.piece))
.and_then(|p| run_glyph(&p.piece))
.is_some_and(|glyph| right_to_left(glyph.ch));
let kept_before = self.frame.end_space_fit != EndSpaceFit::WithoutSpaces
&& (rtl_before || letters_before)
&& !last.is_empty()
&& self.line.holds_left_to_right_text();
let (space, hanging) = if kept_before {
(Length::ZERO, 0)
} else {
(space, last_count)
};
let joints = if self.frame.shrink.joints == JointGaps::default() {
JointCounts::default()
} else {
joints::joint_counts(&self.line.placed)
};
self.frame.shrink.over(
self.shrink + ends.shrink,
(space, word),
(self.space_count + ends.count, hanging + ends.count),
joints,
)
}
fn take_trailing_tabs(&mut self) -> Vec<Piece> {
let placed = &self.line.placed;
let count = placed
.iter()
.rev()
.take_while(|p| matches!(p.piece, Piece::Tab(_) | Piece::PositionTab(..)))
.count();
if count == placed.len() {
return Vec::new();
}
let tabs = self.line.placed.split_off(placed.len() - count);
if let Some(first) = tabs.first() {
self.x = first.x;
}
tabs.into_iter().map(|p| p.piece).collect()
}
fn place_split(&mut self, word: &[Piece]) -> usize {
let mut placed = 0;
for piece in word {
let a = advance(piece);
if placed > 0 && self.x + self.counted + a + counted(piece) > self.width() {
break;
}
self.push(*piece, a);
placed += 1;
}
if placed < word.len() {
self.finish(LineEnd::Split);
}
placed
}
fn push(&mut self, piece: Piece, advance: Length) {
self.line.placed.push(Placed {
piece,
x: self.x,
advance,
leader: None,
tab: None,
});
self.x += advance;
if is_thai(&piece) {
self.thai = ThaiText::OnLine;
}
if matches!(piece, Piece::Tab(_) | Piece::PositionTab(..)) {
self.shrink = Length::ZERO;
self.spaces = Length::ZERO;
self.space_count = 0;
self.stretching = false;
self.counted = Length::ZERO;
} else if !is_space(&piece) {
self.stretching = true;
} else if self.stretching {
self.shrink += self.frame.shrink.of(advance);
self.spaces += advance;
self.space_count += 1;
}
self.counted += counted(&piece);
self.blank = self.blank.and(Halves::of(&[piece]));
}
}
fn word_end(pieces: &[Piece], i: usize, frame: &Frame) -> usize {
let mut j = i;
loop {
match pieces.get(j) {
Some(Piece::Glyph(g))
if g.ch != ' ' || matches!(g.space, SpaceKind::Equation | SpaceKind::Assembly) =>
{
j += 1;
if (g.space == SpaceKind::Operator && !pieces.get(j).is_some_and(is_operator_space))
|| ends_word_after(g.ch, pieces.get(j), frame.kinsoku)
{
return j;
}
}
Some(
Piece::Shift(_)
| Piece::Bar { .. }
| Piece::Vinculum { .. }
| Piece::Diagonal { .. }
| Piece::NoteMarkEnd,
) => j += 1,
Some(
Piece::Object {
joins_before: true, ..
}
| Piece::Advance(_),
) => return j + 1,
Some(Piece::Note(_)) if frame.breaking.note_reference_in_word => {
j += 1;
let before = j.checked_sub(2).and_then(|k| pieces.get(k));
if let Some(Piece::Glyph(g)) = before
&& ends_word_after(g.ch, pieces.get(j), frame.kinsoku)
{
return j;
}
}
Some(_) if frame.joined_spaces && joins(pieces, (i, j)) => j = spaces_end(pieces, j),
_ => break,
}
}
spaces_end(pieces, j).max(i + 1)
}
#[must_use]
pub(crate) fn widest_word(pieces: &[Piece], frame: &Frame) -> Length {
let mut widest = Length::ZERO;
let mut start = 0;
while start < pieces.len() {
let end = word_end(pieces, start, frame);
widest = widest.max(widths(pieces.get(start..end).unwrap_or_default()).1);
start = end;
}
widest
}
fn spaces_end(pieces: &[Piece], mut j: usize) -> usize {
while matches!(pieces.get(j), Some(p) if is_space(p)) {
j += 1;
}
j
}
fn joins(pieces: &[Piece], (i, j): (usize, usize)) -> bool {
let no_break =
|piece: Option<&Piece>| matches!(piece, Some(Piece::Glyph(g)) if g.ch == NO_BREAK_SPACE);
let before = j > i && no_break(j.checked_sub(1).and_then(|k| pieces.get(k)));
pieces.get(j).is_some_and(is_space) && (before || no_break(pieces.get(spaces_end(pieces, j))))
}
fn ends_word_after(ch: char, next: Option<&Piece>, kinsoku: Option<Kinsoku>) -> bool {
if matches!(ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | SOFT_HYPHEN) {
return true;
}
matches!(next, Some(Piece::Glyph(next)) if next.ch != ' ' && breaks_between(ch, next.ch, kinsoku))
}
const fn is_hyphen_point(ch: char) -> bool {
matches!(ch, SOFT_HYPHEN | AUTOMATIC_HYPHEN)
}
fn widths(word: &[Piece]) -> (Length, Length) {
let total: Length = word.iter().map(|p| advance(p) + counted(p)).sum();
let trailing: Length = word
.iter()
.rev()
.take_while(|p| is_space(p) || is_operator_space(p))
.map(|p| advance(p) + counted(p))
.sum();
let hyphen = match word.last() {
Some(Piece::Glyph(g)) if is_hyphen_point(g.ch) => g.advance,
_ => Length::ZERO,
};
(total, total - trailing + hyphen)
}
fn settle_soft_hyphens(line: &mut Line, wrapped: bool) {
if wrapped
&& let Some(last) = line.placed.last_mut()
&& let Piece::Glyph(g) = &mut last.piece
&& is_hyphen_point(g.ch)
{
let hyphen = if g.ch == AUTOMATIC_HYPHEN {
g.ch = LINE_END_HYPHEN;
EndHyphen::Automatic
} else {
g.ch = '-';
EndHyphen::Soft
};
last.advance = g.advance;
line.hyphen = Some(hyphen);
}
line.placed
.retain(|p| !matches!(p.piece, Piece::Glyph(g) if is_hyphen_point(g.ch)));
}
pub(crate) fn following_width(after: &[Piece], decimal: Option<char>) -> Length {
let mut total = Length::ZERO;
let mut visible = Length::ZERO;
for piece in after {
match piece {
Piece::Glyph(glyph) => {
if Some(glyph.ch) == decimal {
return total;
}
total += glyph.advance + glyph.counted;
if glyph.ch != ' ' {
visible = total;
}
}
Piece::Object { width, .. } => {
total += *width;
visible = total;
}
_ => break,
}
}
if decimal.is_some() { total } else { visible }
}
const fn counted(piece: &Piece) -> Length {
match piece {
Piece::Glyph(g) if !is_hyphen_point(g.ch) => g.counted,
_ => Length::ZERO,
}
}
pub(crate) const fn advance(piece: &Piece) -> Length {
match piece {
Piece::Glyph(g) if is_hyphen_point(g.ch) => Length::ZERO,
Piece::Glyph(g) => g.advance,
Piece::Shift(length) | Piece::Advance(length) => *length,
Piece::Object { width, .. } | Piece::Rule { width, .. } | Piece::CheckBox { width, .. } => {
*width
}
Piece::Bar { .. }
| Piece::Vinculum { .. }
| Piece::Diagonal { .. }
| Piece::Tab(_)
| Piece::PositionTab(..)
| Piece::LineBreak(_)
| Piece::PageBreak
| Piece::ColumnBreak
| Piece::Note(_)
| Piece::NoteMarkEnd
| Piece::Comment(_)
| Piece::Anchor(_)
| Piece::Strut(_)
| Piece::Clear => Length::ZERO,
}
}
#[must_use]
pub fn closing_mark(ch: char) -> bool {
matches!(
ch,
'\u{3001}'
| '\u{3002}'
| '\u{FF0C}'
| '\u{FF0E}'
| '\u{FF1A}'
| '\u{FF1B}'
| '\u{FF01}'
| '\u{300D}'
| '\u{300F}'
| '\u{FF09}'
| '\u{3011}'
| '\u{3015}'
| '\u{3009}'
| '\u{300B}'
| '\u{FF5D}'
| '\u{FF3D}'
)
}
#[must_use]
pub const fn centered_mark(ch: char) -> bool {
matches!(
ch,
'\u{FF0C}' | '\u{3001}' | '\u{3002}' | '\u{FF1B}' | '\u{FF1A}'
)
}
#[must_use]
pub fn opening_mark(ch: char) -> bool {
matches!(
ch,
'\u{300C}'
| '\u{300E}'
| '\u{FF08}'
| '\u{3010}'
| '\u{3014}'
| '\u{3008}'
| '\u{300A}'
| '\u{FF5B}'
| '\u{FF3B}'
)
}
#[must_use]
pub fn kerned_pair(left: char, right: char, script: Option<crate::props::EastAsianScript>) -> bool {
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Opening,
Closing,
Middle,
}
let kind = |ch: char| -> Option<Kind> {
use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
if opening_mark(ch) {
return Some(Kind::Opening);
}
if matches!(
ch,
'\u{300D}'
| '\u{300F}'
| '\u{FF09}'
| '\u{3011}'
| '\u{3015}'
| '\u{3009}'
| '\u{300B}'
| '\u{FF5D}'
| '\u{FF3D}'
) {
return Some(Kind::Closing);
}
match (ch, script) {
('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Simplified | Japanese))
| ('\u{FF01}' | '\u{FF1A}' | '\u{FF1B}', Some(Simplified)) => Some(Kind::Closing),
('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Traditional))
| ('\u{FF1A}' | '\u{FF1B}', Some(Japanese | Traditional))
| ('\u{30FB}', Some(Japanese)) => Some(Kind::Middle),
_ => None,
}
};
matches!(
(kind(left), kind(right)),
(Some(Kind::Closing), Some(_)) | (Some(_), Some(Kind::Opening))
)
}
#[must_use]
pub fn is_space(piece: &Piece) -> bool {
matches!(piece, Piece::Glyph(g) if g.ch == ' ' && g.space == SpaceKind::Free)
}
#[must_use]
pub fn stretches(piece: &Piece) -> bool {
is_space(piece) || matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::NoBreak)
}
fn is_operator_space(piece: &Piece) -> bool {
matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::Operator)
}
pub(crate) const fn run_glyph(piece: &Piece) -> Option<&Glyph> {
match piece {
Piece::Glyph(glyph) if !glyph.label => Some(glyph),
_ => None,
}
}
pub(crate) fn run_rtl(piece: &Piece) -> Option<bool> {
run_glyph(piece).map(|glyph| glyph.direction.class().is_some())
}
pub(crate) fn right_to_left(ch: char) -> bool {
matches!(
unicode_bidi::bidi_class(ch),
unicode_bidi::BidiClass::R | unicode_bidi::BidiClass::AL
)
}
fn left_to_right(ch: char) -> bool {
unicode_bidi::bidi_class(ch) == unicode_bidi::BidiClass::L
}
#[cfg(test)]
mod tests {
use super::{
EndHyphen, EndSpaceFit, Frame, Hyphenation, JointCounts, JointGaps, LeadingBreaks, Line,
LineBreaking, LineEnd, NoteNumber, Piece, Shrink, break_lines, following_width, is_space,
};
use crate::props::{TabKind, TabStop};
use crate::quirks::{AlignedTabOverrun, LeftStopPastEnd, NoteReferenceBreak};
use crate::tabs::Tabs;
use crate::text::AUTOMATIC_HYPHEN;
use crate::text::{FaceIndex, Glyph, SpaceKind};
use f_office_units::Length;
#[test]
fn keeps_a_footnote_s_place_from_zero() {
assert_eq!(NoteNumber::of_index(4).index(), 4);
}
fn glyphs(text: &str) -> Vec<Piece> {
text.chars()
.map(|ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)))
.collect()
}
fn marked_from(text: &str, first: usize) -> Vec<Piece> {
let mut pieces = glyphs(text);
for piece in pieces.iter_mut().skip(first) {
if let Piece::Glyph(glyph) = piece {
glyph.direction = crate::text::RunDirection::of(true, None);
}
}
pieces
}
#[test]
fn fits_a_word_with_its_rtl_end_spaces_beside_left_to_right_text() {
let mixed = marked_from("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 3);
let fitted = |width| Frame {
end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
..frame(width)
};
assert_eq!(
texts(&break_lines(&mixed, &frame(85))),
["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
);
assert_eq!(
texts(&break_lines(&mixed, &fitted(85))),
["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
);
let plain = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
assert_eq!(
texts(&break_lines(&plain, &fitted(85))),
["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
);
let latin_after = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} cd");
assert_eq!(
texts(&break_lines(&latin_after, &fitted(85))),
["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "cd"]
);
let pure = marked_from("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 0);
assert_eq!(
texts(&break_lines(&pure, &fitted(55))),
texts(&break_lines(&pure, &frame(55)))
);
let plain_only = glyphs("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
assert_eq!(
texts(&break_lines(&plain_only, &fitted(55))),
["\u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
);
}
#[test]
fn counts_kept_rtl_spaces_as_spaces_of_a_justified_line() {
let mixed = marked_from(
"ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
12,
);
let justified = |width| Frame {
shrink: Shrink {
permille: 250,
stretch_permille: 500,
natural: (0, 0),
joints: JointGaps::default(),
},
end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
..frame(width)
};
let fitted = [
"ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} ",
"\u{5d4}\u{5d5}",
];
let wrapped = [
"ab cd ef gh \u{5d0}\u{5d1} ",
"\u{5d2}\u{5d3} \u{5d4}\u{5d5}",
];
assert_eq!(texts(&break_lines(&mixed, &justified(169))), fitted);
assert_eq!(texts(&break_lines(&mixed, &justified(168))), wrapped);
let plain = glyphs("ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
assert_eq!(texts(&break_lines(&plain, &justified(169))), fitted);
assert_eq!(texts(&break_lines(&plain, &justified(168))), wrapped);
let only = glyphs(
"\u{5e9}\u{5ea} \u{5e7}\u{5e8} \u{5e6}\u{5e4} \u{5e2}\u{5e1} \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
);
for width in 160..180 {
let hanging = Frame {
end_space_fit: EndSpaceFit::WithoutSpaces,
..justified(width)
};
assert_eq!(
texts(&break_lines(&only, &justified(width))),
texts(&break_lines(&only, &hanging)),
"{width}"
);
}
}
fn frame(width: i64) -> Frame {
Frame {
first_width: Length::from_units(width),
width: Length::from_units(width),
area_width: Length::from_units(width),
first_start: Length::ZERO,
start: Length::ZERO,
tabs: Tabs::new([], Length::from_units(25), None),
shrink: Shrink::default(),
thai_keeps_spaces: false,
end_space_fit: EndSpaceFit::WithoutSpaces,
kinsoku: None,
joined_spaces: false,
breaking: LineBreaking::default(),
limits_past_end: true,
punctuation: None,
hyphenation: None,
}
}
fn texts(lines: &[Line]) -> Vec<String> {
lines
.iter()
.map(|line| {
line.placed
.iter()
.map(|p| match p.piece {
Piece::Glyph(g) => g.ch,
_ => '|',
})
.collect()
})
.collect()
}
#[test]
fn anchor_marks_change_no_line_and_go_to_the_line_of_the_piece_after_them() {
let text = glyphs("ab cd ef");
let mut marked = text.clone();
for (at, drawing) in [(8, 3), (6, 2), (4, 1), (0, 0)] {
marked.insert(at, Piece::Anchor(drawing));
}
for width in [25, 45, 55, 100] {
assert_eq!(
texts(&break_lines(&marked, &frame(width))),
texts(&break_lines(&text, &frame(width))),
"{width}"
);
}
let anchors = |lines: &[Line]| -> Vec<Vec<(usize, usize)>> {
lines
.iter()
.map(|line| line.anchors.iter().map(|a| (a.at, a.drawing)).collect())
.collect()
};
let lines = break_lines(&marked, &frame(55));
assert_eq!(texts(&lines), ["ab cd ", "ef"]);
assert_eq!(
anchors(&lines),
[vec![(0, 0), (4, 1)], vec![(0, 2), (2, 3)]]
);
let again = break_lines(&Line::pieces(&lines), &frame(100));
assert_eq!(anchors(&again), [vec![(0, 0), (4, 1), (6, 2), (8, 3)]]);
}
#[test]
fn a_footnote_reference_as_text_keeps_the_closing_parenthesis_after_it_on_its_line() {
let with = |note_reference_break| Frame {
breaking: LineBreaking {
note_reference_in_word: note_reference_break == NoteReferenceBreak::AsText,
..LineBreaking::default()
},
..frame(65)
};
let mut pieces = glyphs("ab (c1");
pieces.push(Piece::Note(NoteNumber::of_index(0)));
pieces.extend(glyphs(") d"));
assert_eq!(
texts(&break_lines(&pieces, &with(NoteReferenceBreak::After))),
["ab (c1|", ") d"]
);
assert_eq!(
texts(&break_lines(&pieces, &with(NoteReferenceBreak::AsText))),
["ab ", "(c1|) d"]
);
let mut spaced = glyphs("ab c1");
spaced.push(Piece::Note(NoteNumber::of_index(0)));
spaced.extend(glyphs(" de"));
assert_eq!(
texts(&break_lines(&spaced, &with(NoteReferenceBreak::AsText))),
["ab c1| ", "de"]
);
}
#[test]
fn a_joined_space_run_keeps_the_words_on_both_of_its_sides_on_one_line() {
let with = |joined_spaces| Frame {
joined_spaces,
..frame(70)
};
for (text, apart, together) in [
(
"aa bb\u{a0} cc",
["aa bb\u{a0} ", "cc"],
["aa ", "bb\u{a0} cc"],
),
(
"aa bb \u{a0}cc",
["aa bb ", "\u{a0}cc"],
["aa ", "bb \u{a0}cc"],
),
(
"aa b \u{a0} cc",
["aa b \u{a0} ", "cc"],
["aa ", "b \u{a0} cc"],
),
("aa bb cc", ["aa bb ", "cc"], ["aa bb ", "cc"]),
(
"aa bb\u{a0}cc",
["aa ", "bb\u{a0}cc"],
["aa ", "bb\u{a0}cc"],
),
] {
assert_eq!(texts(&break_lines(&glyphs(text), &with(false))), apart);
assert_eq!(texts(&break_lines(&glyphs(text), &with(true))), together);
}
}
#[test]
fn breaks_east_asian_text_between_characters_with_kinsoku() {
use crate::kinsoku::Kinsoku;
use crate::props::EastAsianScript;
let with = |kinsoku: Option<Kinsoku>| Frame {
kinsoku,
..frame(40)
};
let text = glyphs("ab 日本語、文字");
let latin = break_lines(&text, &with(None));
assert_eq!(texts(&latin), vec!["ab ", "日本語、", "文字"]);
let japanese = Some(Kinsoku::of(EastAsianScript::Japanese));
let lines = break_lines(&text, &with(japanese));
assert_eq!(texts(&lines), vec!["ab 日", "本語、文", "字"]);
let mark = glyphs("日本語文、字");
let kept = break_lines(&mark, &with(japanese));
assert_eq!(texts(&kept), vec!["日本語", "文、字"]);
let free = break_lines(&mark, &with(Some(Kinsoku::FREE)));
assert_eq!(texts(&free), vec!["日本語文", "、字"]);
}
#[test]
fn marks_a_line_before_a_word_that_fits_without_its_hanging_mark() {
use crate::kinsoku::Kinsoku;
use crate::props::EastAsianScript;
let simplified = Kinsoku::of(EastAsianScript::Simplified);
let with = |kinsoku: Kinsoku| Frame {
kinsoku: Some(kinsoku),
..frame(40)
};
let hangs = |text: &str, kinsoku: Kinsoku| {
let lines = break_lines(&glyphs(text), &with(kinsoku));
(
texts(&lines),
lines.iter().map(|l| l.would_hang).collect::<Vec<_>>(),
)
};
let lines = |a: &[&str]| a.iter().map(|t| (*t).to_owned()).collect::<Vec<_>>();
assert_eq!(
hangs("一二三四,五", simplified),
(lines(&["一二三", "四,五"]), vec![true, false])
);
assert_eq!(
hangs("一(ab)", simplified),
(lines(&["一", "(ab)"]), vec![true, false])
);
let no = |text: &str, kinsoku: Kinsoku| {
let (_, hung) = hangs(text, kinsoku);
assert!(hung.iter().all(|hang| !hang), "{text}");
};
no("一二三四,五", simplified.without_hanging());
no("一二三四…五", simplified);
no("一二三四五,", simplified);
no("一二三四,五", Kinsoku::FREE);
}
#[test]
fn breaks_after_spaces_and_hyphens() {
let lines = break_lines(&glyphs("aa bb-cc dd"), &frame(60));
assert_eq!(texts(&lines), vec!["aa bb-", "cc dd"]);
let narrow = break_lines(&glyphs("aa bb-cc dd"), &frame(50));
assert_eq!(texts(&narrow), vec!["aa ", "bb-cc ", "dd"]);
assert_eq!(lines[0].width(), Length::from_units(60));
assert_eq!(lines[1].last_visible(), Some(4));
}
#[test]
fn breaks_an_equation_after_the_space_of_an_operator_which_hangs() {
let pieces: Vec<Piece> = glyphs("a+\u{a0}b+\u{a0}cd")
.into_iter()
.map(|piece| match piece {
Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
g.space = SpaceKind::Operator;
Piece::Glyph(g)
}
other => other,
})
.collect();
let lines = break_lines(&pieces, &frame(50));
assert_eq!(texts(&lines), vec!["a+\u{a0}b+\u{a0}", "cd"]);
assert_eq!(lines[0].last_visible(), Some(4));
assert!(!is_space(&pieces[2]));
}
#[test]
fn a_justified_line_counts_the_operator_space_before_a_term_in_its_room() {
let pieces: Vec<Piece> = glyphs("a b c d+\u{a0}e+\u{a0}f")
.into_iter()
.map(|piece| match piece {
Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
g.space = SpaceKind::Operator;
Piece::Glyph(g)
}
other => other,
})
.collect();
let mut f = frame(101);
f.shrink = Shrink {
permille: 500,
stretch_permille: 500,
natural: (0, 0),
joints: JointGaps::default(),
};
assert_eq!(
texts(&break_lines(&pieces, &f)),
vec!["a b c d+\u{a0}e+\u{a0}", "f"]
);
f.width = Length::from_units(99);
f.first_width = f.width;
assert_eq!(
texts(&break_lines(&pieces, &f)),
vec!["a b c d+\u{a0}", "e+\u{a0}f"]
);
}
#[test]
fn hangs_the_whole_space_after_a_relation() {
let pieces: Vec<Piece> = glyphs("a=\u{200a}\u{a0}b=\u{200a}\u{a0}cd")
.into_iter()
.map(|piece| match piece {
Piece::Glyph(mut g) if matches!(g.ch, '\u{200a}' | '\u{a0}') => {
g.space = SpaceKind::Operator;
Piece::Glyph(g)
}
other => other,
})
.collect();
let lines = break_lines(&pieces, &frame(60));
assert_eq!(
texts(&lines),
vec!["a=\u{200a}\u{a0}b=\u{200a}\u{a0}", "cd"]
);
assert_eq!(lines[0].last_visible(), Some(5));
}
#[test]
fn keeps_the_numbers_of_its_decisions() {
let lines = break_lines(&glyphs("aa bb cc"), &frame(50));
assert_eq!(texts(&lines), vec!["aa bb ", "cc"]);
let u = Length::from_units;
let kept = lines[0].kept.unwrap();
assert_eq!(
(kept.end, kept.word, kept.spaces, kept.space),
(u(50), u(20), u(10), u(10))
);
let wrapped = lines[0].wrapped.unwrap();
assert_eq!(
(wrapped.width, wrapped.end, wrapped.spaces),
(u(50), u(80), u(20))
);
assert_eq!((wrapped.over, wrapped.shrinks), (Length::ZERO, false));
assert_eq!(lines[1].kept.unwrap().end, u(20));
assert_eq!(lines[1].wrapped, None);
}
#[test]
fn shows_a_soft_hyphen_only_where_a_line_ends() {
let text = "aa bb\u{E0AD}cc dd";
let wide = break_lines(&glyphs(text), &frame(70));
assert_eq!(texts(&wide), vec!["aa bbcc ", "dd"]);
assert_eq!(wide[0].placed[5].x, Length::from_units(50));
let narrow = break_lines(&glyphs(text), &frame(60));
assert_eq!(texts(&narrow), vec!["aa bb-", "cc dd"]);
assert_eq!(narrow[0].width(), Length::from_units(60));
let tight = break_lines(&glyphs(text), &frame(50));
assert_eq!(texts(&tight), vec!["aa ", "bbcc ", "dd"]);
let end = break_lines(&glyphs("aa\u{E0AD}"), &frame(60));
assert_eq!(texts(&end), vec!["aa"]);
let literal = break_lines(&glyphs("aa bb\u{AD}cc dd"), &frame(70));
assert_eq!(texts(&literal), vec!["aa ", "bb\u{AD}cc ", "dd"]);
}
#[test]
fn marks_the_line_that_ends_at_a_soft_hyphen() {
let hyphens = |text: &str, width| {
let lines = break_lines(&glyphs(text), &frame(width));
lines.iter().map(|line| line.hyphen).collect::<Vec<_>>()
};
assert_eq!(hyphens("aa bb\u{E0AD}cc dd", 70), [None, None]);
assert_eq!(
hyphens("aa bb\u{E0AD}cc dd", 60),
[Some(EndHyphen::Soft), None]
);
assert_eq!(hyphens("aa\u{E0AD}", 60), [None]);
}
#[test]
fn breaks_after_the_move_of_an_advance_field_but_not_before_it() {
let moved = |before: &str, after: &str| {
let mut pieces = glyphs(before);
pieces.push(Piece::Advance(Length::from_units(30)));
pieces.extend(glyphs(after));
pieces
};
let lines = break_lines(&moved("aa", "bb cc"), &frame(60));
assert_eq!(texts(&lines), vec!["aa|", "bb cc"]);
let lines = break_lines(&moved("a aa", "bb"), &frame(50));
assert_eq!(texts(&lines), vec!["a ", "aa|", "bb"]);
}
fn with_points(text: &str) -> Vec<Piece> {
glyphs(&text.replace('=', &AUTOMATIC_HYPHEN.to_string()))
}
fn hyphenated_texts(lines: &[Line]) -> Vec<String> {
texts(lines)
.into_iter()
.map(|text| text.replace(super::LINE_END_HYPHEN, "-"))
.collect()
}
#[test]
fn ends_a_line_at_the_last_automatic_point_that_fits() {
let hyphenated = |rules| Frame {
hyphenation: Some(rules),
..frame(120)
};
let pieces = with_points("aaaa hy=phen=ation");
let lines = break_lines(&pieces, &hyphenated(Hyphenation::default()));
assert_eq!(hyphenated_texts(&lines), ["aaaa hyphen-", "ation"]);
assert_eq!(lines[0].hyphen, Some(EndHyphen::Automatic));
assert_eq!(
hyphenated_texts(&break_lines(&pieces, &frame(120))),
["aaaa ", "hyphenation"]
);
let zone = |units| Hyphenation {
zone: Some(Length::from_units(units)),
limit: None,
};
assert_eq!(
hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(70)))),
["aaaa ", "hyphenation"]
);
assert_eq!(
hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(69)))),
["aaaa hyphen-", "ation"]
);
}
#[test]
fn ends_no_more_lines_in_a_row_at_a_point_than_the_limit() {
let pieces = with_points("aaaa=aaaa=aaaa=aaaa=aaaa=aaaa");
let limited = |limit| Frame {
hyphenation: Some(Hyphenation {
zone: None,
limit: std::num::NonZeroUsize::new(limit),
}),
..frame(60)
};
assert_eq!(
hyphenated_texts(&break_lines(&pieces, &limited(0))),
["aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa"]
);
assert_eq!(
hyphenated_texts(&break_lines(&pieces, &limited(2))),
["aaaa-", "aaaa-", "aaaaaa", "aa-", "aaaa-", "aaaa"]
);
}
#[test]
fn breaks_after_en_and_em_dashes() {
let en = break_lines(&glyphs("aa bb\u{2013}cc dd"), &frame(60));
assert_eq!(texts(&en), vec!["aa bb\u{2013}", "cc dd"]);
let em = break_lines(&glyphs("aa bb\u{2014}cc dd"), &frame(60));
assert_eq!(texts(&em), vec!["aa bb\u{2014}", "cc dd"]);
}
#[test]
fn breaks_after_a_unicode_hyphen() {
let lines = break_lines(&glyphs("aa bb\u{2010}cc dd"), &frame(60));
assert_eq!(texts(&lines), vec!["aa bb\u{2010}", "cc dd"]);
}
#[test]
fn thai_text_keeps_the_spaces_of_its_line() {
let mut f = frame(72);
f.shrink = Shrink {
permille: 400,
stretch_permille: 0,
natural: (0, 0),
joints: JointGaps::default(),
};
f.thai_keeps_spaces = true;
assert_eq!(
texts(&break_lines(&glyphs("aa bb cc"), &f)),
vec!["aa bb cc"]
);
assert_eq!(
texts(&break_lines(&glyphs("aa bb กข"), &f)),
vec!["aa bb ", "กข"]
);
assert_eq!(
texts(&break_lines(&glyphs("กข bb cc"), &f)),
vec!["กข bb ", "cc"]
);
f.thai_keeps_spaces = false;
assert_eq!(
texts(&break_lines(&glyphs("กข bb cc"), &f)),
vec!["กข bb cc"]
);
}
#[test]
fn justified_lines_may_shrink_their_spaces() {
let mut f = frame(50);
f.shrink = Shrink {
permille: 400,
stretch_permille: 0,
natural: (0, 0),
joints: JointGaps::default(),
};
assert_eq!(
texts(&break_lines(&glyphs("aa bb c"), &f)),
vec!["aa bb ", "c"]
);
f.width = Length::from_units(72);
f.first_width = f.width;
assert_eq!(
texts(&break_lines(&glyphs("aa bb cc"), &f)),
vec!["aa bb cc"]
);
let u = Length::from_units;
assert_eq!(f.shrink.of(u(10)), u(4));
assert_eq!(
Shrink {
permille: 100,
stretch_permille: 0,
natural: (0, 0),
joints: JointGaps::default(),
}
.of(u(10)),
u(1)
);
}
#[test]
fn a_share_of_the_natural_width_limits_the_overrun_to_the_nearest_twip() {
let twips = |t| Length::from_twips(t).unwrap();
let shrink = Shrink {
natural: (3, 80),
..Shrink::default()
};
assert_eq!(shrink.of_natural(twips(8_000)), Some(twips(300)));
assert_eq!(shrink.of_natural(twips(8_001)), Some(twips(300)));
assert_eq!(shrink.of_natural(twips(8_010)), Some(twips(300)));
assert_eq!(shrink.of_natural(twips(8_020)), Some(twips(301)));
assert_eq!(Shrink::default().of_natural(twips(8_000)), None);
}
#[test]
fn keeps_the_spaces_after_a_word_that_shrinks_its_line() {
let mut f = frame(72);
f.shrink = Shrink {
permille: 400,
stretch_permille: 0,
natural: (0, 0),
joints: JointGaps::default(),
};
let dashed = break_lines(&glyphs("aa bb c\u{2013} dd"), &f);
assert_eq!(texts(&dashed), vec!["aa bb c\u{2013} ", "dd"]);
}
#[test]
fn a_justified_line_takes_a_word_only_when_its_spaces_shrink_by_at_most_half_the_stretch() {
let mut f = frame(82);
f.shrink = Shrink {
permille: 500,
stretch_permille: 500,
natural: (0, 0),
joints: JointGaps::default(),
};
assert_eq!(
texts(&break_lines(&glyphs("a b c d e"), &f)),
vec!["a b c d e"]
);
f.width = Length::from_units(81);
f.first_width = f.width;
assert_eq!(
texts(&break_lines(&glyphs("a b c d e"), &f)),
vec!["a b c d ", "e"]
);
f.shrink.stretch_permille = 0;
assert_eq!(
texts(&break_lines(&glyphs("a b c d e"), &f)),
vec!["a b c d e"]
);
f.shrink.stretch_permille = 500;
let u = Length::from_units;
assert_eq!(
f.shrink
.over(u(20), (u(10), u(10)), (4, 1), JointCounts::default()),
u(8)
);
assert_eq!(
f.shrink
.over(u(5), (u(10), u(10)), (4, 1), JointCounts::default()),
u(5)
);
assert_eq!(
f.shrink
.over(u(5), (u(10), u(10)), (1, 1), JointCounts::default()),
u(5)
);
assert_eq!(
Shrink::default().over(u(10), (u(10), u(20)), (2, 1), JointCounts::default()),
u(10)
);
}
#[test]
fn a_justified_line_takes_a_word_less_often_when_its_letter_joints_count_as_gaps() {
let mut shrink = Shrink {
permille: 500,
stretch_permille: 500,
natural: (0, 0),
joints: JointGaps { seen: 9, other: 3 },
};
let u = Length::from_units;
let other = JointCounts { seen: 0, other: 1 };
assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(5));
let seen = JointCounts { seen: 1, other: 0 };
assert_eq!(shrink.over(u(20), (u(7), u(7)), (4, 1), seen), u(2));
shrink.joints = JointGaps::default();
assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(8));
}
#[test]
fn trailing_spaces_do_not_force_a_break() {
let lines = break_lines(&glyphs("aaaa b"), &frame(40));
assert_eq!(texts(&lines), vec!["aaaa ", "b"]);
assert_eq!(lines[0].width(), Length::from_units(40));
}
#[test]
fn places_an_object_as_a_word_of_its_own() {
let object = Piece::Object {
width: Length::from_units(50),
height: Length::from_units(200),
raised: Length::ZERO,
picture: None,
drawing: None,
underlined: false,
run_face: None,
joins_before: false,
};
let mut pieces = glyphs("ab ");
pieces.push(object);
pieces.extend(glyphs(" cd"));
let lines = break_lines(&pieces, &frame(100));
assert_eq!(texts(&lines), vec!["ab | ", "cd"]);
assert_eq!(lines[0].placed[3].advance, Length::from_units(50));
assert_eq!(lines[0].width(), Length::from_units(80));
let narrow = break_lines(&pieces, &frame(70));
assert_eq!(texts(&narrow), vec!["ab ", "| ", "cd"]);
}
#[test]
fn attaches_a_joining_object_to_its_preceding_word_only() {
let obj = |width: i64, joins_before: bool| Piece::Object {
width: Length::from_units(width),
height: Length::from_units(100),
raised: Length::ZERO,
picture: None,
drawing: None,
underlined: false,
run_face: None,
joins_before,
};
let mut pieces = glyphs("ab cd");
pieces.push(obj(60, true));
assert_eq!(texts(&break_lines(&pieces, &frame(85))), vec!["ab ", "cd|"]);
let mut non_joining = glyphs("ab cd");
non_joining.push(obj(60, false));
assert_eq!(
texts(&break_lines(&non_joining, &frame(85))),
vec!["ab cd", "|"]
);
let mut after_text = glyphs("ab ");
after_text.push(obj(50, true));
after_text.extend(glyphs("ef"));
assert_eq!(
texts(&break_lines(&after_text, &frame(85))),
vec!["ab |", "ef"]
);
let mut two_objs = glyphs("ab ");
two_objs.push(obj(50, true));
two_objs.push(obj(50, true));
assert_eq!(
texts(&break_lines(&two_objs, &frame(85))),
vec!["ab |", "|"]
);
let mut hyphen = glyphs("ab cd-");
hyphen.push(obj(60, true));
assert_eq!(
texts(&break_lines(&hyphen, &frame(85))),
vec!["ab cd-", "|"]
);
let mut overlong = glyphs("ab cd");
overlong.push(obj(75, true));
assert_eq!(
texts(&break_lines(&overlong, &frame(85))),
vec!["ab ", "cd", "|"]
);
}
#[test]
fn measures_an_object_after_a_tab_as_text_with_its_width() {
let object = Piece::Object {
width: Length::from_units(50),
height: Length::from_units(200),
raised: Length::ZERO,
picture: None,
drawing: None,
underlined: false,
run_face: None,
joins_before: false,
};
let mut after = vec![object];
after.extend(glyphs("ab "));
assert_eq!(following_width(&after, None), Length::from_units(70));
let mut spaced = vec![object];
spaced.extend(glyphs(" "));
assert_eq!(following_width(&spaced, None), Length::from_units(50));
}
#[test]
fn splits_a_word_that_is_too_long() {
let lines = break_lines(&glyphs("abcdefg"), &frame(30));
assert_eq!(texts(&lines), vec!["abc", "def", "g"]);
let ends: Vec<LineEnd> = lines.iter().map(|l| l.end).collect();
assert_eq!(ends, vec![LineEnd::Split, LineEnd::Split, LineEnd::Wrap]);
assert_eq!(
break_lines(&glyphs("ab cd"), &frame(30))[0].end,
LineEnd::Wrap
);
}
#[test]
fn honors_breaks_and_tabs() {
let mut pieces = glyphs("a");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs("b"));
pieces.push(Piece::LineBreak(Some(FaceIndex::nth(3))));
pieces.extend(glyphs("c"));
pieces.push(Piece::PageBreak);
let lines = break_lines(&pieces, &frame(100));
assert_eq!(texts(&lines), vec!["a|b", "c"]);
assert_eq!(lines[0].placed[1].advance, Length::from_units(15));
assert_eq!(lines[0].placed[2].x, Length::from_units(25));
assert_eq!(lines[1].end, LineEnd::PageBreak);
assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(3))));
pieces.extend(glyphs("d"));
assert_eq!(
texts(&break_lines(&pieces, &frame(100))),
vec!["a|b", "c", "d"]
);
assert_eq!(break_lines(&[], &frame(100)).len(), 1);
}
fn narrow_first(leading: LeadingBreaks) -> Frame {
let mut f = frame(100);
f.first_width = Length::from_units(50);
f.breaking.leading_breaks = leading;
f
}
#[test]
fn starts_the_first_line_after_leading_page_breaks_where_the_frame_says_so() {
let (none, first, all) = (
LeadingBreaks::None,
LeadingBreaks::First,
LeadingBreaks::All,
);
let cases = [
((1, none), (2, 0)),
((1, first), (3, 1)),
((1, all), (3, 1)),
((2, none), (3, 0)),
((2, first), (3, 1)),
((3, first), (4, 1)),
((2, all), (4, 2)),
((0, all), (2, 0)),
((0, first), (2, 0)),
];
for ((breaks, leading), expected) in cases {
let mut pieces = vec![Piece::PageBreak; breaks];
pieces.extend(glyphs("aaaa bbbb"));
let lines = break_lines(&pieces, &narrow_first(leading));
let found = (lines.len(), Line::first_index(&lines, leading));
assert_eq!(found, expected, "{breaks} breaks, {leading:?}");
}
}
#[test]
fn keeps_the_first_line_at_the_start_after_text_or_without_text() {
let mut pieces = glyphs("c");
pieces.push(Piece::PageBreak);
pieces.extend(glyphs("aaaa bbbb"));
let lines = break_lines(&pieces, &narrow_first(LeadingBreaks::All));
assert_eq!(lines.len(), 2);
assert_eq!(Line::first_index(&lines, LeadingBreaks::All), 0);
let only = [Piece::PageBreak, Piece::PageBreak];
for leading in [LeadingBreaks::First, LeadingBreaks::All] {
let lines = break_lines(&only, &narrow_first(leading));
assert_eq!(Line::first_index(&lines, leading), 0);
}
}
#[test]
fn keeps_an_empty_line_after_a_column_break_that_ends_the_pieces() {
let mut pieces = glyphs("a");
pieces.push(Piece::ColumnBreak);
let lines = break_lines(&pieces, &frame(100));
assert_eq!(texts(&lines), vec!["a", ""]);
assert_eq!(lines[0].end, LineEnd::ColumnBreak);
let mut pieces = glyphs("a");
pieces.push(Piece::PageBreak);
assert_eq!(break_lines(&pieces, &frame(100)).len(), 1);
}
#[test]
fn gives_back_the_pieces_of_lines_with_their_breaks() {
let mut pieces = glyphs("aaa bbb");
pieces.push(Piece::LineBreak(Some(FaceIndex::nth(1))));
pieces.extend(glyphs("ccc"));
pieces.push(Piece::PageBreak);
pieces.extend(glyphs("ddd"));
let lines = break_lines(&pieces, &frame(100));
assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(1))));
assert_eq!(lines[1].end, LineEnd::PageBreak);
let again = Line::pieces(&lines);
assert_eq!(again, pieces);
let narrow = break_lines(&again, &frame(40));
assert_eq!(texts(&narrow), vec!["aaa ", "bbb", "ccc", "ddd"]);
assert_eq!(narrow[1].end, LineEnd::Break(Some(FaceIndex::nth(1))));
assert_eq!(narrow[2].end, LineEnd::PageBreak);
}
#[test]
fn stretches_only_spaces_after_the_last_tab_and_the_first_glyph() {
let line = |pieces: &[Piece]| break_lines(pieces, &frame(1000)).remove(0);
assert_eq!(line(&glyphs(" a b")).first_stretched(), 2);
assert_eq!(line(&glyphs("a b")).first_stretched(), 0);
let mut pieces = glyphs("a b");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs(" c d"));
assert_eq!(line(&pieces).first_stretched(), 5);
}
#[test]
fn moves_a_tab_down_with_the_word_after_it() {
let mut pieces = glyphs("aaaa");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs("bbbbbb"));
let lines = break_lines(&pieces, &frame(100));
assert_eq!(texts(&lines), vec!["aaaa", "|bbbbbb"]);
assert_eq!(lines[1].placed[0].advance, Length::from_units(25));
assert_eq!(lines[1].placed[1].x, Length::from_units(25));
let mut alone = vec![Piece::Tab(None)];
alone.extend(glyphs(&"c".repeat(12)));
let lines = break_lines(&alone, &frame(100));
assert_eq!(texts(&lines)[0], "|");
}
#[test]
fn starts_a_new_line_with_a_tab_whose_default_stop_lies_past_the_end() {
let mut pieces = glyphs("aa");
pieces.extend([Piece::Tab(None); 3]);
pieces.extend(glyphs(" bb"));
let lines = break_lines(&pieces, &frame(60));
assert_eq!(texts(&lines), vec!["aa||", "| bb"]);
assert_eq!(lines[1].placed[2].x, Length::from_units(35));
let mut pieces = glyphs("a");
pieces.extend([Piece::Tab(None); 2]);
let lines = break_lines(&pieces, &frame(50));
assert_eq!(texts(&lines), vec!["a||"]);
let mut pieces = glyphs("aaaa ");
pieces.push(Piece::Tab(None));
let lines = break_lines(&pieces, &frame(60));
assert_eq!(texts(&lines), vec!["aaaa ", "|"]);
}
#[test]
fn aligns_text_at_right_center_and_decimal_stops() {
let stop = |position, kind| TabStop {
position: Length::from_units(position),
kind,
leader: Some('.'),
};
let mut f = frame(500);
let mut run = |kind, text: &str| {
f.tabs = Tabs::new([stop(200, kind)], Length::from_units(25), None);
let mut pieces = glyphs("a");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs(text));
let lines = break_lines(&pieces, &f);
(
lines[0].placed[1].advance.units(),
lines[0].placed[1].leader,
)
};
assert_eq!(run(TabKind::Right, "bcd "), (160, Some('.')));
assert_eq!(run(TabKind::Center, "bcd"), (175, Some('.')));
assert_eq!(run(TabKind::Decimal, "12.5"), (170, Some('.')));
assert_eq!(run(TabKind::Decimal, "125"), (160, Some('.')));
assert_eq!(run(TabKind::Right, &"x".repeat(30)), (0, Some('.')));
}
#[test]
fn ends_text_after_a_center_or_decimal_stop_at_the_line_end_where_the_quirk_says() {
let (past, ends) = (
AlignedTabOverrun::RunsPast,
AlignedTabOverrun::EndsAtAreaEnd,
);
assert!(aligned_tab(TabKind::Center, 80, "bcdef", past, 0).0 > 1);
assert_eq!(
aligned_tab(TabKind::Center, 80, "bcdef", ends, 0),
(1, Some(40))
);
assert!(aligned_tab(TabKind::Decimal, 80, "12.345", past, 0).0 > 1);
assert_eq!(
aligned_tab(TabKind::Decimal, 80, "12.345", ends, 0),
(1, Some(30))
);
assert_eq!(
aligned_tab(TabKind::Center, 80, "bc", ends, 0),
(1, Some(60))
);
}
#[test]
fn ends_text_after_a_stop_past_the_line_end_at_the_line_end_where_the_quirk_says() {
let ends = AlignedTabOverrun::EndsAtAreaEnd;
assert_eq!(
aligned_tab(TabKind::Center, 120, "bc", ends, 0),
(1, Some(70))
);
assert_eq!(
aligned_tab(TabKind::Right, 120, "bc", ends, 0),
(1, Some(70))
);
}
#[test]
fn takes_the_text_area_end_as_the_limit_of_a_stop_beside_a_right_indent() {
let ends = AlignedTabOverrun::EndsAtAreaEnd;
assert_eq!(
aligned_tab(TabKind::Center, 70, "bcd", ends, 20),
(1, Some(40))
);
assert_eq!(
aligned_tab(TabKind::Center, 90, "bcd", ends, 20),
(1, Some(60))
);
assert_eq!(
aligned_tab(TabKind::Center, 90, "bcdefgh", ends, 20),
(1, Some(20))
);
assert_eq!(
aligned_tab(TabKind::Center, 120, "bc", ends, 20),
(1, Some(50))
);
assert!(aligned_tab(TabKind::Center, 90, "bcdefghijk", ends, 20).0 > 1);
}
#[test]
fn keeps_text_after_a_stop_past_the_line_end_at_the_stop_where_the_mode_says() {
let older = (AlignedTabOverrun::EndsAtAreaEnd, false);
assert_eq!(
aligned_tab_in(TabKind::Center, 120, "bcde", older, 0),
(1, Some(90))
);
assert_eq!(
aligned_tab_in(TabKind::Center, 100, "bcdefg", older, 0),
(1, Some(60))
);
assert_eq!(
aligned_tab_in(TabKind::Right, 130, "bc", older, 0),
(1, Some(100))
);
assert_eq!(
aligned_tab_in(TabKind::Center, 80, "bcdef", older, 0),
(1, Some(40))
);
}
fn aligned_tab(
kind: TabKind,
position: i64,
text: &str,
overrun: AlignedTabOverrun,
indent: i64,
) -> (usize, Option<i64>) {
aligned_tab_in(kind, position, text, (overrun, true), indent)
}
fn aligned_tab_in(
kind: TabKind,
position: i64,
text: &str,
(overrun, limits_past_end): (AlignedTabOverrun, bool),
indent: i64,
) -> (usize, Option<i64>) {
let mut f = frame(100 - indent);
f.area_width = Length::from_units(100);
f.breaking.ends_aligned_text = overrun == AlignedTabOverrun::EndsAtAreaEnd;
f.limits_past_end = limits_past_end;
let stop = TabStop {
position: Length::from_units(position),
kind,
leader: None,
};
f.tabs = Tabs::new([stop], Length::from_units(25), None);
let mut pieces = glyphs("a");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs(text));
let lines = break_lines(&pieces, &f);
let tab = lines
.first()
.and_then(|line| line.placed.get(1))
.map(|placed| placed.advance.units());
(lines.len(), tab)
}
#[test]
fn runs_on_to_a_right_stop_past_the_line_end() {
let stop = |kind| TabStop {
position: Length::from_units(120),
kind,
leader: None,
};
let line = |kind, after: &str| {
let mut f = frame(100);
f.first_start = Length::from_units(10);
f.tabs = Tabs::new([stop(kind)], Length::from_units(25), None);
let mut pieces = glyphs("aaaa");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs(after));
texts(&break_lines(&pieces, &f))
};
assert_eq!(line(TabKind::Right, "bb"), ["aaaa|bb"]);
assert_eq!(
line(TabKind::Right, "bb cccccccc"),
["aaaa|bb ", "cccccccc"]
);
assert_ne!(line(TabKind::Left, "bb"), ["aaaa|bb"]);
}
#[test]
fn empty_paragraph_has_one_line() {
let lines = break_lines(&[], &frame(100));
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].width(), Length::ZERO);
assert!(!is_space(&Piece::LineBreak(None)));
}
#[test]
fn an_object_wider_than_the_line_ends_its_paragraph_on_that_line() {
let wide = Piece::Object {
width: Length::from_units(150),
height: Length::from_units(50),
raised: Length::ZERO,
picture: None,
drawing: None,
underlined: false,
run_face: None,
joins_before: false,
};
assert_eq!(texts(&break_lines(&[wide], &frame(100))), ["|"]);
let mut pieces = vec![wide];
pieces.extend(glyphs("aa"));
assert_eq!(texts(&break_lines(&pieces, &frame(100))), ["|", "aa"]);
assert_eq!(
texts(&break_lines(&glyphs("abcdefghijkl"), &frame(100))),
["abcdefghij", "kl"]
);
}
#[test]
fn punctuation_shrinks_up_to_r_times_the_stretch_per_gap_of_the_shorter_line() {
let compression = super::Compression { ratio: 32 };
let u = Length::from_units;
let halves = |count| super::Halves {
count,
em: u(1_000),
};
assert_eq!(compression.over(halves(10), (u(60), 19)), u(1_010));
assert_eq!(compression.over(halves(10), (u(55), 19)), u(926));
assert_eq!(compression.over(halves(11), (u(100), 19)), u(1_852));
assert_eq!(compression.over(halves(1), (u(900), 2)), u(500));
assert_eq!(compression.over(halves(10), (u(60), 0)), Length::ZERO);
}
#[test]
fn a_justified_line_takes_one_more_character_when_its_halves_may_shrink() {
let pieces = glyphs("永、永、永、永永永");
let frame = |width, compressing: bool| Frame {
kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
punctuation: compressing.then_some(super::Compression { ratio: 32 }),
..frame(width)
};
assert_eq!(
texts(&break_lines(&pieces, &frame(71, true))),
["永、永、永、永永", "永"]
);
assert_eq!(
texts(&break_lines(&pieces, &frame(70, true))),
["永、永、永、永", "永永"]
);
assert_eq!(
texts(&break_lines(&pieces, &frame(71, false))),
["永、永、永、永", "永永"]
);
}
#[test]
fn closes_up_pairs_after_a_blank_right_half_or_before_an_opening_mark() {
use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
let check = |script, yes: &[&str], no: &[&str]| {
let kerned = |pair: &str| {
let mut chars = pair.chars();
super::kerned_pair(chars.next().unwrap(), chars.next().unwrap(), script)
};
assert!(yes.iter().all(|pair| kerned(pair)));
assert!(no.iter().all(|pair| !kerned(pair)));
};
check(
Some(Japanese),
&[
"。」", ",(", "」「", ")。", "。。", "、、", ":「", "・(", "((", ")・",
],
&[
"!,", "!(", ")!", "!?", "?(", ")?", "::", "・・",
],
);
check(
Some(Simplified),
&[
"!,", "!(", "!!", ")!", ":,", "::", ";;", ",,",
],
&[
"!?", "?(", ")?", "・(", ")・", "测(", ")测", "」a",
],
);
check(
Some(Traditional),
&["),", "。「", ":(", "):", "、("],
&[",,", ",。", "。、", "!,", "!(", "・(", "?("],
);
check(None, &[")【", "】)"], &["),", "。「"]);
}
#[test]
fn a_tab_to_a_left_stop_past_the_line_end_starts_the_next_line_and_ends_at_its_end() {
let stop = TabStop {
position: Length::from_units(120),
kind: TabKind::Left,
leader: None,
};
let lay_out = |rule| {
let mut f = frame(100);
f.tabs = Tabs::new([stop], Length::from_units(25), None);
f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
let mut pieces = glyphs("a");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs("b"));
let lines = break_lines(&pieces, &f);
let tab = lines
.iter()
.flat_map(|line| &line.placed)
.find(|placed| matches!(placed.piece, Piece::Tab(_)))
.map(|placed| (placed.x.units(), placed.advance.units()));
(texts(&lines), tab)
};
let (texts_to_stop, tab_to_stop) = lay_out(LeftStopPastEnd::ToStop);
assert_eq!(texts_to_stop, ["a", "|b"]);
assert_eq!(tab_to_stop, Some((0, 120)));
let (texts_to_end, tab_to_end) = lay_out(LeftStopPastEnd::ToLineEnd);
assert_eq!(texts_to_end, ["a", "|", "b"]);
assert_eq!(tab_to_end, Some((0, 100)));
}
#[test]
fn a_tab_to_a_left_stop_inside_the_line_keeps_its_place_on_both_variants() {
let stop = TabStop {
position: Length::from_units(80),
kind: TabKind::Left,
leader: None,
};
for rule in [LeftStopPastEnd::ToStop, LeftStopPastEnd::ToLineEnd] {
let mut f = frame(100);
f.tabs = Tabs::new([stop], Length::from_units(25), None);
f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
let mut pieces = glyphs("a");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs("b"));
assert_eq!(texts(&break_lines(&pieces, &f)), ["a|b"], "{rule:?}");
}
}
#[test]
fn a_tab_to_a_hanging_indent_past_the_line_end_runs_on_on_both_variants() {
let lay_out = |rule| {
let mut f = frame(100);
f.tabs = Tabs::new([], Length::from_units(25), Some(Length::from_units(120)));
f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
let mut pieces = glyphs("a");
pieces.push(Piece::Tab(None));
pieces.extend(glyphs("b"));
texts(&break_lines(&pieces, &f))
};
assert_eq!(
lay_out(LeftStopPastEnd::ToLineEnd),
lay_out(LeftStopPastEnd::ToStop)
);
}
}