Skip to content

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

T: ruby and kenten

Brandon Thomas5294c8f677d3
diff --git a/ROADMAP.md b/ROADMAP.md
index 15ac74e28..0c90e24a4 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -105,7 +105,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Colour management exposed: Edit ▸ Color Settings (`color.settings`: RGB/CMYK working spaces, intent, black-point compensation; `color.loadProfile` for ICC files; `color.convert` through the working spaces, with gamut checks) and View ▸ Proof Setup / Proof Colors (press, sRGB, legacy Mac RGB, colour-blindness simulations, simulate paper) on the canvas.
- Keyboard: Tab / Shift+Tab hide and show all panels / all but Tools (`window.hidePanels`, `window.hidePanelsExceptTools`); Cmd+F6 / Cmd+Shift+F6 cycle documents; panel fields are reached with Tab and Escape returns to the layout.
- View ▸ Rotate Spread (`view.rotateSpread`, `layout.rotateSpreadView`): the spread in view turns in quarter turns on screen (stored with the document; output is unaffected). The canvas maps each spread through its own transform, so tools, snapping, resize handles, guides, overlays and rendering all follow the turned spread.
-- Vertical type (Vertical Type Tool, Type ▸ Story Direction, `object.textFrameOptions {vertical}`, IDML StoryOrientation): lines run top to bottom and follow each other right to left; CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text). Punctuation and brackets take their vertical forms (OpenType `vert`/`vrt2`) in vertical frames. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Vertical metrics (`vmtx`) and warichu aren't there yet.
+- Vertical type (Vertical Type Tool, Type ▸ Story Direction, `object.textFrameOptions {vertical}`, IDML StoryOrientation): lines run top to bottom and follow each other right to left; CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text). Punctuation and brackets take their vertical forms (OpenType `vert`/`vrt2`) in vertical frames. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Ruby (Type ▸ Ruby…, `type.ruby`, IDML RubyString; group ruby spread 1-2-1 or centred) and kenten emphasis dots (`type.kenten`, IDML KentenKind) are set over their text — to its right in vertical frames — without changing line breaks. Vertical metrics (`vmtx`), warichu and ruby options (per-character ruby, positions, overhang) aren't there yet.
- Math expressions (Type ▸ Insert Math Expression…, `math.insert`, `math.svg`): a LaTeX subset (fractions, scripts, roots, big operators with limits, Greek, relations and operators with math spacing, `\left…\right`, `\text`) typeset by our own engine into SVG, placed inline at the cursor or as a frame; the LaTeX is kept as alt text and can be edited.
- Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen; in exported PDFs such graphics go out as 300 ppi images of their visible layers.
- Effects: Inner Glow (edge or centre), Bevel and Emboss (inner bevel lit from the light angle), Satin (`object.innerGlow`, `object.bevel`, `object.satin`); PDF export now keeps soft effects: objects with shadows, glows, feathers, bevels or satin go out as 300 ppi transparent images of their appearance (threaded text frames excepted).
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index fb85c1771..b48591fc9 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -14,6 +14,7 @@ mod cache;
pub mod hyphen;
mod notes;
mod overlay;
+mod ruby;
pub mod shape;
pub mod table;
pub mod vars;
@@ -62,6 +63,9 @@ pub struct RunStyle {
pub inserted: bool,
/// XML element the text is tagged with (tag markers on screen).
pub xml_tag: Option<String>,
+ /// Ruby over the run, and kenten (emphasis dots).
+ pub ruby: Option<String>,
+ pub kenten: bool,
}
/// An underline or strikethrough bar: its top edge `offset` below the baseline (negative =
@@ -788,8 +792,9 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
let lx0 = x0 + ind_l;
let lx1 = x1 - pp.right_indent;
let last = k + 1 == breaks.len();
- let (placed, end_x, ratio) =
+ let (mut placed, end_x, ratio) =
layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page);
+ ruby::annotate(&styles_tab, &mut placed);
let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };
let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);
let range_start = if line_no == 0 { prange.start } else { range_start };
diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs
new file mode 100644
index 000000000..b2ba294ba
--- /dev/null
+++ b/crates/compose/src/ruby.rs
@@ -0,0 +1,114 @@
+//! Ruby and kenten: small glyphs set over laid-out text (to its right in vertical frames, where
+//! the frame's turn carries "above" there). They don't change line breaks or leading.
+
+use designcraft_geom::Shape as _;
+
+use crate::{PlacedGlyph, RunStyle, upright_in_vertical};
+
+/// Ruby and emphasis marks are half the base size.
+const SCALE: f64 = 0.5;
+
+/// A glyph of `text` set at `size` in `base`'s font from `x`, above the base text; returns them
+/// and their total advance.
+fn set(base: &PlacedGlyph, text: &str, size: f64, base_size: f64) -> (Vec<PlacedGlyph>, f64) {
+ let face = &base.face;
+ let k = size / face.units_per_em();
+ // Its baseline clears the base text's em box top.
+ let y = -(base_size * 0.88 + size * 0.2);
+ let mut x = 0.0;
+ let mut out = Vec::new();
+ for sg in designcraft_fonts::shape(face, text, &[], |c| c) {
+ let ch = text[sg.cluster..].chars().next().unwrap_or(' ');
+ let adv = sg.x_advance as f64 * k;
+ out.push(PlacedGlyph {
+ gid: sg.gid,
+ x: x + sg.x_offset as f64 * k,
+ y: y - sg.y_offset as f64 * k,
+ adv,
+ sx: k,
+ sy: k,
+ len: 0,
+ visible: true,
+ upright: upright_in_vertical(ch),
+ tcy: None,
+ rtl: false,
+ ..base.clone()
+ });
+ x += adv;
+ }
+ (out, x)
+}
+
+/// A sesame dot (or a bullet, when the font has none) centred over `b`.
+fn kenten(b: &PlacedGlyph, size: f64) -> Vec<PlacedGlyph> {
+ let (mut dot, mut w) = set(b, "\u{FE45}", size * SCALE, size);
+ if dot.first().is_some_and(|d| d.gid == 0) {
+ (dot, w) = set(b, "\u{2022}", size * SCALE, size);
+ }
+ // Centre the mark's ink (its advance may hold it off centre) and sit it just over the text.
+ let ink = dot.first().map(|d| designcraft_fonts::FontDb::global().outline(&d.face, d.gid).bounding_box()).filter(|r| r.width() > 0.0);
+ for d in &mut dot {
+ match ink {
+ Some(r) => {
+ d.x = b.x + b.adv / 2.0 - (r.x0 + r.x1) / 2.0 * d.sx;
+ d.y = -(size * 0.92) - r.y1 * d.sy;
+ }
+ None => d.x += b.x + (b.adv - w) / 2.0,
+ }
+ }
+ dot
+}
+
+/// Add the ruby and kenten of a laid-out line's glyphs.
+pub(crate) fn annotate(styles: &[RunStyle], line: &mut Vec<PlacedGlyph>) {
+ let style = |g: &PlacedGlyph| styles.get(g.style as usize);
+ if !line.iter().any(|g| style(g).is_some_and(|s| s.ruby.is_some() || s.kenten)) {
+ return;
+ }
+ let mut extra = Vec::new();
+ let mut i = 0;
+ while i < line.len() {
+ let g = &line[i];
+ let Some(st) = style(g).filter(|_| g.len > 0 && g.visible) else {
+ i += 1;
+ continue;
+ };
+ if st.kenten && g.adv > 0.0 {
+ extra.extend(kenten(g, st.size));
+ }
+ let Some(text) = &st.ruby else {
+ i += 1;
+ continue;
+ };
+ // The group: following glyphs with the same ruby.
+ let mut j = i + 1;
+ while j < line.len() && (line[j].len == 0 || style(&line[j]).is_some_and(|s| s.ruby.as_ref() == Some(text))) {
+ j += 1;
+ }
+ let base: Vec<&PlacedGlyph> = line[i..j].iter().filter(|b| b.len > 0).collect();
+ let x0 = base.iter().map(|b| b.x).fold(f64::MAX, f64::min);
+ let x1 = base.iter().map(|b| b.x + b.adv).fold(f64::MIN, f64::max);
+ let (mut glyphs, w) = set(g, text, st.size * SCALE, st.size);
+ let n = glyphs.len().max(1) as f64;
+ if w < x1 - x0 {
+ // Shorter than the base: spread out, half a gap at each end (the 1-2-1 rule).
+ let gap = (x1 - x0 - w) / n;
+ for (k, r) in glyphs.iter_mut().enumerate() {
+ r.x += x0 + gap * (k as f64 + 0.5);
+ }
+ } else {
+ // Longer: centred over the base.
+ let start = (x0 + x1 - w) / 2.0;
+ for r in &mut glyphs {
+ r.x += start;
+ }
+ }
+ extra.extend(glyphs);
+ // Kenten on the rest of the group.
+ for b in line[i + 1..j].iter().filter(|b| st.kenten && b.len > 0 && b.adv > 0.0) {
+ extra.extend(kenten(b, st.size));
+ }
+ i = j;
+ }
+ line.extend(extra);
+}
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index a91581bfe..8de7dc164 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -141,6 +141,8 @@ impl StyleTable<'_> {
condition: p.conditions.first().cloned(),
inserted: p.change == designcraft_doc::ChangeMark::Inserted,
xml_tag: (!p.xml_tag.is_empty()).then(|| p.xml_tag.clone()),
+ ruby: (!p.ruby.is_empty()).then(|| p.ruby.clone()),
+ kenten: p.kenten,
};
if let Some(i) = self.styles.iter().rposition(|s| *s == rs) {
return i as u32;
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index d8e669cc2..511a703a5 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -913,6 +913,34 @@ fn digits_option_draws_figures_in_another_script() {
assert_ne!(gid(&plain, 4), gid(&hindi, 4));
}
+#[test]
+fn ruby_and_kenten_sit_over_their_text() {
+ let mut d = Document::new(&designcraft_doc::build::NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "漢字です", ParaFormat::default()).unwrap();
+ let base_n = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();
+ let kanji = 0.."漢字".len();
+ d.story_mut(sid).unwrap().format_chars(kanji.clone(), |f| f.over.ruby = Some("かんじ".into()));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let ruby: Vec<_> = l.glyphs[base_n..].iter().collect();
+ assert_eq!(ruby.len(), 3, "one glyph per kana");
+ let size = cs.styles[l.glyphs[0].style as usize].size;
+ let (x0, x1) = (l.glyphs[0].x, l.glyphs[1].x + l.glyphs[1].adv);
+ // Above the base, half size, within the base's width (shorter: spread 1-2-1).
+ assert!(ruby.iter().all(|g| g.y < -size * 0.8 && g.len == 0 && (g.sx - l.glyphs[0].sx * 0.5).abs() < 1e-9));
+ assert!(ruby[0].x > x0 && ruby[2].x + ruby[2].adv < x1 + 1e-6, "{x0} {x1} {:?}", ruby.iter().map(|g| g.x).collect::<Vec<_>>());
+ // Caret positions ignore them.
+ assert_eq!(caret(&cs, "漢字".len()).unwrap().1, l.glyphs[2].x);
+ // Kenten: a dot over each character.
+ d.story_mut(sid).unwrap().format_chars(kanji.end..kanji.end + "で".len(), |f| f.over.kenten = Some(true));
+ let l = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();
+ assert_eq!(l.glyphs.len(), base_n + 4);
+ let dot = l.glyphs.last().unwrap();
+ let de = &l.glyphs[2];
+ assert!((dot.x + dot.adv / 2.0 - (de.x + de.adv / 2.0)).abs() < 1.0 && dot.y < 0.0);
+}
+
#[test]
fn tate_chu_yoko_sets_digits_across_one_em() {
let mut d = Document::new(&designcraft_doc::build::NewDocument::default());
diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs
index 50f900a0a..14f76ca5d 100644
--- a/crates/doc/src/attrs.rs
+++ b/crates/doc/src/attrs.rs
@@ -531,6 +531,11 @@ attr_set! {
no_break: bool = false,
/// Tate-chu-yoko: in vertical text, the run is set horizontally within one em of the line.
tate_chu_yoko: bool = false,
+ /// Ruby: the reading set small above the text (to its right in vertical text), one group
+ /// over each run that has it.
+ ruby: String = String::new(),
+ /// Kenten: an emphasis dot above each character.
+ kenten: bool = false,
/// Digits (World-Ready): how 0–9 are drawn.
digits: Digits = Digits::Default,
language: String = "English: USA".into(),
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index 62a27de11..d37340c13 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -157,6 +157,34 @@ pub fn specs() -> Vec<CommandSpec> {
format_chars(s, &json!({"tate_chu_yoko": on}))
}
),
+ cmd!(
+ "type.ruby",
+ "Ruby",
+ [],
+ None,
+ "{text} — the reading set over the selected text (one group); empty removes it",
+ has_text_or_frames,
+ |s, p| { format_chars(s, &json!({"ruby": str_param(p, "text").unwrap_or("")})) }
+ ),
+ cmd!(
+ "type.kenten",
+ "Kenten",
+ [],
+ None,
+ "{on?: bool} — emphasis dots over the selected characters (toggles by default)",
+ has_text_or_frames,
+ |s, p| {
+ let on = match p.get("on").and_then(Value::as_bool) {
+ Some(v) => v,
+ None => !format_targets(s).first().is_some_and(|t| {
+ s.doc().ok().and_then(|d| d.doc.text_story(t.story, t.cell)).is_some_and(|st| {
+ st.char_format_at(if t.range.is_empty() { t.range.start } else { t.range.start + 1 }).over.kenten == Some(true)
+ })
+ }),
+ };
+ format_chars(s, &json!({"kenten": on}))
+ }
+ ),
cmd!("type.sizeUp", "Increase Point Size", [], Some("Cmd+Shift+."), "{}", has_text_or_frames, |s, _| step_size(s, 2.0)),
cmd!("type.sizeDown", "Decrease Point Size", [], Some("Cmd+Shift+,"), "{}", has_text_or_frames, |s, _| step_size(s, -2.0)),
cmd!(
@@ -1209,6 +1237,24 @@ mod tcy_tests {
s.execute("type.tateChuYoko", &json!({"on": true})).unwrap();
assert_eq!(get(&s), Some(true));
}
+
+ #[test]
+ fn ruby_and_kenten_on_the_selection() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "漢字です"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": "漢字".len()})).unwrap();
+ s.execute("type.ruby", &json!({"text": "かんじ"})).unwrap();
+ s.execute("type.kenten", &json!({})).unwrap();
+ let f = |s: &Session| s.doc().unwrap().doc.stories[&designcraft_doc::StoryId(sid)].char_format_at(1).over.clone();
+ assert_eq!(f(&s).ruby.as_deref(), Some("かんじ"));
+ assert_eq!(f(&s).kenten, Some(true));
+ s.execute("type.kenten", &json!({})).unwrap();
+ s.execute("type.ruby", &json!({"text": ""})).unwrap();
+ assert_eq!(f(&s).kenten, Some(false));
+ assert_eq!(f(&s).ruby.as_deref(), Some(""));
+ }
}
#[cfg(test)]
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index c61c5c09b..0600520bc 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1040,6 +1040,13 @@ impl<'a> Ex<'a> {
if let Some(v) = a.digits {
el.set("DigitsType", names::digits_out(v));
}
+ if let Some(r) = a.ruby.as_ref().filter(|r| !r.is_empty()) {
+ el.set("RubyFlag", "true");
+ el.set("RubyString", r.as_str());
+ }
+ if let Some(k) = a.kenten {
+ el.set("KentenKind", if k { "KentenSesameDot" } else { "None" });
+ }
if let Some(v) = a.tate_chu_yoko {
el.set("Tatechuyoko", bool_s(v));
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index c0e90bfba..d0ecf2477 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -1073,6 +1073,12 @@ impl<'r> Importer<'r> {
}
a.no_break = e.boolean("NoBreak");
a.tate_chu_yoko = e.boolean("Tatechuyoko");
+ if e.boolean("RubyFlag") == Some(true) {
+ a.ruby = e.get("RubyString").map(str::to_string);
+ }
+ if let Some(k) = e.get("KentenKind") {
+ a.kenten = Some(k != "None");
+ }
a.digits = e.get("DigitsType").and_then(names::digits_in);
if let Some(v) = e.get("AppliedConditions").filter(|v| !v.trim().is_empty()) {
let names: Vec<String> = v.split_whitespace().filter_map(|r| self.condition_names.get(r).cloned()).collect();
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index dd8b9154a..95b3ec584 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -724,6 +724,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
"newDocument" => "New Document",
"frameSize" => "Rectangle",
"goToPage" => "Go to Page",
+ "ruby" => "Ruby",
"insertTable" => "Create Table",
"textFrameOptions" => "Text Frame Options",
"documentSetup" => "Document Setup",
@@ -1200,6 +1201,13 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
text_field(ui, &mut d, "page", 80.0);
});
}
+ "ruby" => {
+ ui.horizontal(|ui| {
+ ui.label("Ruby:");
+ text_field(ui, &mut d, "text", 200.0);
+ });
+ ui.label(egui::RichText::new("Set over the selected text; empty removes it.").size(11.0));
+ }
"insertTable" => {
ui.label(egui::RichText::new("Table Dimensions").font(semibold(12.0)));
egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
@@ -1293,6 +1301,7 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
json!({"spread": d.fields.get("spread").cloned().unwrap_or(json!(0)), "shape": d.s("shape"), "content": d.s("content"), "rect": [x, y, x + w, y + h]}),
)
}
+ "ruby" => app.run("type.ruby", json!({"text": d.s("text")})),
"goToPage" => {
// A page name ("iv", "A-3"), a number, or "+n" for an absolute position.
let typed = match d.fields.get("page") {
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 837265ac7..0e81fb6bb 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -56,6 +56,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"),
("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"),
("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),
+ ("app.rubyDialog", "Ruby…", None, "{} — the reading set over the selected text"),
("app.findFontDialog", "Find/Replace Font…", None, "{} — fonts used (missing ones flagged) and replacing them"),
("app.insertXrefDialog", "Insert Cross-Reference…", None, "{} — New Cross-Reference dialog (paragraph or text anchor, format)"),
("app.deleteAllGuides", "Delete All Guides on Spread", None, "{} — the spread in view"),
@@ -394,6 +395,8 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:object.textFrameOptions|Vertical|{\"vertical\": true}",
"<",
"cmd:type.tateChuYoko",
+ "ui:app.rubyDialog",
+ "cmd:type.kenten",
">Track Changes",
"cmd:changes.track",
"cmd:changes.acceptAll",
@@ -866,6 +869,16 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
app.ui.dialog = Some(crate::dialogs::Dialog::new("insertTable", p.clone()));
Ok(Value::Null)
}
+ "app.rubyDialog" => {
+ let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };
+ let cur = st.selection.text.and_then(|t| {
+ let story = st.doc.text_story(t.story, t.cell)?;
+ let at = if t.range().is_empty() { t.range().start } else { t.range().start + 1 };
+ story.char_format_at(at).over.ruby.clone()
+ });
+ app.ui.dialog = Some(crate::dialogs::Dialog::new("ruby", json!({"text": cur.unwrap_or_default()})));
+ Ok(Value::Null)
+ }
"app.footnoteOptionsDialog" => {
let Some(st) = app.session.active() else { return Some(Err("no document open".into())) };
let o = serde_json::to_value(&st.doc.footnote_options).unwrap_or_default();