Skip to content

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

refactor: split complex functions in ruby, warichu, pdf text, render text, epub, pdfx (Sonar S3776) (#1728)

Dylan M. Taylorc313c5349761
diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs
index 1afea6b0d..47c48a728 100644
--- a/crates/compose/src/ruby.rs
+++ b/crates/compose/src/ruby.rs
@@ -71,6 +71,36 @@ fn tcy_char(c: char, roman: bool) -> bool {
c.is_ascii_digit() || (roman && c.is_ascii_alphabetic())
}
+/// Tate-chu-yoko in vertical ruby: each short run of digits (and Latin letters) is set in one
+/// ruby em across the line, scaled down to fit when the spec asks for it.
+fn apply_tcy(glyphs: &mut [RubyGlyph], spec: &RubySpec, size: f64) {
+ let roman = spec.auto_tcy_include_roman;
+ let mut i = 0;
+ while i < glyphs.len() {
+ let j = i + glyphs.get(i..).unwrap_or_default().iter().take_while(|g| tcy_char(g.ch, roman)).count();
+ if j == i {
+ i += 1;
+ continue;
+ }
+ if u32::try_from(j - i).is_ok_and(|n| n <= spec.auto_tcy_digits)
+ && let Some(run) = glyphs.get_mut(i..j)
+ {
+ let total: f64 = run.iter().map(|g| g.adv).sum();
+ let f = if spec.auto_tcy_auto_scale && total > size && total > 0.0 { size / total } else { 1.0 };
+ let mut across = -total * f / 2.0;
+ for (n, g) in run.iter_mut().enumerate() {
+ g.tcy = Some([size / 2.0, across + g.x * f, size]);
+ across += g.adv * f;
+ g.sx *= f;
+ g.x = 0.0;
+ g.adv = if n == 0 { size } else { 0.0 };
+ g.joined = n > 0;
+ }
+ }
+ i = j;
+ }
+}
+
/// Shape `text` as the ruby of parent text `parent_size` points big.
fn shape_ruby(db: &ScopedFonts<'_>, parent: FaceRef, text: &str, spec: &RubySpec, parent_size: f64, fallback: bool, vertical: bool) -> Shaped {
let size = spec.size_for(parent_size);
@@ -96,31 +126,7 @@ fn shape_ruby(db: &ScopedFonts<'_>, parent: FaceRef, text: &str, spec: &RubySpec
.collect();
// Tate-chu-yoko: short runs of digits (and Latin letters) take one ruby em along the line.
if vertical && spec.auto_tcy_digits > 0 {
- let roman = spec.auto_tcy_include_roman;
- let mut i = 0;
- while i < glyphs.len() {
- let j = i + glyphs.get(i..).unwrap_or_default().iter().take_while(|g| tcy_char(g.ch, roman)).count();
- if j == i {
- i += 1;
- continue;
- }
- if u32::try_from(j - i).is_ok_and(|n| n <= spec.auto_tcy_digits)
- && let Some(run) = glyphs.get_mut(i..j)
- {
- let total: f64 = run.iter().map(|g| g.adv).sum();
- let f = if spec.auto_tcy_auto_scale && total > size && total > 0.0 { size / total } else { 1.0 };
- let mut across = -total * f / 2.0;
- for (n, g) in run.iter_mut().enumerate() {
- g.tcy = Some([size / 2.0, across + g.x * f, size]);
- across += g.adv * f;
- g.sx *= f;
- g.x = 0.0;
- g.adv = if n == 0 { size } else { 0.0 };
- g.joined = n > 0;
- }
- }
- i = j;
- }
+ apply_tcy(&mut glyphs, spec, size);
}
// Pen positions: a joined glyph sits at its group's start.
let mut pen = 0.0;
diff --git a/crates/compose/src/warichu.rs b/crates/compose/src/warichu.rs
index 14b732e5e..8418faac4 100644
--- a/crates/compose/src/warichu.rs
+++ b/crates/compose/src/warichu.rs
@@ -93,6 +93,21 @@ fn line_count(len: usize, want: usize, before: usize, after: usize) -> usize {
1
}
+/// The per-line counts recovered from the split table, or `None` when they don't cover all `m`.
+fn trace_counts(take: &[Vec<usize>], n: usize, m: usize) -> Option<Vec<usize>> {
+ let mut counts = Vec::with_capacity(n);
+ let mut s = 0_usize;
+ for lines in (1..=n).rev() {
+ let t = take[lines][s];
+ if t == 0 || s + t > m {
+ return None;
+ }
+ counts.push(t);
+ s += t;
+ }
+ (s == m).then_some(counts)
+}
+
/// Glyph counts for `n` lines. Minimises the widest line, and the first and last lines keep their
/// break minimums. One line when no split satisfies them.
fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec<usize> {
@@ -142,17 +157,7 @@ fn split_even(advs: &[f64], n: usize, before: usize, after: usize) -> Vec<usize>
if !best[n][0].is_finite() {
return vec![m];
}
- let mut counts = Vec::with_capacity(n);
- let mut s = 0_usize;
- for lines in (1..=n).rev() {
- let t = take[lines][s];
- if t == 0 || s + t > m {
- return vec![m];
- }
- counts.push(t);
- s += t;
- }
- if s != m { vec![m] } else { counts }
+ trace_counts(&take, n, m).unwrap_or_else(|| vec![m])
}
fn restore(line: &mut [PlacedGlyph], members: &[usize], saved: &[(f64, f64, f64, f64)]) {
diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs
index 1df759608..348b9c80e 100644
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@ -785,6 +785,39 @@ impl<'a, 'f> StoryWriter<'a, 'f> {
close_blocks(&mut list, &mut pre, out);
}
+ /// The markup for one run's text `raw` (starting at byte `a` of the story): anchored objects
+ /// and notes where their marks are.
+ fn run_markup(&mut self, st: &Story, raw: &str, a: usize, depth: usize, after: &mut String) -> String {
+ let doc = self.doc;
+ let mut t = String::new();
+ let mut seg_start = 0;
+ // Index of the next anchored object: marks count from the story start, as
+ // `Story::object_at` counts them (counted once, at the run's first mark).
+ let mut mark: Option<usize> = None;
+ for (i, c) in raw.char_indices() {
+ if c != FOOTNOTE_REF && c != ENDNOTE_REF && c != OBJECT_MARK {
+ continue;
+ }
+ t.push_str(&run_text(doc, raw.get(seg_start..i).unwrap_or_default()));
+ seg_start = i + c.len_utf8();
+ if c == OBJECT_MARK {
+ let k = mark.unwrap_or_else(|| st.text.get(..a).map_or(0, |t| t.matches(OBJECT_MARK).count()));
+ mark = Some(k.saturating_add(1));
+ if let Some(o) = st.objects.get(k) {
+ t.push_str(&self.object(o));
+ }
+ } else if depth < MAX_DEPTH {
+ if c == FOOTNOTE_REF {
+ self.footnote(st, a + i, depth, &mut t, after);
+ } else {
+ self.endnote(st, a + i, depth, &mut t);
+ }
+ }
+ }
+ t.push_str(&run_text(doc, raw.get(seg_start..).unwrap_or_default()));
+ t
+ }
+
/// The runs of paragraph `para` of `st`; footnotes go to `after`.
fn runs(&mut self, st: &Story, para: std::ops::Range<usize>, depth: usize, out: &mut String, after: &mut String) {
let doc = self.doc;
@@ -799,32 +832,7 @@ impl<'a, 'f> StoryWriter<'a, 'f> {
continue;
}
let Some(raw) = st.text.get(a..b) else { continue };
- let mut t = String::new();
- let mut seg_start = 0;
- // Index of the next anchored object: marks count from the story start, as
- // `Story::object_at` counts them (counted once, at the run's first mark).
- let mut mark: Option<usize> = None;
- for (i, c) in raw.char_indices() {
- if c != FOOTNOTE_REF && c != ENDNOTE_REF && c != OBJECT_MARK {
- continue;
- }
- t.push_str(&run_text(doc, raw.get(seg_start..i).unwrap_or_default()));
- seg_start = i + c.len_utf8();
- if c == OBJECT_MARK {
- let k = mark.unwrap_or_else(|| st.text.get(..a).map_or(0, |t| t.matches(OBJECT_MARK).count()));
- mark = Some(k.saturating_add(1));
- if let Some(o) = st.objects.get(k) {
- t.push_str(&self.object(o));
- }
- } else if depth < MAX_DEPTH {
- if c == FOOTNOTE_REF {
- self.footnote(st, a + i, depth, &mut t, after);
- } else {
- self.endnote(st, a + i, depth, &mut t);
- }
- }
- }
- t.push_str(&run_text(doc, raw.get(seg_start..).unwrap_or_default()));
+ let t = self.run_markup(st, raw, a, depth, after);
let (ctag, cls) = if f.style != story::NO_CHAR_STYLE {
let (tag, class) = export_mapping(&doc.styles, &f.style, true, &self.cc);
(tag, format!(" class=\"{}\"", xml_attr(&class)))
diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs
index 9aaeb445a..11d30602b 100644
--- a/crates/pdf/src/pdfx.rs
+++ b/crates/pdf/src/pdfx.rs
@@ -392,18 +392,7 @@ impl RgbScan {
}
b"BI" | b"EI" if !managed => {
if let Some(Object::Stream(img)) = last {
- let cs = img.dict().get::<Object<'_>>(b"CS").or_else(|| img.dict().get::<Object<'_>>(b"ColorSpace"));
- let cs = match cs {
- Some(Object::Name(n))
- if !matches!(n.as_ref(), b"DeviceRGB" | b"RGB" | b"G" | b"DeviceGray" | b"CMYK" | b"DeviceCMYK") =>
- {
- res.get_color_space(&n)
- }
- cs => cs,
- };
- if cs.is_some_and(|cs| is_device_rgb(&cs)) {
- self.add("an RGB inline image".into());
- }
+ self.inline_image(&img, res);
}
}
_ => {}
@@ -411,6 +400,20 @@ impl RgbScan {
}
}
+ /// An inline image (`BI … EI`) in an RGB space, named directly or through the resources.
+ fn inline_image(&mut self, img: &Stream<'_>, res: &Resources<'_>) {
+ let cs = img.dict().get::<Object<'_>>(b"CS").or_else(|| img.dict().get::<Object<'_>>(b"ColorSpace"));
+ let cs = match cs {
+ Some(Object::Name(n)) if !matches!(n.as_ref(), b"DeviceRGB" | b"RGB" | b"G" | b"DeviceGray" | b"CMYK" | b"DeviceCMYK") => {
+ res.get_color_space(&n)
+ }
+ cs => cs,
+ };
+ if cs.is_some_and(|cs| is_device_rgb(&cs)) {
+ self.add("an RGB inline image".into());
+ }
+ }
+
fn image(&mut self, img: &Stream<'_>, managed: bool) {
let id = img.obj_id();
if managed || !self.seen.insert(id) || img.dict().get::<bool>(b"ImageMask") == Some(true) {
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index 1aaf435d9..7687bd2f8 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -303,6 +303,25 @@ impl Exporter<'_> {
});
}
+ /// One table cell's graphic, or its text composed in the cell's own area.
+ fn table_cell(&mut self, s: &mut Surface, c: &designcraft_compose::PlacedCell) {
+ if let Some(g) = &c.graphic {
+ if let Some(clip) = to_path(&c.clip.to_path(0.1)) {
+ s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero);
+ s.push_transform(&tf(Affine::translate((c.clip.x0, c.clip.y0))));
+ self.graphic(s, g);
+ s.pop();
+ s.pop();
+ }
+ } else if let Some(cft) = c.text.frames.first() {
+ s.push_transform(&tf(Affine::translate(c.origin.to_vec2())));
+ let area = std::mem::replace(&mut self.text_area, lines_area(cft));
+ self.frame_text(s, &c.text, cft, &c.source);
+ self.text_area = area;
+ s.pop();
+ }
+ }
+
/// Table fragments: cell fills, cell text (real text), edges and the border.
fn tables(&mut self, s: &mut Surface, ft: &FrameText) {
for t in &ft.tables {
@@ -314,21 +333,7 @@ impl Exporter<'_> {
}
}
for c in &t.cells {
- if let Some(g) = &c.graphic {
- if let Some(clip) = to_path(&c.clip.to_path(0.1)) {
- s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero);
- s.push_transform(&tf(Affine::translate((c.clip.x0, c.clip.y0))));
- self.graphic(s, g);
- s.pop();
- s.pop();
- }
- } else if let Some(cft) = c.text.frames.first() {
- s.push_transform(&tf(Affine::translate(c.origin.to_vec2())));
- let area = std::mem::replace(&mut self.text_area, lines_area(cft));
- self.frame_text(s, &c.text, cft, &c.source);
- self.text_area = area;
- s.pop();
- }
+ self.table_cell(s, c);
}
for seg in &t.strokes {
let st = &seg.stroke;
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index a4fa80ad0..a9cdc5ce3 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -156,6 +156,22 @@ fn union(r: Option<Rect>, b: Rect) -> Option<Rect> {
Some(r.map_or(b, |r| r.union(b)))
}
+/// Add a rule bar, joined onto the previous one when it continues the same stretch.
+fn push_bar(bars: &mut Vec<(String, f32, Rect)>, color: &str, tint: f32, r: Rect) {
+ match bars.last_mut() {
+ Some((c, t, last))
+ if c.as_str() == color
+ && *t == tint
+ && (last.y0 - r.y0).abs() < 1e-6
+ && (last.y1 - r.y1).abs() < 1e-6
+ && (r.x0 - last.x1).abs() < 0.5 =>
+ {
+ last.x1 = last.x1.max(r.x1);
+ }
+ _ => bars.push((color.to_owned(), tint, r)),
+ }
+}
+
fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> LineGlyphs {
let mut runs: Vec<(u32, BezPath)> = Vec::new();
let mut underlines: Vec<(String, f32, Rect)> = Vec::new();
@@ -171,18 +187,7 @@ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> Line
let r = rule.rect(g.x, g.x + g.adv, designcraft_compose::rule_baseline(style, l, g));
// One bar per stretch, as the PDF export draws them: a bar per glyph left
// anti-aliased seams between the letters.
- match bars.last_mut() {
- Some((color, tint, last))
- if *color == rule.color
- && *tint == rule.tint
- && (last.y0 - r.y0).abs() < 1e-6
- && (last.y1 - r.y1).abs() < 1e-6
- && (r.x0 - last.x1).abs() < 0.5 =>
- {
- last.x1 = last.x1.max(r.x1);
- }
- _ => bars.push((rule.color.clone(), rule.tint, r)),
- }
+ push_bar(bars, &rule.color, rule.tint, r);
}
}
// A tab carries the rule across its width but draws nothing itself.