mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 08:11:41 +00:00
Merge pull request #7229 from dotCooCoo/feat/kinsoku-sets
Type: Kinsoku Shori sets can be created, edited and chosen per paragraph
This commit is contained in:
@@ -36,6 +36,7 @@ mod vertical;
|
||||
mod warichu;
|
||||
|
||||
pub(crate) use bidi::{is_rtl, para_bidi, starts_bidi};
|
||||
pub(crate) use breaking::is_hanging_punctuation;
|
||||
use breaking::tab_advance;
|
||||
#[cfg(test)]
|
||||
use breaking::{break_line, candidates};
|
||||
|
||||
@@ -1,11 +1,76 @@
|
||||
use super::region::Region;
|
||||
use super::vertical::stands_upright;
|
||||
use super::{
|
||||
Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, SGlyph,
|
||||
hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start,
|
||||
Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, ParaStyle,
|
||||
SGlyph, hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start,
|
||||
};
|
||||
use crate::justify::is_format_control;
|
||||
|
||||
/// The kinsoku rules a paragraph is composed with: a built-in Kinsoku Set (None, Hard or Soft), or
|
||||
/// a custom set (Type › Kinsoku Shori Settings…).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum KinsokuRules<'a> {
|
||||
BuiltIn(Kinsoku),
|
||||
Custom(&'a vectorcraft_doc::KinsokuSet),
|
||||
}
|
||||
|
||||
impl<'a> KinsokuRules<'a> {
|
||||
/// The rules of paragraph `para`: its custom set when it has one, else its Kinsoku Set.
|
||||
pub(crate) fn of(para: &'a ParaStyle) -> Self {
|
||||
match ¶.kinsoku_set {
|
||||
Some(set) => Self::Custom(set),
|
||||
None => Self::BuiltIn(para.kinsoku),
|
||||
}
|
||||
}
|
||||
|
||||
/// Kinsoku None: no character is kept off a line's ends, and Bunri-Kinshi has no effect.
|
||||
pub(crate) fn is_none(self) -> bool {
|
||||
matches!(self, Self::BuiltIn(Kinsoku::None))
|
||||
}
|
||||
|
||||
/// May `c` not start a line? Hard: every character of [`no_line_start`]; Soft: those
|
||||
/// [`soft_line_start`] doesn't let start one; a custom set: its Cannot Start Line characters.
|
||||
pub(crate) fn cannot_start(self, c: char) -> bool {
|
||||
match self {
|
||||
Self::BuiltIn(Kinsoku::None) => false,
|
||||
Self::BuiltIn(Kinsoku::Hard) => no_line_start(c),
|
||||
Self::BuiltIn(Kinsoku::Soft) => no_line_start(c) && !soft_line_start(c),
|
||||
Self::Custom(set) => set.cannot_start(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// May `c` not end a line? Hard and Soft: an opening bracket ([`no_line_end`]); a custom set:
|
||||
/// its Cannot End Line characters.
|
||||
pub(crate) fn cannot_end(self, c: char) -> bool {
|
||||
match self {
|
||||
Self::BuiltIn(Kinsoku::None) => false,
|
||||
Self::BuiltIn(Kinsoku::Hard | Kinsoku::Soft) => no_line_end(c),
|
||||
Self::Custom(set) => set.cannot_end(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// May `c` hang outside a line's end with Burasagari? An East Asian comma or full stop (、。,.
|
||||
/// and the half-width 、。), or a custom set's Hanging Punctuation characters.
|
||||
pub(crate) fn hangs(self, c: char) -> bool {
|
||||
match self {
|
||||
Self::BuiltIn(_) => is_hanging_punctuation(c),
|
||||
Self::Custom(set) => set.hangs(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Kinsoku> for KinsokuRules<'_> {
|
||||
fn from(k: Kinsoku) -> Self {
|
||||
Self::BuiltIn(k)
|
||||
}
|
||||
}
|
||||
|
||||
/// The punctuation Burasagari hangs with the built-in Kinsoku Sets: the East Asian comma and full
|
||||
/// stop, full width and half width.
|
||||
pub(crate) fn is_hanging_punctuation(c: char) -> bool {
|
||||
matches!(c, '、' | '。' | ',' | '.' | '、' | '。')
|
||||
}
|
||||
|
||||
/// Vertical metrics of a line: (ascent, descent, leading, cap height, x height).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Metrics {
|
||||
@@ -351,12 +416,13 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64,
|
||||
/// Width of the word starting at glyph `i`: its advances up to the first place a line may break
|
||||
/// (spaces left out, the hyphen of a soft hyphen in), the least room a line needs not to break
|
||||
/// inside it. As in [`break_line`], kinsoku keeps a character that may not end a line with the one
|
||||
/// after it, a No Break run (its spaces inside it included) is one word up to a forced line break,
|
||||
/// after it, spaces between them included, a No Break run (its spaces inside it included) is one word up to a forced line break,
|
||||
/// and a cluster is never split. A soft hyphen just before a forced line break adds no hyphen. A list marker at `i` (glyphs of length 0) counts whole, with the word after it. A word
|
||||
/// that ends where a line may end is measured as the line is set: without the spaces at its end,
|
||||
/// and with its last glyph as narrow as `line_end` sets it; one that ends at a soft hyphen or past
|
||||
/// the measured glyphs is not.
|
||||
pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kinsoku) -> f64 {
|
||||
/// the measured glyphs is not. With `burasagari`, the word may end after hanging punctuation.
|
||||
pub(super) fn word_width<'k>(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: impl Into<KinsokuRules<'k>>, burasagari: Burasagari) -> f64 {
|
||||
let kinsoku = kinsoku.into();
|
||||
/// Glyphs measured at most: a word wrapped over many lines is measured again from each line's
|
||||
/// start, and one this long is broken inside whatever cell it meets.
|
||||
const MAX_GLYPHS: usize = 1024;
|
||||
@@ -375,7 +441,15 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
|
||||
return set(w, trailing, ink);
|
||||
}
|
||||
if gl.is_space() && (end == start || !splits_no_break(g, end)) {
|
||||
return set(w, trailing, ink);
|
||||
// A line breaks after one of these spaces only where kinsoku allows it, as in
|
||||
// [`break_line`]; where it allows none (after 「, or before 」), the word goes on past them.
|
||||
let run = end + g[end..].iter().take(start + MAX_GLYPHS - end).take_while(|h| h.is_space()).count();
|
||||
if end == start || (end..run).any(|k| g[k].break_after() && g[k].len > 0 && kinsoku_allows(g, k, kinsoku) && !splits_no_break(g, k + 1)) {
|
||||
return set(w, trailing, ink);
|
||||
}
|
||||
let spaces: f64 = g[end..run].iter().map(|h| h.adv).sum();
|
||||
(w, trailing, end) = (w + spaces, trailing + spaces, run);
|
||||
continue;
|
||||
}
|
||||
let forced_next = g.get(end + 1).is_some_and(|n| n.ch == '\u{2028}');
|
||||
if gl.is_soft_hyphen() && !forced_next && kinsoku_allows(g, end, kinsoku) && !splits_no_break(g, end + 1) {
|
||||
@@ -389,7 +463,10 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
|
||||
(trailing, ink) = (0.0, end);
|
||||
}
|
||||
let cluster_ends = g.get(end).is_none_or(|next| next.byte != gl.byte);
|
||||
if gl.break_after() && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) {
|
||||
// Hanging punctuation of one glyph may end the line with Burasagari, as in [`break_line`].
|
||||
let alone = cluster_ends && end.checked_sub(2).and_then(|k| g.get(k)).is_none_or(|p| p.byte != gl.byte);
|
||||
let hang_break = burasagari != Burasagari::None && alone && hangs(gl, kinsoku);
|
||||
if (gl.break_after() || hang_break) && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) {
|
||||
return set(w, trailing, ink);
|
||||
}
|
||||
}
|
||||
@@ -442,7 +519,7 @@ fn drawn_last(g: &[SGlyph], i: usize, j: usize, end: usize) -> bool {
|
||||
/// end in the visual order of the line's levels ([`drawn_last`]) and the line before the mark fits
|
||||
/// as drawn.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn break_line(
|
||||
pub(super) fn break_line<'k>(
|
||||
text: &str,
|
||||
g: &[SGlyph],
|
||||
i: usize,
|
||||
@@ -451,13 +528,14 @@ pub(super) fn break_line(
|
||||
x_start: f64,
|
||||
hyphenate: Option<(&HyphenationOptions, f64)>,
|
||||
burasagari: Burasagari,
|
||||
kinsoku: Kinsoku,
|
||||
kinsoku: impl Into<KinsokuRules<'k>>,
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
hanging: bool,
|
||||
vertical: bool,
|
||||
line_end: &[f64],
|
||||
fits: Option<&dyn Fn(usize, bool) -> bool>,
|
||||
) -> (usize, bool) {
|
||||
let kinsoku = kinsoku.into();
|
||||
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| {
|
||||
craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits)
|
||||
};
|
||||
@@ -551,13 +629,14 @@ pub(super) fn break_line(
|
||||
let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width };
|
||||
overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS;
|
||||
if j > first && !gl.is_space() && measured - end_credit > width + EPS {
|
||||
// It ends the line with the spaces after it, when the mark is all the characters kept
|
||||
// together (the line's last character is the mark, which is what hangs). Once the line
|
||||
// holds a tab and is measured as drawn, the mark hangs only where it is drawn at the
|
||||
// line's right end (its cluster is last in the line's visual order, [`drawn_last`]) and
|
||||
// the line before it fits as drawn with no line-end trim on its last glyph; otherwise the
|
||||
// line ends at a legal break that fits as drawn.
|
||||
let alone = g[j..cluster_end].iter().all(|h| h.byte == gl.byte);
|
||||
// It ends the line with the spaces after it, when it hangs alone: not with the rest of a
|
||||
// No Break run or an inseparable sequence it starts, and only as one glyph, the one the
|
||||
// line's geometry hangs. Once the line holds a tab and is measured as drawn, the mark
|
||||
// hangs only where it is drawn at the line's right end (its cluster is last in the
|
||||
// line's visual order, [`drawn_last`]) and the line before it fits as drawn with no
|
||||
// line-end trim on its last glyph; otherwise the line ends at a legal break that fits as
|
||||
// drawn.
|
||||
let alone = cluster_end == j + 1;
|
||||
let hangs_as_drawn = || match fits.filter(|_| tabbed) {
|
||||
None => true,
|
||||
Some(fits) => {
|
||||
@@ -568,7 +647,7 @@ pub(super) fn break_line(
|
||||
drawn_last(g, i, j, cluster_end) && line_end_credit(g, line_end, body) == 0.0 && fits(j, false)
|
||||
}
|
||||
};
|
||||
if burasagari != Burasagari::None && hangs(gl) && alone && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() {
|
||||
if burasagari != Burasagari::None && alone && hangs(gl, kinsoku) && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() {
|
||||
let mut end = cluster_end;
|
||||
while g.get(end).is_some_and(SGlyph::is_space) {
|
||||
end += 1;
|
||||
@@ -586,7 +665,10 @@ pub(super) fn break_line(
|
||||
ink += cluster_ink;
|
||||
back += cluster_back;
|
||||
let last = &g[cluster_end - 1];
|
||||
if last.break_after() && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) {
|
||||
// Hanging punctuation that would hang alone where it overflows may end the line where it
|
||||
// fits too: a custom set's may be a character no other rule breaks after.
|
||||
let hang_break = burasagari != Burasagari::None && cluster_end == j + 1 && hangs(last, kinsoku);
|
||||
if (last.break_after() || hang_break) && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) {
|
||||
// Once the line holds a tab, whether a break fits as drawn is settled when the line ends.
|
||||
let hyphenated = last.is_soft_hyphen();
|
||||
if !hyphenated || (tabbed && fits.is_some()) || x + hyphen_glyph(last).adv <= width + EPS {
|
||||
@@ -661,11 +743,12 @@ pub(super) fn break_line(
|
||||
}
|
||||
|
||||
/// Can glyph `g` hang outside the line (burasagari)? An East Asian comma or full stop, full width
|
||||
/// (、。,.) or half width (、。); not a closing bracket, nor Latin punctuation (Latin text keeps
|
||||
/// its line breaks and composer). Never an inline graphic (U+FFFC), nor a character of a
|
||||
/// tate-chu-yoko or warichu block.
|
||||
pub(super) fn hangs(g: &SGlyph) -> bool {
|
||||
g.inline.is_none() && matches!(g.ch, '、' | '。' | ',' | '.' | '、' | '。') && g.tcy.is_none() && g.wari.is_none()
|
||||
/// (、。,.) or half width (、。), or with a custom set a character of its Hanging Punctuation
|
||||
/// ([`KinsokuRules::hangs`]); with the built-in sets not a closing bracket, nor Latin punctuation
|
||||
/// (Latin text keeps its line breaks and composer). Never an inline graphic (U+FFFC), nor a
|
||||
/// character of a tate-chu-yoko or warichu block.
|
||||
pub(super) fn hangs(g: &SGlyph, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
g.inline.is_none() && kinsoku.hangs(g.ch) && g.tcy.is_none() && g.wari.is_none()
|
||||
}
|
||||
|
||||
/// Optical Margin Alignment: the share of glyph `g`'s advance that hangs outside the margin when
|
||||
@@ -755,7 +838,7 @@ fn line_end_credit(g: &[SGlyph], line_end: &[f64], end: usize) -> f64 {
|
||||
|
||||
/// May [`break_line`] end a line after glyph `end - 1` (and the spaces after it)? At the paragraph's
|
||||
/// end or a forced line break, and where it records a break without a hyphen.
|
||||
fn may_end_after(g: &[SGlyph], end: usize, kinsoku: Kinsoku) -> bool {
|
||||
fn may_end_after(g: &[SGlyph], end: usize, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
let mut e = end;
|
||||
while g.get(e).is_some_and(SGlyph::is_space) {
|
||||
e += 1;
|
||||
@@ -775,20 +858,25 @@ fn splits_no_break(g: &[SGlyph], end: usize) -> bool {
|
||||
|
||||
/// Does kinsoku allow a line break after glyph `j`? Not after an opening bracket, nor before a
|
||||
/// closing one, a comma, a full stop, a small kana… (the character is pushed to the next line
|
||||
/// with the one before it).
|
||||
fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: Kinsoku) -> bool {
|
||||
g.get(j).is_some_and(|gl| kinsoku_between(gl.ch, g.get(j + 1).map(|n| n.ch), kinsoku))
|
||||
/// with the one before it). A line that breaks after spaces is drawn without them, so the
|
||||
/// character before them is the one that ends it: up to [`KINSOKU_SPACES_BACK`] spaces are looked
|
||||
/// past, and after a longer run of spaces the space itself counts.
|
||||
fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
let Some(gl) = g.get(j) else { return false };
|
||||
let before = if gl.is_space() { g[..j].iter().rev().take(KINSOKU_SPACES_BACK).find(|h| !h.is_space()).map_or(gl.ch, |h| h.ch) } else { gl.ch };
|
||||
kinsoku_between(before, g.get(j + 1).map(|n| n.ch), kinsoku)
|
||||
}
|
||||
|
||||
/// The most spaces [`kinsoku_allows`] looks past for the character that ends a line, so a long run
|
||||
/// of spaces is not read again at each of its breaks.
|
||||
const KINSOKU_SPACES_BACK: usize = 64;
|
||||
|
||||
/// Kinsoku for a break between `before` and `after` (none: the end of the paragraph): Hard keeps
|
||||
/// every character of the set off the line start and end, Soft lets 々, ー and small kana start a
|
||||
/// line, None allows the break.
|
||||
fn kinsoku_between(before: char, after: Option<char>, kinsoku: Kinsoku) -> bool {
|
||||
match kinsoku {
|
||||
Kinsoku::None => true,
|
||||
Kinsoku::Hard => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c)),
|
||||
Kinsoku::Soft => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c) || soft_line_start(c)),
|
||||
}
|
||||
/// line, a custom set keeps its own characters off them ([`KinsokuRules`]), and None allows the
|
||||
/// break.
|
||||
fn kinsoku_between(before: char, after: Option<char>, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
!kinsoku.cannot_end(before) && after.is_none_or(|c| !kinsoku.cannot_start(c))
|
||||
}
|
||||
|
||||
/// The share of an em by which a push-in ([`push_in`]) may close each gap next to a CJK character
|
||||
@@ -823,13 +911,13 @@ fn push_in(
|
||||
x: f64,
|
||||
width: f64,
|
||||
pushed_out: Option<usize>,
|
||||
kinsoku: Kinsoku,
|
||||
kinsoku: KinsokuRules<'_>,
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
hanging: bool,
|
||||
vertical: bool,
|
||||
line_end: &[f64],
|
||||
) -> Option<usize> {
|
||||
if kinsoku == Kinsoku::None || kinsoku_type == KinsokuShoriType::PushOutOnly {
|
||||
if kinsoku.is_none() || kinsoku_type == KinsokuShoriType::PushOutOnly {
|
||||
return None;
|
||||
}
|
||||
let before = g.get(j.checked_sub(1)?)?;
|
||||
@@ -933,13 +1021,30 @@ pub(super) fn squeeze_em(g: &SGlyph, vertical: bool) -> f64 {
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends() {
|
||||
let hard = KinsokuRules::BuiltIn(Kinsoku::Hard);
|
||||
for (a, b) in [('字', '。'), ('弧', '」'), ('」', '、'), ('ャ', 'ー'), ('カ', 'ッ'), ('「', 'か'), ('(', '雅')] {
|
||||
assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}");
|
||||
assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}");
|
||||
}
|
||||
for (a, b) in [('。', '雅'), ('」', 'は'), ('字', '「'), ('の', '演')] {
|
||||
assert!(kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), hard), "{a}{b}");
|
||||
}
|
||||
assert!(kinsoku_between('。', None, Kinsoku::Hard));
|
||||
assert!(kinsoku_between('。', None, hard));
|
||||
}
|
||||
|
||||
/// A custom set keeps its own characters off a line's ends, and nothing else: here 字 may not
|
||||
/// start a line and 弧 may not end one, while 。 and 「 may.
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn a_custom_kinsoku_set_keeps_its_own_characters_off_line_ends() {
|
||||
let mut set = vectorcraft_doc::KinsokuSet { name: "Custom".into(), cannot_start: vec!['字'], cannot_end: vec!['弧'], ..Default::default() };
|
||||
set.normalize();
|
||||
let custom = KinsokuRules::Custom(&set);
|
||||
assert!(!kinsoku_between('の', Some('字'), custom));
|
||||
assert!(!kinsoku_between('弧', Some('の'), custom));
|
||||
for (a, b) in [('字', '。'), ('「', 'か'), ('字', 'の')] {
|
||||
assert!(kinsoku_between(a, Some(b), custom), "{a}{b}");
|
||||
}
|
||||
assert!(!custom.is_none());
|
||||
}
|
||||
|
||||
/// Soft kinsoku lets 々, ー and small kana (JLREQ cl-09's 々, cl-10, cl-11) start a line and keeps
|
||||
@@ -947,13 +1052,14 @@ fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends()
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() {
|
||||
let [none, hard, soft] = [Kinsoku::None, Kinsoku::Hard, Kinsoku::Soft].map(KinsokuRules::BuiltIn);
|
||||
for (a, b) in [('ャ', 'ー'), ('カ', 'ッ'), ('時', '々'), ('ト', 'ㇰ'), ('か', 'ゃ')] {
|
||||
assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}");
|
||||
assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), soft), "{a}{b}");
|
||||
}
|
||||
for (a, b) in [('字', '。'), ('弧', '」'), ('「', 'か'), ('カ', 'ッ'), ('カ', 'ー'), ('字', 'ゝ')] {
|
||||
assert!(!kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), Kinsoku::None), "{a}{b}");
|
||||
assert!(!kinsoku_between(a, Some(b), soft), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), none), "{a}{b}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1001,7 +1107,13 @@ fn word_hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyp
|
||||
/// paragraph's Hyphenation options) when it is given. No break comes before a space: a line that
|
||||
/// may end after a dash, a Thai word or a space ends after the spaces that follow it, as in
|
||||
/// [`break_line`].
|
||||
pub(super) fn candidates(text: &str, g: &[SGlyph], hyphenate: Option<&HyphenationOptions>, kinsoku: Kinsoku) -> Vec<Breakpoint> {
|
||||
pub(super) fn candidates<'k>(
|
||||
text: &str,
|
||||
g: &[SGlyph],
|
||||
hyphenate: Option<&HyphenationOptions>,
|
||||
kinsoku: impl Into<KinsokuRules<'k>>,
|
||||
) -> Vec<Breakpoint> {
|
||||
let kinsoku = kinsoku.into();
|
||||
let mut v = vec![];
|
||||
let mut ws = 0;
|
||||
for (j, gl) in g.iter().enumerate() {
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
use super::bidi::{is_rtl, para_bidi_with, visual_order};
|
||||
use super::breaking::{
|
||||
Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs, optical_hangs_rtl,
|
||||
optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width,
|
||||
KinsokuRules, Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs,
|
||||
optical_hangs_rtl, optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width,
|
||||
};
|
||||
use super::region::Region;
|
||||
use super::vertical::{
|
||||
EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin,
|
||||
};
|
||||
use super::{
|
||||
Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker,
|
||||
ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph,
|
||||
is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics,
|
||||
Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, ParaStyle,
|
||||
Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, is_cjk,
|
||||
is_word_space, kashida, mark_word_ends, style_metrics,
|
||||
};
|
||||
use crate::justify::is_format_control;
|
||||
use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range};
|
||||
use crate::shape::{keep_inseparable_pairs, keep_inseparable_sequences, keep_korean_words, repeat_base, repeated_char, shape_range};
|
||||
use std::cell::Cell;
|
||||
|
||||
/// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First,
|
||||
/// with kinsoku on)?
|
||||
fn pushes_in(para: &ParaStyle) -> bool {
|
||||
para.kinsoku != Kinsoku::None && para.kinsoku_type != KinsokuShoriType::PushOutOnly
|
||||
!KinsokuRules::of(para).is_none() && para.kinsoku_type != KinsokuShoriType::PushOutOnly
|
||||
}
|
||||
|
||||
/// May paragraph `para` push one of glyphs `sg` in onto a line: does it push characters in, and
|
||||
/// hold a character its kinsoku rules keep off a line's start or end?
|
||||
pub(super) fn may_push_in(para: &ParaStyle, sg: &[SGlyph]) -> bool {
|
||||
let kinsoku = KinsokuRules::of(para);
|
||||
pushes_in(para) && sg.iter().any(|g| kinsoku.cannot_start(g.ch) || kinsoku.cannot_end(g.ch))
|
||||
}
|
||||
|
||||
/// Paragraphs longer than this (glyphs) are always broken line by line.
|
||||
@@ -55,9 +62,10 @@ fn compose_para(
|
||||
let composer = cx.opts.composer.unwrap_or(para.composer);
|
||||
// A paragraph whose commas or full stops may hang is composed line by line (as the Japanese
|
||||
// single-line composer does).
|
||||
let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs);
|
||||
let kinsoku = KinsokuRules::of(para);
|
||||
let may_hang = para.burasagari != Burasagari::None && sg.iter().any(|g| hangs(g, kinsoku));
|
||||
// So is a paragraph that may push characters kinsoku keeps off a line's ends in onto a line.
|
||||
let may_push_in = pushes_in(para) && sg.iter().any(|g| no_line_start(g.ch) || no_line_end(g.ch));
|
||||
let may_push_in = may_push_in(para, sg);
|
||||
// A tab's width depends on where it falls in its line, which the composer's fixed glyph widths
|
||||
// can't follow: such a paragraph is broken line by line ([`break_line`] measures its tabs).
|
||||
// The tab of a list marker is on the first line, with the marker, and has a fixed width.
|
||||
@@ -100,7 +108,7 @@ fn compose_para(
|
||||
// Only the first line's first word is known here. Later lines are placed as the composed
|
||||
// lines need: each fits its width, so its first word does too. It is measured as the line
|
||||
// loop measures it, with Mojikumi's narrower start and end.
|
||||
let word = if first { word_width(sg, 0, line_end, para.kinsoku) - start_credit(0) } else { 0.0 };
|
||||
let word = if first { word_width(sg, 0, line_end, kinsoku, para.burasagari) - start_credit(0) } else { 0.0 };
|
||||
let Some((b, x0, x1, _)) = sim.place(m, ind_l, para.right_indent, word) else { break };
|
||||
let w = x1 - x0 - ind_l - para.right_indent;
|
||||
widths.push(w);
|
||||
@@ -119,7 +127,7 @@ fn compose_para(
|
||||
let width = |k: usize| widths.get(k).copied().unwrap_or(last);
|
||||
// Lines from `uniform_from` on are interchangeable (same width).
|
||||
let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1);
|
||||
let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), para.kinsoku);
|
||||
let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), kinsoku);
|
||||
let justify_last = para.justify == Justify::JustifyAll;
|
||||
let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX);
|
||||
let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from, hyphen_limit };
|
||||
@@ -277,8 +285,12 @@ fn prepare_paragraph<'a, 'text>(
|
||||
keep_korean_words(&mut sg);
|
||||
}
|
||||
// Bunri-Kinshi keeps inseparable pairs on one line, while kinsoku is on.
|
||||
if para.bunri_kinshi && para.kinsoku != Kinsoku::None {
|
||||
keep_inseparable_pairs(text, &mut sg);
|
||||
// A custom set keeps its own inseparable sequences instead.
|
||||
match KinsokuRules::of(para) {
|
||||
_ if !para.bunri_kinshi => {}
|
||||
KinsokuRules::Custom(set) => keep_inseparable_sequences(text, &mut sg, &set.inseparable),
|
||||
rules if !rules.is_none() => keep_inseparable_pairs(text, &mut sg),
|
||||
_ => {}
|
||||
}
|
||||
// Japanese composition (the paragraph's Mojikumi set): every punctuation mark set half width,
|
||||
// or consecutive punctuation sharing one half-em space…
|
||||
@@ -442,7 +454,8 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
|
||||
glyph.lead += half;
|
||||
}
|
||||
// The line's first word, as narrow as the line sets it at both ends.
|
||||
let word = word_width(sg, *i, line_end, para.kinsoku);
|
||||
let kinsoku = KinsokuRules::of(para);
|
||||
let word = word_width(sg, *i, line_end, kinsoku, para.burasagari);
|
||||
// A composed line in a frame whose lines are not all as wide is placed at its own tallest
|
||||
// metrics, as the composer placed it (`shaped::Shaped`): its room is the room across its height.
|
||||
let composed_line = composed.as_ref().and_then(|lines| lines.get(*para_line)).is_some_and(|&(end, _)| end > *i);
|
||||
@@ -502,7 +515,7 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
|
||||
// A right-to-left paragraph draws a burasagari mark inside its line
|
||||
// ([`prepare_line_geometry`]): the line ends where it fits with the mark.
|
||||
if *rtl { Burasagari::None } else { para.burasagari },
|
||||
para.kinsoku,
|
||||
kinsoku,
|
||||
ty,
|
||||
*hanging,
|
||||
cx.vertical,
|
||||
@@ -782,7 +795,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData
|
||||
let hang = (paragraph.regions.is_some() && !paragraph.rtl && hyphen.is_none() && trimmed > index + 1)
|
||||
.then(|| sg.get(trimmed - 1))
|
||||
.flatten()
|
||||
.filter(|g| hangs(g))
|
||||
.filter(|g| hangs(g, KinsokuRules::of(para)))
|
||||
.map(|g| g.adv - end_trim)
|
||||
.filter(|_| match para.burasagari {
|
||||
Burasagari::None => false,
|
||||
|
||||
@@ -15,7 +15,7 @@ use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::breaking::{Metrics, Pen, word_width};
|
||||
use super::breaking::{KinsokuRules, Metrics, Pen, word_width};
|
||||
use super::flow::line_indents;
|
||||
use super::{ParaStyle, SGlyph};
|
||||
use crate::composer::{Exhausted, Measure};
|
||||
@@ -278,7 +278,7 @@ fn past_end<'r>(p: &Para<'_>, start: &Start<'r>) -> Option<Placed<'r>> {
|
||||
/// frame's end ([`past_end`]) when no frame cell has room for it.
|
||||
fn place<'r>(p: &Para<'_>, start: &Start<'r>, m: Metrics) -> Result<Option<Placed<'r>>, Exhausted> {
|
||||
let (ind_l, ind_r) = line_indents(p.para, start.first, p.mirror);
|
||||
let word = word_width(p.sg, start.pos, p.line_end, p.para.kinsoku) - (p.start_credit)(start.pos);
|
||||
let word = word_width(p.sg, start.pos, p.line_end, KinsokuRules::of(p.para), p.para.burasagari) - (p.start_credit)(start.pos);
|
||||
let mut pen = start.pen.clone();
|
||||
loop {
|
||||
match pen.place(m, ind_l, ind_r, word) {
|
||||
|
||||
@@ -300,12 +300,12 @@ fn word_width_measures_across_a_soft_hyphen_inside_a_no_break_run() {
|
||||
for g in &mut glyphs {
|
||||
g.sx = 0.001;
|
||||
}
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!(plain < 30.0, "without the mark the word ends at the soft hyphen: {plain}");
|
||||
for g in &mut glyphs {
|
||||
g.no_break = true;
|
||||
}
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((marked - 30.0).abs() < 1e-9, "the marked run is measured whole: {marked}");
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ fn word_width_stops_at_a_forced_line_break() {
|
||||
for g in &mut glyphs {
|
||||
g.no_break = true;
|
||||
}
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}");
|
||||
|
||||
let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 2, 0.0, '\u{00ad}'), (3, 3, 5.0, '\u{2028}'), (6, 1, 10.0, 'B')]);
|
||||
@@ -325,12 +325,12 @@ fn word_width_stops_at_a_forced_line_break() {
|
||||
for g in &mut glyphs {
|
||||
g.sx = 0.001;
|
||||
}
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((plain - 10.0).abs() < 1e-9, "no hyphen before the forced line break: {plain}");
|
||||
for g in &mut glyphs {
|
||||
g.no_break = true;
|
||||
}
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}");
|
||||
}
|
||||
|
||||
@@ -1342,8 +1342,8 @@ fn korean_words_break_at_spaces_unless_line_break_anywhere() {
|
||||
let cands = candidates(text, &off, None, Kinsoku::Hard);
|
||||
assert_eq!(compose(&off, &|_| 50.0, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms), Some(vec![(4, false), (7, false)]));
|
||||
// The first word is measured whole, as the line loop measures it.
|
||||
assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard), 30.0);
|
||||
assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard), 10.0);
|
||||
assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard, Burasagari::None), 30.0);
|
||||
assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0);
|
||||
// A word wider than the line still breaks, at the syllable that overflows.
|
||||
assert_eq!(greedy(&korean("가나다라마바", false), 25.0), 2);
|
||||
// A soft return still ends the line.
|
||||
@@ -1449,8 +1449,8 @@ fn bunri_kinshi_keeps_jlreq_pairs_in_both_composers() {
|
||||
};
|
||||
assert_eq!(greedy(&pairs(text, false), 35.0), 3, "off: the line ends between the dashes");
|
||||
assert_eq!(greedy(&pairs(text, true), 35.0), 2, "on: both dashes go to the next line");
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard), 20.0);
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard), 10.0);
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard, Burasagari::None), 20.0);
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0);
|
||||
let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 };
|
||||
let on = pairs("あい——う", true);
|
||||
let cands = candidates("あい——う", &on, None, Kinsoku::Hard);
|
||||
@@ -1500,6 +1500,241 @@ fn bunri_kinshi_progresses_with_an_overlong_pair_and_no_break() {
|
||||
assert_eq!(line(text, &pairs(text, true), 0, 46.5, Kinsoku::Hard, PushInFirst), 3);
|
||||
}
|
||||
|
||||
/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) with these categories.
|
||||
fn custom_set(cannot_start: &str, cannot_end: &str, hanging: &str, inseparable: &[&str]) -> vectorcraft_doc::KinsokuSet {
|
||||
let mut set = vectorcraft_doc::KinsokuSet {
|
||||
name: "Custom".into(),
|
||||
cannot_start: cannot_start.chars().collect(),
|
||||
cannot_end: cannot_end.chars().collect(),
|
||||
hanging: hanging.chars().collect(),
|
||||
inseparable: inseparable.iter().map(|s| s.to_string()).collect(),
|
||||
};
|
||||
set.normalize();
|
||||
set
|
||||
}
|
||||
|
||||
/// New Set from Hard or Soft starts with their characters: a custom set made from either breaks
|
||||
/// every line where it does, in both composers, with every Kinsoku Shori Type and with and without
|
||||
/// Burasagari, and keeps the same inseparable pairs with Bunri-Kinshi. One made from None is empty.
|
||||
#[test]
|
||||
fn a_set_made_from_hard_or_soft_breaks_lines_as_they_do() {
|
||||
use KinsokuShoriType::{PushInFirst, PushOutFirst, PushOutOnly};
|
||||
let texts = ["一二三四五六七八九十一二三四五」六", "あカッー々ャ「か」、。(雅)", "あい——う〳〵え……カッー", "一二三四(五六)ab\u{201c}c\u{201d}。"];
|
||||
for base in [Kinsoku::Hard, Kinsoku::Soft] {
|
||||
let set = crate::shape::kinsoku_set_from(base, "From");
|
||||
let custom = breaking::KinsokuRules::Custom(&set);
|
||||
for text in texts {
|
||||
let mut built_in = full_width(text);
|
||||
crate::shape::keep_inseparable_pairs(text, &mut built_in);
|
||||
let mut own = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut own, &set.inseparable);
|
||||
let kept = |g: &[SGlyph]| g.iter().map(|g| g.keeps_next).collect::<Vec<_>>();
|
||||
assert_eq!(kept(&built_in), kept(&own), "{base:?} {text}");
|
||||
let ends = |c: Vec<Breakpoint>| c.iter().map(|b| b.end).collect::<Vec<_>>();
|
||||
assert_eq!(ends(candidates(text, &built_in, None, base)), ends(candidates(text, &own, None, custom)), "{base:?} {text}");
|
||||
for ty in [PushInFirst, PushOutFirst, PushOutOnly] {
|
||||
for burasagari in [Burasagari::None, Burasagari::Standard] {
|
||||
for width in (15..=160).step_by(5).map(f64::from) {
|
||||
let at = |g: &[SGlyph], k: breaking::KinsokuRules<'_>| {
|
||||
break_line(text, g, 0, width, &[], 0.0, None, burasagari, k, ty, false, false, &[], None).0
|
||||
};
|
||||
assert_eq!(at(&built_in, base.into()), at(&own, custom), "{base:?} {ty:?} {burasagari:?} {width} {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let empty = crate::shape::kinsoku_set_from(Kinsoku::None, "Empty");
|
||||
assert!(empty.cannot_start.is_empty() && empty.cannot_end.is_empty() && empty.hanging.is_empty() && empty.inseparable.is_empty());
|
||||
}
|
||||
|
||||
/// A custom set keeps its own Cannot Start Line characters off a line's start and its Cannot End
|
||||
/// Line characters off its end, and lets every other character start or end one: here 四 never
|
||||
/// starts a line and 三 never ends one, while 」, which Hard keeps off a line's start, may start
|
||||
/// one with an empty set.
|
||||
#[test]
|
||||
fn a_custom_set_keeps_its_own_characters_off_line_ends() {
|
||||
use KinsokuShoriType::PushOutOnly;
|
||||
let end = |text: &str, width: f64, k: breaking::KinsokuRules<'_>| {
|
||||
break_line(text, &full_width(text), 0, width, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0
|
||||
};
|
||||
let text = "一二三四五六";
|
||||
let start = custom_set("四", "", "", &[]);
|
||||
let finish = custom_set("", "三", "", &[]);
|
||||
let empty = custom_set("", "", "", &[]);
|
||||
assert_eq!(end(text, 35.0, Kinsoku::Hard.into()), 3);
|
||||
assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&start)), 2, "四 does not start the next line");
|
||||
assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line");
|
||||
let bracket = "一二三」四";
|
||||
assert_eq!(end(bracket, 35.0, Kinsoku::Hard.into()), 2, "Hard keeps 」 off the next line's start");
|
||||
assert_eq!(end(bracket, 35.0, breaking::KinsokuRules::Custom(&empty)), 3, "the empty set lets 」 start it");
|
||||
// A space after 三 is not drawn at the end of the line, so a break after it would still end
|
||||
// the line with 三.
|
||||
let spaced = "一二三 四";
|
||||
assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line before a space");
|
||||
assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&empty)), 4);
|
||||
let ends = candidates(text, &full_width(text), None, breaking::KinsokuRules::Custom(&start)).iter().map(|b| b.end).collect::<Vec<_>>();
|
||||
assert_eq!(ends, [1, 2, 4, 5]);
|
||||
}
|
||||
|
||||
/// The least room a word needs ([`breaking::word_width`]) runs past spaces where kinsoku allows no
|
||||
/// break after them, to the first break [`break_line`] may take: after 「 or a custom set's 三 with
|
||||
/// spaces after it, and before a 」 that follows a space. Where the break after the space is
|
||||
/// allowed, the word still ends before the space.
|
||||
#[test]
|
||||
fn word_width_runs_past_spaces_kinsoku_does_not_break_after() {
|
||||
use KinsokuShoriType::PushOutOnly;
|
||||
let finish = custom_set("", "三", "", &[]);
|
||||
let empty = custom_set("", "", "", &[]);
|
||||
for (text, k, word) in [
|
||||
("「 四五", breaking::KinsokuRules::from(Kinsoku::Hard), 30.0),
|
||||
("「 四五", Kinsoku::Hard.into(), 40.0),
|
||||
("a 」二", Kinsoku::Hard.into(), 30.0),
|
||||
("三 四五", breaking::KinsokuRules::Custom(&finish), 30.0),
|
||||
("三 四五", breaking::KinsokuRules::Custom(&empty), 10.0),
|
||||
("一 二三", Kinsoku::Hard.into(), 10.0),
|
||||
] {
|
||||
let g = full_width(text);
|
||||
assert_eq!(breaking::word_width(&g, 0, &[], k, Burasagari::None), word, "{text}");
|
||||
// In a measure that wide, break_line's first line is that word, drawn without the spaces
|
||||
// at its end.
|
||||
let mut end = break_line(text, &g, 0, word, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0;
|
||||
while end > 0 && g[end - 1].is_space() {
|
||||
end -= 1;
|
||||
}
|
||||
assert_eq!(g[..end].iter().map(|h| h.adv).sum::<f64>(), word, "{text}");
|
||||
}
|
||||
// A No Break run of spaces after 「 longer than the glyphs a word is measured over stops the
|
||||
// measure there.
|
||||
let long: String = std::iter::once('「').chain(std::iter::repeat_n(' ', 2000)).chain(['四']).collect();
|
||||
let mut g = full_width(&long);
|
||||
for h in g.iter_mut().skip(1) {
|
||||
h.no_break = true;
|
||||
}
|
||||
assert_eq!(breaking::word_width(&g, 0, &[], Kinsoku::Hard, Burasagari::None), 10240.0);
|
||||
}
|
||||
|
||||
/// Soft and a set made from it choose the same composer: small kana and the prolonged sound mark,
|
||||
/// which Soft lets start a line, do not send a paragraph that pushes in to the single-line
|
||||
/// composer with either, while Hard, which keeps them off a line's start, does.
|
||||
#[test]
|
||||
fn soft_and_a_set_made_from_it_push_in_the_same_characters() {
|
||||
use KinsokuShoriType::{PushInFirst, PushOutOnly};
|
||||
let glyphs = full_width("あゃいーう");
|
||||
let para = |kinsoku: Kinsoku, own: bool, kinsoku_type: KinsokuShoriType| ParaStyle {
|
||||
kinsoku,
|
||||
kinsoku_set: own.then(|| Arc::new(crate::shape::kinsoku_set_from(kinsoku, "From"))),
|
||||
kinsoku_type,
|
||||
..ParaStyle::default()
|
||||
};
|
||||
assert!(!flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &glyphs), "built-in Soft");
|
||||
assert!(!flow::may_push_in(¶(Kinsoku::Soft, true, PushInFirst), &glyphs), "a set made from Soft");
|
||||
assert!(flow::may_push_in(¶(Kinsoku::Hard, false, PushInFirst), &glyphs), "built-in Hard");
|
||||
assert!(flow::may_push_in(¶(Kinsoku::Hard, true, PushInFirst), &glyphs), "a set made from Hard");
|
||||
assert!(!flow::may_push_in(¶(Kinsoku::Hard, false, PushOutOnly), &glyphs), "Push Out Only");
|
||||
let bracket = full_width("あい」う");
|
||||
assert!(flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &bracket), "Soft keeps 」 off a line's start");
|
||||
}
|
||||
|
||||
/// With Burasagari, a custom set hangs its own Hanging Punctuation and not the comma and full stop
|
||||
/// the built-in sets hang: 、 hangs outside a full line with Hard and with a set that lists it; with
|
||||
/// a set that lists only ! it starts the next line, while ! hangs.
|
||||
#[test]
|
||||
fn a_custom_set_hangs_its_own_hanging_punctuation() {
|
||||
use KinsokuShoriType::PushOutOnly;
|
||||
let end = |text: &str, k: breaking::KinsokuRules<'_>| {
|
||||
break_line(text, &full_width(text), 0, 30.0, &[], 0.0, None, Burasagari::Standard, k, PushOutOnly, false, false, &[], None).0
|
||||
};
|
||||
let comma = custom_set("", "", "、", &[]);
|
||||
let bang = custom_set("", "", "!", &[]);
|
||||
assert_eq!(end("一二三、四", Kinsoku::Hard.into()), 4);
|
||||
assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&comma)), 4, "、 hangs");
|
||||
assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&bang)), 3, "、 does not hang");
|
||||
assert_eq!(end("一二三!四", breaking::KinsokuRules::Custom(&bang)), 4, "! hangs");
|
||||
// In a wider line where ! fits, the line still ends after it.
|
||||
let text = "一二三!四";
|
||||
let wide = |b: Burasagari| {
|
||||
break_line(text, &full_width(text), 0, 40.0, &[], 0.0, None, b, breaking::KinsokuRules::Custom(&bang), PushOutOnly, false, false, &[], None).0
|
||||
};
|
||||
assert_eq!(wide(Burasagari::Standard), 4, "! fits and ends the line");
|
||||
assert_eq!(wide(Burasagari::None), 3, "without Burasagari ! does not hang, and no line ends after it");
|
||||
// The first word, which places a line in a frame of uneven width, ends after ! as the line may.
|
||||
let word = |b: Burasagari| breaking::word_width(&full_width("AB!CD"), 0, &[], breaking::KinsokuRules::Custom(&bang), b);
|
||||
assert_eq!(word(Burasagari::Standard), 30.0);
|
||||
assert_eq!(word(Burasagari::None), 50.0);
|
||||
// A hanging character that starts an inseparable sequence kept with Bunri-Kinshi does not hang
|
||||
// the rest of the sequence with it: the sequence goes to the next line.
|
||||
let joined = custom_set("", "", "!", &["!あ"]);
|
||||
let text = "一二三!あい";
|
||||
let mut g = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, &joined.inseparable);
|
||||
let rules = breaking::KinsokuRules::Custom(&joined);
|
||||
assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, rules, PushOutOnly, false, false, &[], None).0, 3);
|
||||
// A hanging character drawn with two glyphs does not hang: the line's geometry hangs only one
|
||||
// glyph, so the other would stay past the measure. 三 goes to the next line with it.
|
||||
let text = "一二三、四";
|
||||
let mut g = full_width(text);
|
||||
g[3].adv = 5.0;
|
||||
g.insert(3, g[3].clone());
|
||||
assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, PushOutOnly, false, false, &[], None).0, 2);
|
||||
let g = full_width("、!");
|
||||
assert!(breaking::hangs(&g[1], breaking::KinsokuRules::Custom(&bang)) && !breaking::hangs(&g[0], breaking::KinsokuRules::Custom(&bang)));
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi with a custom set: a line never breaks inside one of its inseparable sequences,
|
||||
/// which may be longer than a pair and may overlap, and the built-in pairs are kept only when the
|
||||
/// set lists them.
|
||||
#[test]
|
||||
fn a_custom_set_keeps_its_inseparable_sequences_on_one_line() {
|
||||
let marked = |text: &str, sequences: &[&str]| {
|
||||
let mut g = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, &sequences.iter().map(|s| s.to_string()).collect::<Vec<_>>());
|
||||
g.iter().map(|g| g.keeps_next).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(marked("かあいうえ", &["あいう"]), [false, true, true, false, false]);
|
||||
assert_eq!(marked("あいうえお", &["あい", "いう"]), [true, true, false, false, false], "overlapping sequences chain");
|
||||
assert_eq!(marked("あ——い", &["あい"]), [false; 4], "the built-in pairs are not kept by a set without them");
|
||||
assert_eq!(marked("", &["あい"]), Vec::<bool>::new());
|
||||
assert_eq!(marked("あいうえお", &["あい", "あいうえ"]), [true, true, true, false, false], "the longer of two sequences that start alike");
|
||||
assert_eq!(marked("あいう", &["あい", "あいか"]), [true, false, false], "the shorter where only it is found");
|
||||
// A set at the category limit whose sequences all start with one character.
|
||||
let many: Vec<String> = (0..2047u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect();
|
||||
let many: Vec<&str> = many.iter().map(String::as_str).chain(["あい"]).collect();
|
||||
assert_eq!(marked("あいあ一う", &many), [true, false, true, false, false]);
|
||||
let text = "かあいうえ";
|
||||
let set = custom_set("", "", "", &["あいう"]);
|
||||
let mut g = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, &set.inseparable);
|
||||
let ends = candidates(text, &g, None, breaking::KinsokuRules::Custom(&set)).iter().map(|b| b.end).collect::<Vec<_>>();
|
||||
assert_eq!(ends, [1, 4]);
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi with a custom set compares at most 15 texts with the set's sequences for each
|
||||
/// character of a paragraph, however many sequences start with one character: 2048 sequences of
|
||||
/// 2 characters cost one lookup at each place, 256 of 16 characters cost 15, and a sequence longer
|
||||
/// than a set holds is not looked for.
|
||||
#[test]
|
||||
fn inseparable_sequences_cost_a_bounded_number_of_lookups() {
|
||||
let lookups = |text: &str, sequences: &[String]| {
|
||||
let mut g = full_width(text);
|
||||
crate::shape::SEQUENCE_LOOKUPS.with(|n| n.set(0));
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, sequences);
|
||||
(crate::shape::SEQUENCE_LOOKUPS.with(std::cell::Cell::get), g.iter().filter(|g| g.keeps_next).count())
|
||||
};
|
||||
// A place n characters from the paragraph's end looks up min(n, 16) - 1 texts.
|
||||
let cost = |chars: usize, longest: usize| (1..=chars).map(|n| n.min(longest) - 1).sum::<usize>();
|
||||
let text = "あ".repeat(1000);
|
||||
let pairs: Vec<String> = (0..2048u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect();
|
||||
assert_eq!(lookups(&text, &pairs), (999, 0));
|
||||
let long: Vec<String> = (0..256u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| format!("{}{c}", "あ".repeat(15))).collect();
|
||||
assert_eq!(lookups(&text, &long), (cost(1000, 16), 0));
|
||||
assert!(cost(1000, 16) <= 1000 * 15);
|
||||
let mut found = long.clone();
|
||||
found.push("あ".repeat(16));
|
||||
assert_eq!(lookups(&"あ".repeat(16), &found), (cost(16, 16), 15));
|
||||
assert_eq!(lookups(&"あ".repeat(17), &["あ".repeat(17)]), (cost(17, 16), 0), "17 characters are never found");
|
||||
}
|
||||
|
||||
/// Justification adds no gap between two glyphs of one warichu block, whichever of them is drawn
|
||||
/// first: right to left, the block's first glyph (the one that starts it) is drawn after the
|
||||
/// others. Between glyphs of two blocks, the gap stays.
|
||||
|
||||
@@ -56,7 +56,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
|
||||
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
|
||||
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
|
||||
pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale};
|
||||
pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
|
||||
pub use vectorcraft_doc::TextObject;
|
||||
|
||||
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
|
||||
|
||||
@@ -438,6 +438,89 @@ pub(crate) fn keep_inseparable_pairs(text: &str, sg: &mut [SGlyph]) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many texts [`keep_inseparable_sequences`] has compared with a set's sequences on this
|
||||
/// thread.
|
||||
pub(crate) static SEQUENCE_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi with a custom Kinsoku Shori set: as [`keep_inseparable_pairs`], for the set's
|
||||
/// inseparable `sequences` (each [`vectorcraft_doc::text::KINSOKU_SEQUENCE`] characters): a line
|
||||
/// never breaks between two characters of one occurrence of a sequence in the paragraph's text.
|
||||
/// Occurrences may overlap. The text is read once; at each place that starts a sequence, only the
|
||||
/// text of each sequence length (at most [`vectorcraft_doc::text::KINSOKU_SEQUENCE`]'s end) is
|
||||
/// looked up, however many sequences share a first character: at most 15 lookups for each
|
||||
/// character of the paragraph. A sequence longer than a set can hold is never found.
|
||||
pub(crate) fn keep_inseparable_sequences(text: &str, sg: &mut [SGlyph], sequences: &[String]) {
|
||||
let (Some(first), Some(last)) = (sg.iter().map(|g| g.byte).min(), sg.iter().map(|g| g.byte + g.len).max()) else { return };
|
||||
let Some(longest) = sequences.iter().map(|s| s.chars().count()).max() else { return };
|
||||
let longest = longest.min(*vectorcraft_doc::text::KINSOKU_SEQUENCE.end());
|
||||
let known: std::collections::HashSet<&str> = sequences.iter().map(String::as_str).collect();
|
||||
let starts: std::collections::HashSet<char> = sequences.iter().filter_map(|s| s.chars().next()).collect();
|
||||
let Some(para) = text.get(first..last) else { return };
|
||||
// The bytes (of `text`) where a character inside an occurrence starts, after its first.
|
||||
let mut inside = std::collections::HashSet::new();
|
||||
for (at, c) in para.char_indices() {
|
||||
if !starts.contains(&c) {
|
||||
continue;
|
||||
}
|
||||
let rest = ¶[at..];
|
||||
// Every sequence found here is the start of the longest one found here, so that one marks
|
||||
// the characters of them all.
|
||||
let mut found = None;
|
||||
for end in rest.char_indices().take(longest).map(|(k, ch)| k + ch.len_utf8()).skip(1) {
|
||||
#[cfg(test)]
|
||||
SEQUENCE_LOOKUPS.with(|n| n.set(n.get() + 1));
|
||||
if known.contains(&rest[..end]) {
|
||||
found = Some(end);
|
||||
}
|
||||
}
|
||||
if let Some(end) = found {
|
||||
inside.extend(rest[..end].char_indices().skip(1).map(|(k, _)| first + at + k));
|
||||
}
|
||||
}
|
||||
if inside.is_empty() {
|
||||
return;
|
||||
}
|
||||
for k in 1..sg.len() {
|
||||
let (a, b) = (&sg[k - 1], &sg[k]);
|
||||
if a.byte == b.byte || a.inline.is_some() || b.inline.is_some() || a.byte + a.len != b.byte {
|
||||
continue;
|
||||
}
|
||||
if inside.contains(&b.byte) {
|
||||
sg[k - 1].keeps_next = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters, hanging punctuation and inseparable sequences of a built-in Kinsoku Set
|
||||
/// (`base`), as a custom set named `name` holds them: New Set's starting point. A set made from
|
||||
/// Hard or Soft breaks lines as that set does; one made from None is empty.
|
||||
pub fn kinsoku_set_from(base: vectorcraft_doc::Kinsoku, name: &str) -> vectorcraft_doc::KinsokuSet {
|
||||
use vectorcraft_doc::Kinsoku;
|
||||
let mut set = vectorcraft_doc::KinsokuSet { name: name.to_string(), ..Default::default() };
|
||||
if base == Kinsoku::None {
|
||||
return set;
|
||||
}
|
||||
// Every character the built-in sets name is in the Basic Multilingual Plane.
|
||||
for c in (0..=0xFFFF_u32).filter_map(char::from_u32) {
|
||||
if no_line_start(c) && !(base == Kinsoku::Soft && soft_line_start(c)) {
|
||||
set.cannot_start.push(c);
|
||||
}
|
||||
if no_line_end(c) {
|
||||
set.cannot_end.push(c);
|
||||
}
|
||||
if crate::layout::is_hanging_punctuation(c) {
|
||||
set.hanging.push(c);
|
||||
}
|
||||
}
|
||||
let pairs = [('\u{2014}', '\u{2014}'), ('\u{2026}', '\u{2026}'), ('\u{2025}', '\u{2025}'), ('\u{3033}', '\u{3035}'), ('\u{3034}', '\u{3035}')];
|
||||
set.inseparable = pairs.iter().filter(|&&(a, b)| inseparable(a, b)).map(|&(a, b)| [a, b].iter().collect()).collect();
|
||||
set.normalize();
|
||||
set
|
||||
}
|
||||
|
||||
/// Is `a` followed by `b` an inseparable pair that Bunri-Kinshi keeps on one line? VectorCraft's
|
||||
/// set is the pairs W3C JLREQ lists for its class cl-08 (https://www.w3.org/TR/jlreq/#cl-08): two
|
||||
/// em dashes, two horizontal ellipses, two two-dot leaders, and the upper half of a vertical kana
|
||||
|
||||
Reference in New Issue
Block a user