Type: a line's first word is measured as set when looking for room

In a frame that is not a rectangle, or with text wrap, layout moves a
line down to the first span wide enough for its first word. The word
was measured at full width before Mojikumi set an opening bracket at
the line's start flush, and with its last character at full width, so
a word that fit as set moved down to a wider line. It also ended at any
break opportunity, so an opening bracket counted without the character
kinsoku keeps with it and could be placed alone on a line too narrow
for that character.

- word_width ends the word only where break_line may end a line: at a
  cluster end that kinsoku allows, not inside a No Break run, whose
  spaces count. It leaves out the spaces at the word's end and narrows
  its last glyph by the Mojikumi line-end credit.
- place_flow_line measures the word after the opening-bracket trim, and
  the Every-line Composer's first-line placement takes off the same
  start credit, so the composed widths match the placed lines.
This commit is contained in:
dotCooCoo
2026-11-11 15:20:50 -08:00
parent a5bfa524dc
commit 253c60a23e
4 changed files with 141 additions and 22 deletions
+28 -10
View File
@@ -240,29 +240,47 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64,
out
}
/// Width of the word starting at glyph `i`: its advances up to the first break opportunity (spaces
/// left out, the hyphen of a soft hyphen in), the least room a line needs not to break inside it.
/// A list marker at `i` (glyphs of length 0) counts whole, with the word after it.
pub(super) fn word_width(g: &[SGlyph], i: usize) -> 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, and a cluster is never
/// split. 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 {
/// 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;
let rest = g.get(i..).unwrap_or_default();
let marker = rest.iter().take_while(|gl| gl.len == 0).count();
let mut w: f64 = rest.iter().take(marker).map(|gl| gl.adv).sum();
for gl in rest.iter().skip(marker).take(MAX_GLYPHS) {
if gl.is_space() {
break;
let start = i + marker;
let mut end = start;
// The spaces at the end of what is measured so far (inside a No Break run), and the end of its
// last glyph that is not a space.
let (mut trailing, mut ink) = (0.0, start);
let set = |w: f64, trailing: f64, ink: usize| w - trailing - line_end_credit(g, line_end, ink);
while let Some(gl) = g.get(end).filter(|_| end - start < MAX_GLYPHS) {
if gl.is_space() && (end == start || !splits_no_break(g, end)) {
return set(w, trailing, ink);
}
if gl.is_soft_hyphen() {
return w + hyphen_glyph(gl).adv;
}
w += gl.adv;
if gl.break_after() {
break;
end += 1;
if gl.is_space() {
trailing += gl.adv;
} else {
(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) {
return set(w, trailing, ink);
}
}
w
if end >= g.len() { set(w, trailing, ink) } else { w }
}
/// Greedy break: returns (end glyph index, hyphenated) for a line starting at `i` of `width`.
+12 -11
View File
@@ -71,6 +71,12 @@ fn compose_para(
return None;
}
let total: f64 = sg.iter().map(|g| g.adv).sum();
// The same rule as the line loop below: an opening bracket starting a wrapped line gives up
// the space before it.
let start_credit = |i: usize| {
let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf;
sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0)
};
let mut sim = pen.clone();
let mut widths = vec![];
let mut acc = 0.0;
@@ -80,8 +86,9 @@ fn compose_para(
let first = widths.is_empty();
let ind_l = para.laid_out_left_indent() + if first && !continued { para.first_line_indent } else { 0.0 };
// 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.
let word = if first { word_width(sg, 0) } else { 0.0 };
// 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 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);
@@ -106,13 +113,7 @@ fn compose_para(
// stop at four times its stretch and fall back to the single-line composer; the documented
// default range (word spacing up to 133%) is narrow enough that most paragraphs would.
let (strict, loose) = (1.0, f64::INFINITY);
// The same rule as the line loop below: an opening bracket starting a wrapped line gives up
// the space before it.
let start_credit = |i: usize| {
let flush = !rtl && para.mojikumi == Mojikumi::LineEndHalf;
sg.get(i).filter(|g| flush && g.lead <= 0.0).and_then(|g| punct_half(g, Punct::Opening)).unwrap_or(0.0)
};
// …and its last character is set narrower, as the line loop sets it.
// A line's last character is set narrower, as the line loop sets it.
let end_credit = |end: usize| end.checked_sub(1).and_then(|k| line_end.get(k)).copied().unwrap_or(0.0);
let pass = |p: &Params| compose(sg, &width, &start_credit, &end_credit, &cands, flex, p);
pass(&params(strict)).or_else(|| pass(&params(loose)))
@@ -352,8 +353,6 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
let est = if *i < n { Metrics::of(&sg[*i]) } else { *pm };
let first_line = *para_line == 0 && !*continued;
let (ind_l, ind_r) = line_indents(para, first_line, *mirror);
// Measured before Mojikumi narrows an opening bracket, as the composer measures it.
let word = word_width(sg, *i);
// Mojikumi: an opening bracket starting a line is set flush with the line's start (the
// space before it goes), and the line has that much more room. At a paragraph's start
// that is the first-line indent: JIS X 4051's principle (JLREQ 3.1.5, Figure 71 ①).
@@ -366,6 +365,8 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
glyph.adv -= half;
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);
// Place, break, then settle the baseline on the line's real metrics (moving on to the
// next row/column if it no longer fits).
loop {
+100
View File
@@ -1145,6 +1145,106 @@ fn mojikumi_line_end_half_width_counts_when_a_line_breaks() {
}
}
/// Mojikumi: in a frame that is narrow at the top, and in a frame a wrap object narrows at the top,
/// a line's first word is measured as the line sets it. A word ending with a closing bracket that
/// fits the narrow lines only with the bracket half width, and an opening bracket that fits them
/// only flush with the line's start, start on the first line, with both composers. An opening
/// bracket that kinsoku keeps with the character after it, and a No Break run, are measured whole.
#[test]
fn mojikumi_narrows_a_lines_first_word_when_looking_for_room() {
use crate::test_fonts::{FULL_WIDTH_FAMILY, full_width_font};
use vectorcraft_doc::{Composer, Kinsoku, KinsokuShoriType, Mojikumi, TextWrap, WrapShape};
let db = FontDb::with_font_dirs(vec![]);
db.add_font(full_width_font().expect("test font"));
// The top 40 pt of the frame are `top` wide, the rest 200: an L-shaped frame, or a rectangle
// with a wrap object over the top right.
let lay = |text: &str, styled: fn(&mut TextObject), composer: Composer, top: f64, wrapped: bool| {
let style = CharStyle { size: 20.0, font_family: FULL_WIDTH_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() };
let mut t = TextObject::point(Point::ZERO, text, style);
t.xf = Affine::IDENTITY;
styled(&mut t);
t.para.mojikumi = Mojikumi::LineEndHalf;
t.para.composer = composer;
t.para.kinsoku = Kinsoku::Hard;
t.para.kinsoku_type = KinsokuShoriType::PushOutOnly;
let frame = if wrapped {
t.wrap = vec![WrapShape {
path: PathData::from_bezpath(&Rect::new(top, -10.0, 210.0, 40.0).to_path(0.1)),
wrap: TextWrap { offset: 0.0, invert: false },
}];
Rect::new(0.0, 0.0, 200.0, 200.0).to_path(0.1)
} else {
let mut p = kurbo::BezPath::new();
p.move_to((0.0, 0.0));
p.line_to((top, 0.0));
p.line_to((top, 40.0));
p.line_to((200.0, 40.0));
p.line_to((200.0, 200.0));
p.line_to((0.0, 200.0));
p.close_path();
p
};
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) };
layout(&db, &t)
};
let plain: fn(&mut TextObject) = |_| {};
let wide_bracket: fn(&mut TextObject) = |t| edit::style_range(&mut t.runs, 0, '「'.len_utf8(), |s| s.h_scale = 250.0);
let no_break: fn(&mut TextObject) = |t| {
let n = t.plain_text().len();
edit::style_range(&mut t.runs, 0, n, |s| s.no_break = true);
};
let no_break_but_the_last_word: fn(&mut TextObject) = |t| {
let n = t.plain_text().rfind(' ').map_or(0, |k| k + 1);
edit::style_range(&mut t.runs, 0, n, |s| s.no_break = true);
};
// "ABCD」" is `full` wide inside a line; ending one, 」 is half width.
let closing = "ABCD」EFGH";
let open = lay(closing, plain, Composer::SingleLine, 200.0, false);
let full: f64 = open.glyphs[..5].iter().map(|g| g.advance).sum();
assert!((open.glyphs[4].advance - 20.0).abs() < 1e-9, "」 is one em inside a line");
for wrapped in [false, true] {
for composer in [Composer::SingleLine, Composer::EveryLine] {
let at = format!("wrapped {wrapped} {composer:?}");
let top = full - 5.0;
let l = lay(closing, plain, composer, top, wrapped);
let first = l.lines.first().expect("a line");
assert_eq!(&closing[first.start..first.end], "ABCD」", "{at}");
assert!(first.baseline < 40.0, "{at}: the word starts on the narrow lines: {}", first.baseline);
let set: f64 = l.glyphs[first.glyph_start..first.glyph_end].iter().map(|g| g.advance).sum();
assert!(set <= top + 1e-9, "{at}: {set} in {top}");
// 「 is 50 pt at 250%, 25 pt flush with the line's start: 「一 is 45 pt.
let opening = "「一二三四五六";
let l = lay(opening, wide_bracket, composer, 47.0, wrapped);
let first = l.lines.first().expect("a line");
assert_eq!(&opening[first.start..first.end], "「一", "{at}");
assert!(first.baseline < 40.0, "{at}: 「 starts on the narrow lines: {}", first.baseline);
let set: f64 = l.glyphs[first.glyph_start..first.glyph_end].iter().map(|g| g.advance).sum();
assert!(set <= 47.0 + 1e-9, "{at}: {set}");
// Kinsoku keeps 「 with 一: in 40 pt they don't fit, and the line starts below, whole.
let l = lay(opening, wide_bracket, composer, 40.0, wrapped);
let first = l.lines.first().expect("a line");
assert!(first.baseline > 40.0 && &opening[first.start..first.end] != "「", "{at}: kinsoku: {:?}", placed_lines(&l, opening));
// A No Break run is one word, its space included: it doesn't fit the narrow lines.
let run_text = "ABCD EFGH";
let run: f64 = lay(run_text, no_break, composer, 200.0, false).glyphs.iter().map(|g| g.advance).sum();
let l = lay(run_text, no_break, composer, run - 5.0, wrapped);
let first = l.lines.first().expect("a line");
assert!(first.baseline > 40.0 && &run_text[first.start..first.end] == run_text, "{at}: no break: {:?}", placed_lines(&l, run_text));
// …but the space ending a No Break run is not set at the line's end: the run fits a
// line 2 pt wider than it is without that space.
let ending = "ABCD EFGH IJ";
let l = lay(ending, no_break_but_the_last_word, composer, run + 2.0, wrapped);
let first = l.lines.first().expect("a line");
assert!(first.baseline < 40.0 && ending[first.start..first.end].trim_end() == run_text, "{at}: {:?}", placed_lines(&l, ending));
}
}
}
/// Each line's baseline and text.
fn placed_lines(l: &TextLayout, text: &str) -> Vec<(f64, String)> {
l.lines.iter().map(|line| (line.baseline, text[line.start..line.end].to_string())).collect()
}
/// Burasagari: in a measure of exactly five ems, a comma that would be the sixth character goes to
/// the next line with the character before it (None) or hangs outside the line (Standard, Forced);
/// a full stop that is the fifth character stays inside (None, Standard) or hangs while the four
File diff suppressed because one or more lines are too long