Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Compose: No Break runs and nonbreaking spaces stretch on justified lines (#368)

aiongg42cfc8b06c28
diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs
index 754cfc3d0..9688c1f0d 100644
--- a/crates/compose/src/breaker.rs
+++ b/crates/compose/src/breaker.rs
@@ -81,15 +81,20 @@ impl Spacing {
if !self.justify || g.locked_advance {
return ([0.0; 3], [0.0; 3]);
}
+ // A space that is no break opportunity (No Break, U+00A0) is a box with word-space elasticity.
+ if g.is_justify_space() {
+ let (st, sh) = self.space_elastic(g);
+ return ([st, 0.0, 0.0], [sh, 0.0, 0.0]);
+ }
let natural = g.adv / self.glyph_desired.max(0.01);
(
[0.0, g.space * (self.letter_max - self.letter_desired).max(0.0), natural * (self.glyph_max - self.glyph_desired).max(0.0)],
[0.0, g.space * (self.letter_desired - self.letter_min).max(0.0), natural * (self.glyph_desired - self.glyph_min).max(0.0)],
)
}
- /// Word-space stretch and shrink of space glyph `g` (only U+0020 is elastic).
+ /// Word-space stretch and shrink of space glyph `g` (see [`Glyph::is_word_space`]).
fn space_elastic(&self, g: &Glyph) -> (f64, f64) {
- if g.ch != ' ' && !(g.ch == '\u{3000}' && g.ideographic_space_elastic) {
+ if !g.is_word_space() {
return (0.0, 0.0);
}
(g.space * (self.word_max - self.word_desired).max(0.0), g.space * (self.word_desired - self.word_min).max(0.0))
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3dd7c25b3..30c0a0fab 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -1525,7 +1525,7 @@ fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) {
if g.locked_advance {
continue;
}
- if g.ch == ' ' || (g.ch == '\u{3000}' && g.ideographic_space_elastic) {
+ if g.is_word_space() {
g.adv += g.space * (ws - 1.0);
} else if !g.is_space() && g.adv > 0.0 {
g.adv = g.adv * gs + ls * g.space;
@@ -2260,7 +2260,7 @@ fn layout_line(
// a line whose last tab is a right, centre, character or right-indent tab is not justified.
let seg = last_tab.map_or(0, |(i, _)| i + 1);
let seg_justifies = last_tab.is_none_or(|(_, left)| left);
- let spaces: Vec<usize> = line.iter().enumerate().skip(seg).filter(|(_, g)| g.is_space() && !g.no_break).map(|(i, _)| i).collect();
+ let spaces: Vec<usize> = line.iter().enumerate().skip(seg).filter(|(_, g)| g.is_justify_space()).map(|(i, _)| i).collect();
let align = match pp.align {
Align::TowardsSpine => {
if left_page {
@@ -2361,7 +2361,7 @@ fn layout_line(
let mut ratio_n = 0usize;
for &i in &spaces {
let g = &line[i];
- if g.ch == ' ' && g.space > 0.0 {
+ if matches!(g.ch, ' ' | shape::NBSP) && g.space > 0.0 {
ratio_sum += (g.adv + add[i]) / g.space;
ratio_n += 1;
}
@@ -2547,7 +2547,7 @@ fn distribute(line: &[Glyph], spaces: &[usize], extra: f64, sp: &Spacing, add: &
.iter()
.map(|&i| {
let g = &line[i];
- if g.ch != ' ' && !(g.ch == '\u{3000}' && g.ideographic_space_elastic) {
+ if !g.is_word_space() {
0.0
} else if stretch {
g.space * (sp.word_max - sp.word_desired).max(0.0)
@@ -2557,8 +2557,8 @@ fn distribute(line: &[Glyph], spaces: &[usize], extra: f64, sp: &Spacing, add: &
})
.collect();
// Letter gaps: between visible glyphs (not after the line's last glyph).
- let last_box = line.iter().rposition(|g| !g.is_space() && g.adv > 0.0).unwrap_or(0);
- let is_box = |i: usize, g: &Glyph| i < last_box && !g.is_space() && g.adv > 0.0 && (!g.locked_advance || g.break_after != Some(false));
+ let last_box = line.iter().rposition(|g| !g.is_justify_space() && g.adv > 0.0).unwrap_or(0);
+ let is_box = |i: usize, g: &Glyph| i < last_box && !g.is_justify_space() && g.adv > 0.0 && (!g.locked_advance || g.break_after != Some(false));
let letter: Vec<f64> = line
.iter()
.enumerate()
@@ -2575,7 +2575,7 @@ fn distribute(line: &[Glyph], spaces: &[usize], extra: f64, sp: &Spacing, add: &
let glyph: Vec<f64> = line
.iter()
.map(|g| {
- if g.is_space() || g.adv <= 0.0 || g.locked_advance {
+ if g.is_justify_space() || g.adv <= 0.0 || g.locked_advance {
0.0
} else {
let natural = g.adv / sp.glyph_desired.max(0.01);
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 1e1af40a7..229368266 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -70,12 +70,23 @@ impl Glyph {
pub fn is_space(&self) -> bool {
matches!(self.ch, ' ' | '\u{2002}'..='\u{200A}') || (self.ch == '\u{3000}' && self.ideographic_space_elastic)
}
+ /// A space whose width justification and word spacing vary: U+0020, the nonbreaking space
+ /// U+00A0 and an elastic ideographic space. Fixed-width spaces (U+2002–U+200A, U+202F) keep theirs.
+ pub fn is_word_space(&self) -> bool {
+ matches!(self.ch, ' ' | NBSP) || (self.ch == '\u{3000}' && self.ideographic_space_elastic)
+ }
+ /// A space that justification treats as a word space rather than a letter: [`Self::is_space`]
+ /// plus U+00A0, which is never a break opportunity.
+ pub fn is_justify_space(&self) -> bool {
+ self.is_space() || self.ch == NBSP
+ }
pub fn is_letter(&self) -> bool {
self.ch.is_alphabetic() || matches!(self.ch, '\'' | '’')
}
}
pub const SOFT_HYPHEN: char = '\u{AD}';
+pub const NBSP: char = '\u{A0}';
/// Shaped paragraph.
pub struct ShapedPara {
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 0d1fe2d27..ef61b4abc 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -325,6 +325,67 @@ fn hyphenation_skips_a_no_break_word_at_the_start() {
assert!(!first.hyphenated && first.range.end >= 15, "{:?}", &text[first.range.clone()]);
}
+/// Natural advance of each glyph of `text` by byte, and a frame width that puts the first three
+/// words on a justified line with one word space of extra to share.
+fn three_word_measure(text: &str) -> (std::collections::HashMap<usize, f64>, f64) {
+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 1000.0, 100.0), ParaAttrs::default());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let line = all_lines(&cs)[0];
+ let adv = line.glyphs.iter().map(|g| (g.byte, g.adv)).collect::<std::collections::HashMap<_, _>>();
+ let third_end = text.find(" dddd").unwrap();
+ let gap = line.glyphs.iter().find(|g| g.byte == third_end).unwrap();
+ (adv, gap.x - line.x0 + gap.adv + 2.0 * line.x0)
+}
+
+fn justified_first_line(text: &str, width: f64, no_break: Option<std::ops::Range<usize>>) -> Line {
+ let para = ParaAttrs { align: Some(Align::LeftJustified), word_space_max: Some(4.0), ..Default::default() };
+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 1000.0), para);
+ if let Some(run) = no_break {
+ d.story_mut(sid).unwrap().format_chars(run, |f| f.over.no_break = Some(true));
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let line = all_lines(&cs)[0].clone();
+ assert!((line.end_x - line.x1).abs() < 0.1, "line ends at {} not {}", line.end_x, line.x1);
+ line
+}
+
+#[test]
+fn no_break_spaces_stretch_on_justified_lines() {
+ let text = "aaaa bbbb cccc dddd eeee ffff gggg hhhh";
+ let (natural, width) = three_word_measure(text);
+ // The run holds one of the line's two spaces, then both.
+ for run in [0..9, 0..14] {
+ let line = justified_first_line(text, width, Some(run.clone()));
+ assert_eq!(text[line.range.clone()].trim_end(), "aaaa bbbb cccc");
+ let words = line.glyphs.iter().filter(|g| g.byte < 14);
+ let (spaces, letters): (Vec<_>, Vec<_>) = words.partition(|g| text.as_bytes()[g.byte] == b' ');
+ assert_eq!(spaces.len(), 2);
+ for s in &spaces {
+ assert!(s.adv > natural[&s.byte] + 1.0 && (s.adv - spaces[0].adv).abs() < 1e-6, "run {run:?}: space at {} is {}", s.byte, s.adv);
+ }
+ for g in letters {
+ assert!((g.adv - natural[&g.byte]).abs() < 1e-6, "run {run:?}: letter at {} is {}", g.byte, g.adv);
+ }
+ }
+}
+
+#[test]
+fn nonbreaking_space_stretches_and_fixed_width_one_does_not() {
+ for (nb, stretches) in [('\u{A0}', true), ('\u{202F}', false)] {
+ let text = format!("aaaa{nb}bbbb cccc dddd eeee ffff gggg hhhh");
+ let (natural, width) = three_word_measure(&text);
+ let line = justified_first_line(&text, width, None);
+ let nb_glyph = line.glyphs.iter().find(|g| g.byte == 4).unwrap();
+ let space = line.glyphs.iter().find(|g| text.as_bytes()[g.byte] == b' ').unwrap();
+ assert!(space.adv > natural[&space.byte] + 1.0);
+ if stretches {
+ assert!((nb_glyph.adv - space.adv).abs() < 1e-6, "{nb:?}: {} vs {}", nb_glyph.adv, space.adv);
+ } else {
+ assert!((nb_glyph.adv - natural[&4]).abs() < 1e-6, "{nb:?}: {} vs {}", nb_glyph.adv, natural[&4]);
+ }
+ }
+}
+
/// Story of `n` one-line filler paragraphs followed by `extra` paragraphs, in a 2-column frame.
fn keep_doc(fillers: usize, extra: &[&str], height: f64) -> (Document, StoryId, Vec<usize>) {
let mut parts: Vec<String> = (0..fillers).map(|k| format!("Filler {k}")).collect();