use f_office_units::Length;
use super::LinePlace;
use crate::character_class::CharacterClass;
use crate::layout::measure::JUSTIFIED_SHRINK;
use crate::layout::{Layout, decisions};
use crate::lines::{Line, LineEnd, Piece, stretches};
use crate::mode::ShareRounding;
use crate::params;
use crate::props::{Alignment, ParaProps};
use crate::quirks::Quirks;
use crate::styles::{Settings, SoftBreakLines};
pub(in crate::layout) struct Shift {
pub(in crate::layout) offset: Length,
pub(in crate::layout) spread: Length,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(in crate::layout) struct SpaceShares {
pub(in crate::layout) per_space: Length,
pub(in crate::layout) rest: Length,
}
impl Shift {
pub(in crate::layout) fn space_shares(&self, line: &Line, mark_shrink: Length) -> SpaceShares {
match stretched_spaces(line) {
Some(n) if mark_shrink == Length::ZERO => {
let per_space = self.spread.div_toward_zero(n);
SpaceShares {
per_space,
rest: self.spread - per_space * n,
}
}
_ => SpaceShares::default(),
}
}
}
impl Shift {
pub(in crate::layout) fn counted_shares(
&self,
line: &Line,
(shares, mark_shrink): (SpaceShares, Length),
lost: (i128, i128),
rounding: ShareRounding,
) -> Option<CountedShares> {
let spaces = stretched_spaces(line)?;
let (lost, per) = lost;
(self.spread != Length::ZERO && mark_shrink == Length::ZERO && per > 0).then(|| {
CountedShares {
free: (i128::from(self.spread.units()) * per - lost, per),
spaces,
per_space: shares.per_space,
rounding,
}
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct CountedShares {
free: (i128, i128),
spaces: i64,
per_space: Length,
rounding: ShareRounding,
}
impl CountedShares {
fn summed_parts(&self, k: i64) -> i128 {
let (free, per) = self.free;
let parts = i128::from(params::SHARE_PARTS_PER_POINT);
let denominator = per * i128::from(self.spaces) * i128::from(Length::UNITS_PER_POINT);
match self.rounding {
ShareRounding::SumTowardZero => i128::from(k) * free * parts / denominator,
ShareRounding::RemainderFirst => {
let spaces = i128::from(self.spaces);
let (numerator, whole) = (free * parts, per * i128::from(Length::UNITS_PER_POINT));
let total = (2 * numerator + numerator.signum() * whole) / (2 * whole);
let (each, left) = (total / spaces, total % spaces);
i128::from(k) * each + left.signum() * i128::from(k).min(left.abs())
}
}
}
pub(in crate::layout) fn excess(&self, k: i64) -> (i128, i128) {
let parts = i128::from(params::SHARE_PARTS_PER_POINT);
let own = self.summed_parts(k) - self.summed_parts(k - 1);
(
own * i128::from(Length::UNITS_PER_POINT) - i128::from(self.per_space.units()) * parts,
parts,
)
}
}
pub(super) fn stretched_spaces(line: &Line) -> Option<i64> {
let spaces = line
.placed
.iter()
.take(line.written())
.skip(line.first_stretched())
.filter(|p| stretches(&p.piece))
.count();
i64::try_from(spaces).ok().filter(|n| *n > 0)
}
pub(in crate::layout) fn aligned_as_last(
line: &Line,
last: bool,
settings: &Settings,
quirks: &Quirks,
) -> bool {
last || (matches!(line.end, LineEnd::Break(_))
&& decisions::followed_soft_break_lines(quirks, settings.soft_break_lines)
== Some(SoftBreakLines::AsLastLine))
}
impl Layout<'_> {
pub(super) fn alignment_and_shift(
&self,
line: &Line,
props: &ParaProps,
place: LinePlace,
) -> (Alignment, Shift) {
let last = aligned_as_last(line, place.last, self.settings, &self.context.quirks);
let free = place.width - line.width();
let alignment = line_alignment(props, last && free >= Length::ZERO);
(alignment, shift(alignment, free, last))
}
}
pub(super) fn line_alignment(props: &ParaProps, last: bool) -> Alignment {
let rtl = props.flags().bidi;
match (props.alignment.unwrap_or(Alignment::Start), rtl) {
(Alignment::Start, true) => Alignment::End,
(Alignment::Both | Alignment::ThaiDistribute, true) if last => Alignment::End,
(Alignment::End, true) => Alignment::Start,
(alignment, _) => alignment,
}
}
fn blank_halves_before(line: &Line, index: usize, sides: MarkSides) -> i64 {
let glyph = |i: usize| match line.placed.get(i).map(|p| p.piece) {
Some(Piece::Glyph(g)) => Some(g.ch),
_ => None,
};
let closing = index > 0 && glyph(index - 1).is_some_and(|ch| sides.has_trailing_half(ch));
let opening = glyph(index).is_some_and(crate::lines::opening_mark);
i64::from(closing) + i64::from(opening)
}
pub(super) fn inner_blank_halves_before(line: &Line, index: usize, sides: MarkSides) -> i64 {
if inner_piece(line, index) {
blank_halves_before(line, index, sides)
} else {
0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum MarkSides {
BlankHalf,
Japanese,
Centered,
}
impl MarkSides {
const fn splits(self, ch: char) -> bool {
match self {
Self::BlankHalf => false,
Self::Japanese => crate::lines::japanese_centered_mark(ch),
Self::Centered => crate::lines::centered_mark(ch),
}
}
fn has_trailing_half(self, ch: char) -> bool {
crate::lines::closing_mark(ch) || (self == Self::Japanese && crate::lines::middle_dot(ch))
}
}
pub(in crate::layout) fn inner_mark_shrink_before(
line: &Line,
index: usize,
shrink: Length,
sides: MarkSides,
) -> Length {
if !inner_piece(line, index) {
return Length::ZERO;
}
let glyph = |i: usize| match line.placed.get(i).map(|p| p.piece) {
Some(Piece::Glyph(g)) => Some(g.ch),
_ => None,
};
let split = |i: usize| {
inner_piece(line, i)
&& inner_piece(line, i + 1)
&& glyph(i).is_some_and(|ch| sides.splits(ch))
};
let before = shrink.div_toward_zero(2);
let own = if split(index) {
before
} else if glyph(index).is_some_and(crate::lines::opening_mark) {
shrink
} else {
Length::ZERO
};
let after_mark = match index.checked_sub(1) {
Some(previous) if split(previous) => shrink - before,
Some(previous) if glyph(previous).is_some_and(|ch| sides.has_trailing_half(ch)) => shrink,
_ => Length::ZERO,
};
own + after_mark
}
pub(super) fn inner_piece(line: &Line, index: usize) -> bool {
index > line.first_stretched() && line.last_visible().is_some_and(|v| index <= v)
}
pub(in crate::layout) fn spread_gap(line: &Line, index: usize) -> bool {
let full_width = |i: usize| matches!(line.placed.get(i).map(|p| p.piece), Some(Piece::Glyph(g)) if CharacterClass::FullWidthCell.contains(g.ch));
inner_piece(line, index) && (full_width(index - 1) || full_width(index))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct Narrowing {
first: usize,
last: usize,
each: Length,
from: usize,
dot: Length,
}
impl Narrowing {
pub(in crate::layout) fn of(line: &Line, over: Length, dot: Length) -> Option<(Length, Self)> {
let first = line.first_stretched();
let last = line.last_visible().filter(|&last| last >= first)?;
let pieces = line.placed.get(first..=last)?;
if over <= Length::ZERO || dot <= Length::ZERO {
return None;
}
let count = i64::try_from(pieces.len()).ok()?;
let advance = pieces.first()?.advance;
let spaces: Vec<Length> = pieces
.iter()
.filter(|p| stretches(&p.piece))
.map(|p| p.advance)
.collect();
let taken = match i64::try_from(spaces.len()).ok()? {
0 => Length::ZERO,
_ if pieces.iter().all(|p| p.advance == advance) => Length::ZERO,
n => {
let share = over.div_toward_zero(n);
spaces
.iter()
.map(|&space| share.min(JUSTIFIED_SHRINK.of(space)))
.sum()
}
};
let dots = (over - taken).div_round(dot.units()).units();
let from = last + 1 - usize::try_from(dots.rem_euclid(count)).ok()?;
let narrowing = Self {
first,
last,
each: dot * dots.div_euclid(count),
from,
dot,
};
Some((taken, narrowing))
}
pub(in crate::layout) fn at(self, index: usize) -> Length {
if !(self.first..=self.last).contains(&index) {
return Length::ZERO;
}
let extra = if index >= self.from {
self.dot
} else {
Length::ZERO
};
-(self.each + extra)
}
}
pub(in crate::layout) fn spread_over_gaps(line: &Line, spread: Length) -> Length {
let has_space = line.placed.iter().any(|p| stretches(&p.piece));
let gaps: i64 = (0..line.placed.len())
.map(|index| i64::from(spread_gap(line, index)))
.sum();
if spread > Length::ZERO && gaps > 0 && !has_space {
spread.div_toward_zero(gaps)
} else {
Length::ZERO
}
}
pub(in crate::layout) fn compressed_marks(
line: &Line,
free: Length,
sides: MarkSides,
) -> Option<Length> {
let halves: i64 = (0..line.placed.len())
.map(|index| inner_blank_halves_before(line, index, sides))
.sum();
(free < Length::ZERO && halves > 0)
.then(|| Length::from_units((free.units() - halves + 1) / halves))
}
pub(in crate::layout) fn shift(alignment: Alignment, free: Length, last: bool) -> Shift {
let none = Length::ZERO;
let (offset, spread) = match alignment {
Alignment::Start => (none, none),
Alignment::Center => (free.max(none).div_toward_zero(2), none),
Alignment::End => (free.max(none), none),
Alignment::Both | Alignment::ThaiDistribute if last && free >= none => (none, none),
Alignment::Both | Alignment::ThaiDistribute => (none, free),
};
Shift { offset, spread }
}
#[cfg(test)]
mod tests {
use f_office_units::Length;
use super::CountedShares;
use crate::mode::ShareRounding::{self, RemainderFirst, SumTowardZero};
#[test]
fn counts_the_shares_in_parts_of_a_point_as_the_mode_rounds_them() {
let excesses = |free: i128, per_space: i64, rounding: ShareRounding| {
let shares = CountedShares {
free: (free, 1),
spaces: 3,
per_space: Length::from_units(per_space),
rounding,
};
(1..=3).map(|k| shares.excess(k)).collect::<Vec<_>>()
};
let excess = |parts: i128, per_space: i128| (parts * 25_400 - per_space * 4_096, 4_096);
assert_eq!(
excesses(100, 33, SumTowardZero),
[excess(5, 33), excess(5, 33), excess(6, 33)]
);
assert_eq!(
excesses(100, 33, RemainderFirst),
[excess(6, 33), excess(5, 33), excess(5, 33)]
);
assert_eq!(
excesses(-100, -33, SumTowardZero),
[excess(-5, -33), excess(-5, -33), excess(-6, -33)]
);
assert_eq!(
excesses(-100, -33, RemainderFirst),
[excess(-6, -33), excess(-5, -33), excess(-5, -33)]
);
assert_eq!(
excesses(105, 35, RemainderFirst),
[excess(6, 35), excess(6, 35), excess(5, 35)]
);
assert_eq!(
excesses(105, 35, SumTowardZero),
[excess(5, 35), excess(6, 35), excess(5, 35)]
);
let shares = CountedShares {
free: (199, 2),
spaces: 3,
per_space: Length::from_units(33),
rounding: SumTowardZero,
};
assert_eq!(shares.excess(3), excess(6, 33));
}
#[test]
fn shrinks_squeezed_last_line_of_right_to_left_justified_paragraph() {
use crate::props::{Alignment, ParaProps};
let props = ParaProps {
alignment: Some(Alignment::Both),
bidi: Some(true),
..ParaProps::default()
};
let free = Length::from_units(-100);
let loose_alignment = super::line_alignment(&props, true);
assert_eq!(loose_alignment, Alignment::End);
assert_eq!(
super::shift(loose_alignment, Length::from_units(100), true).spread,
Length::ZERO
);
let squeezed_alignment = super::line_alignment(&props, false);
assert_eq!(squeezed_alignment, Alignment::Both);
assert_eq!(super::shift(squeezed_alignment, free, true).spread, free);
}
}