Skip to content

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

T: vertical type — Vertical Type tool, upright CJK, CJK line breaking

Brandon Thomas77fc006b02c9
diff --git a/ROADMAP.md b/ROADMAP.md
index 219cc43be..3ed550f4e 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -103,6 +103,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`: 90° CW / CCW, 180°, clear): the view turns in quarter turns about its centre; tools, hit testing, the render texture and overlays follow; rulers hide while rotated. InDesign turns just the one 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). Vertical punctuation forms (`vert`), tate-chu-yoko and vertical metrics aren't there yet.
- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).
- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.
- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.
diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs
index 8fd9b7d5b..a718a9456 100644
--- a/crates/compose/src/breaker.rs
+++ b/crates/compose/src/breaker.rs
@@ -164,6 +164,19 @@ impl Item {
const INF: f64 = 10000.0;
/// Does the glyph force a line end after it?
+/// A line may break between `a` and `b` in CJK text (any break next to an ideograph, kana or
+/// hangul), except where kinsoku forbids it: no line starts with closing punctuation, small
+/// kana or the prolonged sound mark, and none ends with opening brackets.
+pub fn cjk_break_between(a: char, b: char) -> bool {
+ let cjk = |c: char| crate::upright_in_vertical(c) || matches!(c as u32, 0x3000..=0x303F);
+ if !(cjk(a) || cjk(b)) {
+ return false;
+ }
+ const NO_START: &str = "、。,.・:;?!ー)」』】〕〉》}]〙〗ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶ々〻ゝゞヽヾ!),.:;?]}";
+ const NO_END: &str = "(「『【〔〈《{[〘〖([{";
+ !NO_START.contains(b) && !NO_END.contains(a)
+}
+
pub fn is_forced(c: char) -> bool {
use designcraft_doc::story::*;
matches!(c, FORCED_LINE_BREAK | COLUMN_BREAK | FRAME_BREAK | PAGE_BREAK)
@@ -293,7 +306,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
let mut p = Item::penalty(0.0, 50.0, true);
p.hang = if sp.optical { hang_right(g) } else { 0.0 };
push_inword(&mut it, &mut ig, p, i + 1, sp);
- } else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') {
+ } else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || cjk_break_between(g.ch, glyphs[i + 1].ch) {
let mut p = Item::penalty(0.0, 0.0, false);
p.hang = if sp.optical { hang_right(g) } else { 0.0 };
push_inword(&mut it, &mut ig, p, i + 1, sp);
@@ -626,7 +639,7 @@ pub fn greedy(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn F
shrink += sp.box_elastic(g).1.iter().sum::<f64>();
}
if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break {
- if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') {
+ if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/') || cjk_break_between(g.ch, glyphs[i + 1].ch) {
last_ok = Some((i + 1, false));
} else if hyph_after[i] && may_hyphenate(hyphens) {
let hy = hyphen_width(g, &mut hy_cache) * if sp.optical { 1.0 - hang('-').1 } else { 1.0 };
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3746824f8..b15112dab 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -97,6 +97,16 @@ pub struct PlacedGlyph {
pub len: usize,
/// Control characters (tabs, breaks, markers' carriers) are not drawn.
pub visible: bool,
+ /// Stays upright in vertical frames (CJK ideographs, kana, hangul, full-width forms).
+ pub upright: bool,
+}
+
+/// Characters set upright (unrotated) in vertical text.
+pub fn upright_in_vertical(c: char) -> bool {
+ matches!(c as u32,
+ 0x1100..=0x11FF | 0x2E80..=0x2FFF | 0x3040..=0x30FF | 0x3100..=0x31FF | 0x3200..=0x9FFF
+ | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xF900..=0xFAFF | 0xFF01..=0xFF60 | 0xFFE0..=0xFFE6
+ | 0x20000..=0x3FFFF)
}
#[derive(Clone, Debug)]
@@ -139,6 +149,8 @@ pub struct Deco {
#[derive(Clone, Debug, Default)]
pub struct FrameText {
pub frame: ItemId,
+ /// Vertical Type frame (upright glyphs turn back in it).
+ pub vertical: bool,
pub lines: Vec<Line>,
pub decos: Vec<Deco>,
/// Byte range of the story shown in this frame.
@@ -345,6 +357,15 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec<FrameSpec> {
}
None => (item.text_area(), tf.options.clone()),
};
+ // Vertical type: composed in the turned box; wraps and page rects turned with it.
+ let (area, exclusions, grid, page_rect) = if tf.options.vertical && tf.options.path.is_none() {
+ let v = designcraft_doc::vertical_text_xf(area).inverse();
+ let ex = exclusions.into_iter().map(|e| Exclusion { rect: v.transform_rect_bbox(e.rect), ..e }).collect();
+ let pr = page_rect.map(|(a, b)| (v.transform_rect_bbox(a), v.transform_rect_bbox(b)));
+ (Rect::new(0.0, 0.0, area.height(), area.width()), ex, None, pr)
+ } else {
+ (area, exclusions, grid, page_rect)
+ };
out.push(FrameSpec {
id: fid,
area,
@@ -377,7 +398,7 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() };
let mut styles_tab: Vec<RunStyle> = Vec::new();
let mut missing_fonts: HashMap<String, bool> = HashMap::new();
- out.frames = frames.iter().map(|f| FrameText { frame: f.id, columns: f.columns(), ..Default::default() }).collect();
+ out.frames = frames.iter().map(|f| FrameText { frame: f.id, vertical: f.opts.vertical, columns: f.columns(), ..Default::default() }).collect();
let cols: Vec<Vec<Rect>> = frames.iter().map(FrameSpec::columns).collect();
let mut cur = Cursor { fi: 0, col: 0, last_baseline: None, last_descent: 0.0, pending: 0.0 };
let para_ranges = story.para_ranges();
@@ -1604,6 +1625,7 @@ fn tab_leader(tab: &Glyph, leader: &str, x: f64, w: f64, origin: f64, out: &mut
byte: tab.byte,
len: 0,
visible: true,
+ upright: false,
});
at += adv;
}
@@ -1704,6 +1726,7 @@ fn place(g: &Glyph, x: f64) -> PlacedGlyph {
byte: g.byte,
len: g.len,
visible,
+ upright: upright_in_vertical(g.ch),
}
}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 2ad6d9eaf..7dc5bdaa5 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -840,3 +840,48 @@ fn bidi_matches_the_reference_order() {
assert_eq!(ours, reference, "rtl={rtl}");
}
}
+
+#[test]
+fn vertical_frames_compose_in_the_turned_box() {
+ let mut d = Document::new(&designcraft_doc::build::NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, sid) =
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 400.0), lid, "縦書きの文章です。Latin", ParaFormat::default()).unwrap();
+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {
+ tf.options.vertical = true;
+ tf.options.inset = [0.0; 4];
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let ft = &cs.frames[0];
+ assert!(ft.vertical);
+ // The line runs along the frame's height (300 pt), so it all fits on one line.
+ assert_eq!(ft.lines.len(), 1);
+ let l = &ft.lines[0];
+ assert!(l.x1 - l.x0 > 290.0, "{} {}", l.x0, l.x1);
+ assert!(l.glyphs.iter().filter(|g| g.len > 0).take(5).all(|g| g.upright));
+ assert!(!l.glyphs.iter().rev().find(|g| g.len > 0).unwrap().upright, "Latin turns");
+ // Text space → frame: the first line sits at the right edge and runs down.
+ let it = d.item(fid).unwrap();
+ let p0 = it.text_xf() * designcraft_geom::Point::new(l.glyphs[0].x, l.baseline);
+ let p1 = it.text_xf() * designcraft_geom::Point::new(l.glyphs[3].x, l.baseline);
+ assert!(p0.x > 150.0 && p1.y > p0.y && (p1.x - p0.x).abs() < 1e-6, "{p0:?} {p1:?}");
+}
+
+#[test]
+fn cjk_text_breaks_between_characters_with_kinsoku() {
+ use crate::breaker::cjk_break_between;
+ assert!(cjk_break_between('日', '本'));
+ assert!(!cjk_break_between('す', '。'), "no line starts with a full stop");
+ assert!(!cjk_break_between('「', '日'), "no line ends with an opening bracket");
+ assert!(!cjk_break_between('a', 'b'));
+ let text = "日本語の文章は単語の間に空白を入れずに書くので、文字と文字の間で改行します。";
+ let (d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 156.0, 400.0), ParaAttrs::default());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!(lines.len() > 1, "wraps");
+ for l in &lines {
+ assert!(l.end_x <= l.x1 + 0.5, "line fits: {} > {}", l.end_x, l.x1);
+ let first = text[l.range.clone()].chars().next().unwrap_or(' ');
+ assert!(!"、。".contains(first), "kinsoku: {:?}", &text[l.range.clone()]);
+ }
+}
diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs
index 127aed898..1e0469945 100644
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@ -332,6 +332,9 @@ pub struct TextFrameOptions {
/// Type on a Path: the text runs along the item's path instead of filling it.
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<PathType>,
+ /// Vertical Type: lines run top to bottom and follow each other right to left.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub vertical: bool,
}
/// Type on a Path Options.
@@ -377,6 +380,7 @@ impl Default for TextFrameOptions {
column_rule_color: designcraft_color::swatch::BLACK.into(),
baseline_grid: None,
path: None,
+ vertical: false,
}
}
}
@@ -492,6 +496,12 @@ impl Item {
}
}
+/// Vertical text: composed in a box `area.height()` wide and `area.width()` tall at the origin,
+/// placed so lines go down and follow each other leftwards (a clockwise quarter turn).
+pub fn vertical_text_xf(area: Rect) -> Affine {
+ Affine::new([0.0, 1.0, -1.0, 0.0, area.x1, area.y0])
+}
+
/// "video" or "audio" for a media MIME type.
pub fn media_kind(mime: &str) -> Option<&'static str> {
if mime.starts_with("video/") {
@@ -952,6 +962,23 @@ impl Item {
}
/// The frame's text area (inner space) after inset.
+ /// Text space → item inner space (identity except for vertical frames).
+ pub fn text_local(&self) -> Affine {
+ match self.text_frame() {
+ Some(t) if t.options.vertical && t.options.path.is_none() => vertical_text_xf(self.text_area()),
+ _ => Affine::IDENTITY,
+ }
+ }
+
+ /// Text space → spread-parent space for this frame's composed text (the item transform, with
+ /// the quarter turn of a vertical frame).
+ pub fn text_xf(&self) -> Affine {
+ match self.text_frame() {
+ Some(t) if t.options.vertical && t.options.path.is_none() => self.xf * vertical_text_xf(self.text_area()),
+ _ => self.xf,
+ }
+ }
+
pub fn text_area(&self) -> Rect {
let r = self.inner_bounds();
let inset = self.text_frame().map(|t| t.options.inset).unwrap_or([0.0; 4]);
diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs
index 59bd33afc..8e74bafb5 100644
--- a/crates/engine/src/cmd/anchored.rs
+++ b/crates/engine/src/cmd/anchored.rs
@@ -207,7 +207,7 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
let (spread, xf) = match placed {
Some((fid, origin)) => {
let loc = d0.find(fid).ok_or_else(|| bad("anchored.release", "frame not found"))?;
- let fxf = d0.parent_xf(&loc) * d0.item(fid).map_or(Affine::IDENTITY, |i| i.xf);
+ let fxf = d0.parent_xf(&loc) * d0.item(fid).map_or(Affine::IDENTITY, |i| i.text_xf());
(loc.spread, fxf * Affine::translate(origin.to_vec2()))
}
None => (SpreadRef::Doc(0), Affine::IDENTITY),
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index 60fad25ff..6f92a4eec 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -326,7 +326,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Frame Options…",
["Object"],
Some("Cmd+B"),
- "{columns?, gutter?, inset?: number|[t,l,b,r], verticalJustification?: top|center|bottom|justify, firstBaseline?, autoSize?, ignoreWrap?, balanceColumns?, ids?}",
+ "{columns?, gutter?, inset?: number|[t,l,b,r], verticalJustification?: top|center|bottom|justify, firstBaseline?, autoSize?, ignoreWrap?, balanceColumns?, vertical?: bool (Vertical Type), ids?}",
has_selection,
text_frame_options
),
@@ -646,6 +646,7 @@ fn frame_create(s: &mut Session, p: &Value) -> Result<Value> {
let lid = s.doc()?.active_layer;
let text = str_param(p, "text").unwrap_or("").to_string();
let caret = bool_or(p, "caret", content == "text");
+ let vertical = bool_or(p, "vertical", false);
let sides = p.get("sides").and_then(Value::as_u64).map_or(s.prefs.polygon_sides, |v| v as u32).clamp(3, 100);
let inset = p.get("starInset").and_then(Value::as_f64).map_or(s.prefs.star_inset, |v| v / 100.0).clamp(0.0, 1.0);
let rect = Rect::new(rect.x0, rect.y0, rect.x1.max(rect.x0 + 0.5), rect.y1.max(rect.y0 + 0.5));
@@ -663,6 +664,9 @@ fn frame_create(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(it) = d.item_mut(id) {
it.path = path;
it.shape = sh;
+ if vertical && let Some(tf) = it.text_frame_mut() {
+ tf.options.vertical = true;
+ }
}
*sel = if caret {
Selection::text(TextSel { story: sid, anchor: text.len(), focus: text.len(), frame: Some(id), cell: None })
@@ -1298,6 +1302,9 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = p.get("ignoreWrap").and_then(Value::as_bool) {
o.ignore_wrap = v;
}
+ if let Some(v) = p.get("vertical").and_then(Value::as_bool) {
+ o.vertical = v;
+ }
if let Some(v) = p.get("balanceColumns").and_then(Value::as_bool) {
o.balance_columns = v;
}
diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs
index 935750f42..207f559ee 100644
--- a/crates/engine/src/cmd/paths.rs
+++ b/crates/engine/src/cmd/paths.rs
@@ -274,7 +274,7 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
let at = d.spread(sr).and_then(|sp| sp.items.iter().position(|i| i.id == *id));
let make = |d: &mut Document, ((fill, ft, stroke, stt, sw), bp): ((String, f32, String, f32, f64), BezPath)| {
let mut o = Item::new(ItemId(d.alloc()), it.layer, Shape::Path, PathData::from_bezpath(&bp));
- o.xf = it.xf;
+ o.xf = it.text_xf();
o.fill = Fill { swatch: fill, tint: ft, ..Fill::none() };
o.stroke = if stroke == designcraft_color::swatch::NONE {
Stroke::none()
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index f55b93636..18b15e7bc 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -189,7 +189,7 @@ fn hit_byte(s: &Session, frame: ItemId, pt: Point) -> Option<(StoryId, usize, Op
let loc = st.doc.find(frame)?;
let it = st.doc.item_at(&loc)?;
let sid = it.text_frame()?.story;
- let xf = st.doc.parent_xf(&loc) * it.xf;
+ let xf = st.doc.parent_xf(&loc) * it.text_xf();
let inner = xf.inverse() * pt;
let cs = s.cache.get(&st.doc, sid, None);
let fi = cs.frames.iter().position(|f| f.frame == frame)?;
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 796e8f44c..b44cce87d 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1669,13 +1669,14 @@ impl<'a> Ex<'a> {
// ---------- stories ----------
fn story_el(&mut self, s: &Story) -> El {
+ let vertical = s.frames.iter().any(|f| self.d.item(*f).and_then(|i| i.text_frame()).is_some_and(|t| t.options.vertical));
let mut el = El::new("Story").attr("Self", uid(s.id.0)).attr("AppliedTOCStyle", "n").attr("TrackChanges", "false").attr("StoryTitle", "$ID/");
el.push(
El::new("StoryPreference")
.attr("OpticalMarginAlignment", "false")
.attr("OpticalMarginSize", "12")
.attr("FrameType", "TextFrameType")
- .attr("StoryOrientation", "Horizontal")
+ .attr("StoryOrientation", if vertical { "Vertical" } else { "Horizontal" })
.attr("StoryDirection", "LeftToRightDirection"),
);
for psr in self.story_paras(s) {
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 066fdf9de..4259777dc 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -113,6 +113,8 @@ struct Importer<'r> {
layer_ids: HashMap<String, LayerId>,
stories: BTreeMap<StoryId, Story>,
story_ids: HashMap<String, StoryId>,
+ /// Stories with a vertical StoryOrientation (their frames set text vertically).
+ vertical_stories: std::collections::HashSet<StoryId>,
parents: Vec<Spread>,
parent_ids: HashMap<String, SpreadId>,
spreads: Vec<Spread>,
@@ -194,6 +196,7 @@ impl<'r> Importer<'r> {
layers: Vec::new(),
layer_ids: HashMap::new(),
stories: BTreeMap::new(),
+ vertical_stories: Default::default(),
story_ids: HashMap::new(),
parents: Vec::new(),
parent_ids: HashMap::new(),
@@ -324,6 +327,9 @@ impl<'r> Importer<'r> {
self.story_ids.insert(s.to_string(), id);
}
let story = self.story(id, e);
+ if e.find("StoryPreference").and_then(|p| p.get("StoryOrientation")) == Some("Vertical") {
+ self.vertical_stories.insert(id);
+ }
self.stories.insert(id, story);
}
// Topic cross-references (See / See also) become markers at the start of the first story
@@ -1915,6 +1921,7 @@ impl<'r> Importer<'r> {
}
};
let mut options = e.find("TextFramePreference").map(text_frame_options).unwrap_or_default();
+ options.vertical = self.vertical_stories.contains(&story);
if let Some(g) = e.find("BaselineFrameGridOption")
&& g.get("UseCustomBaselineFrameGrid") == Some("true")
{
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index d61ebdba5..2d4d23de6 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -549,3 +549,14 @@ fn round_trips_frames_with_pasted_in_items() {
let b = f.bounds();
assert!((b.x0 - 100.0).abs() < 0.01 && (b.x1 - 200.0).abs() < 0.01, "{b:?}");
}
+
+#[test]
+fn vertical_story_orientation_round_trips() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, "縦書き", ParaFormat::default()).unwrap();
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical = true;
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let frame = back.spreads[0].items.iter().find_map(|i| i.text_frame()).unwrap();
+ assert!(frame.options.vertical);
+}
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index ae7b539bb..8464c2e78 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -816,7 +816,14 @@ impl Exporter<'_> {
}
} else if let Some(ft) = cs.frame(it.id) {
let text = doc.story(tfr.story).map(|st| st.text.as_str()).unwrap_or("");
+ let local = it.text_local();
+ if local != Affine::IDENTITY {
+ s.push_transform(&tf(local));
+ }
self.frame_text(s, &cs, ft, text);
+ if local != Affine::IDENTITY {
+ s.pop();
+ }
}
}
_ => {}
diff --git a/crates/pdf/src/links.rs b/crates/pdf/src/links.rs
index 9fbf27502..393084c68 100644
--- a/crates/pdf/src/links.rs
+++ b/crates/pdf/src/links.rs
@@ -32,7 +32,7 @@ fn source_rects(doc: &Document, cache: &designcraft_compose::Cache, src: &Hyperl
if loc.spread != SpreadRef::Doc(si) {
continue;
}
- let m: Affine = doc.parent_xf(&loc) * it.xf;
+ let m: Affine = doc.parent_xf(&loc) * it.text_xf();
for l in &ft.lines {
if l.range.end <= *start || l.range.start >= *end {
continue;
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index 6cee3b1c2..8b03b6d7f 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -85,8 +85,17 @@ impl Exporter<'_> {
i += 1;
continue;
}
+ // Vertical type: an upright glyph turns back a quarter about its em box centre.
+ if ft.vertical && g.upright {
+ let c = designcraft_geom::Point::new(g.x + g.adv / 2.0, l.baseline + g.y - g.adv * 0.38);
+ s.push_transform(&crate::export::tf(Affine::rotate_about(-std::f64::consts::FRAC_PI_2, c)));
+ self.run(s, cs, &gs[i..i + 1], l.baseline, story);
+ s.pop();
+ i += 1;
+ continue;
+ }
let mut j = i + 1;
- while j < gs.len() && same_run(g, &gs[j]) {
+ while j < gs.len() && same_run(g, &gs[j]) && !(ft.vertical && gs[j].upright) {
j += 1;
}
self.run(s, cs, &gs[i..j], l.baseline, story);
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index f905e2535..d8de06ccf 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -516,7 +516,7 @@ impl Renderer {
if let Some(ft) = cs.frame(it.id) {
match &tf.options.path {
Some(pt) => self.draw_path_text(ctx, f, &cs, ft, xf, bp, pt),
- None => self.draw_text(ctx, f, &cs, ft, xf),
+ None => self.draw_text(ctx, f, &cs, ft, xf * it.text_local()),
}
}
}
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index a00e6caf7..301a7a505 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -114,7 +114,7 @@ fn union(r: Option<Rect>, b: Rect) -> Option<Rect> {
Some(r.map_or(b, |r| r.union(b)))
}
-fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line) -> LineGlyphs {
+fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> LineGlyphs {
let mut runs: Vec<(u32, BezPath)> = Vec::new();
let mut decos = Vec::new();
let mut glyphs = 0;
@@ -131,7 +131,12 @@ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line) -> LineGlyphs {
continue;
}
let skew = if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
- let a = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
+ let mut a = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
+ if vertical && g.upright {
+ // Upright in vertical text: turned back a quarter about the em box centre.
+ let c = kurbo::Point::new(g.x + g.adv / 2.0, l.baseline + g.y - g.adv * 0.38);
+ a = Affine::rotate_about(-std::f64::consts::FRAC_PI_2, c) * a;
+ }
let bp = match runs.iter_mut().find(|r| r.0 == g.style) {
Some(r) => &mut r.1,
None => {
@@ -158,7 +163,7 @@ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line) -> LineGlyphs {
fn build(cs: &ComposedStory, ft: &FrameText) -> FrameGlyphs {
let db = FontDb::global();
- let lines: Vec<LineGlyphs> = ft.lines.iter().map(|l| build_line(db, cs, l)).collect();
+ let lines: Vec<LineGlyphs> = ft.lines.iter().map(|l| build_line(db, cs, l, ft.vertical)).collect();
let elements = lines.iter().flat_map(|l| &l.runs).map(|(_, bp)| bp.elements().len()).sum();
FrameGlyphs { lines, elements }
}
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index 7744f97a0..945a89b18 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -259,6 +259,7 @@ pub fn create(id: &str) -> Box<dyn Tool> {
"directSelection" => Box::new(select::SelectionTool::new(true)),
"rectangleFrame" | "ellipseFrame" | "polygonFrame" | "rectangle" | "ellipse" | "polygon" | "line" => Box::new(frame::FrameTool::new(id)),
"type" => Box::new(text::TypeTool::default()),
+ "verticalType" => Box::new(text::TypeTool::vertical()),
"pen" => Box::new(pen::PenTool::default()),
"gradientSwatch" => Box::new(gradient::GradientTool::default()),
"gradientFeather" => Box::new(gradient::GradientTool::feather()),
diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs
index f1f488fb6..fa9fc528f 100644
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@ -254,3 +254,19 @@ fn type_on_path_tool_targets_paths() {
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0 + off.x, 100.0 + off.y));
assert_eq!(a, vec![Action::Exec("type.onPath".into(), serde_json::json!({"id": id.0})), Action::SwitchTool("type".into())]);
}
+
+#[test]
+fn vertical_type_tool_draws_vertical_frames() {
+ let d = Document::new(&NewDocument::default());
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("verticalType");
+ assert_eq!(t.id(), "verticalType");
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 300.0));
+ let p = a.iter().find_map(|x| match x {
+ Action::Preview(id, p) if id == "frame.create" => Some(p.clone()),
+ _ => None,
+ });
+ assert_eq!(p.unwrap()["vertical"], true);
+}
diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs
index a92e14732..c119e0b09 100644
--- a/crates/tools/src/text.rs
+++ b/crates/tools/src/text.rs
@@ -9,14 +9,22 @@ use crate::{Action, Cursor, Mods, PointerEvent, PointerKind, Tool, ToolContext,
#[derive(Default)]
pub struct TypeTool {
+ /// Vertical Type Tool: frames it draws set text vertically.
+ pub vertical: bool,
start: Option<Point>,
selecting: Option<u64>,
drawing: bool,
}
+impl TypeTool {
+ pub fn vertical() -> Self {
+ TypeTool { vertical: true, ..Default::default() }
+ }
+}
+
impl Tool for TypeTool {
fn id(&self) -> &'static str {
- "type"
+ if self.vertical { "verticalType" } else { "type" }
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
@@ -61,7 +69,7 @@ impl Tool for TypeTool {
}
out.push(Action::Preview(
"frame.create".into(),
- json!({"spread": spread_json(sr), "shape": "rectangle", "content": "text", "rect": rect_json(r), "caret": true}),
+ json!({"spread": spread_json(sr), "shape": "rectangle", "content": "text", "rect": rect_json(r), "caret": true, "vertical": self.vertical}),
));
out
}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 4dacfc9e2..96bfcc3df 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -927,7 +927,7 @@ fn draw_text_selection(
if let Some(sel) = cells.filter(|c| c.story == ts.story) {
for ft in &cs.frames {
let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame)) else { continue };
- let m = a * it.xf;
+ let m = a * it.text_xf();
for t in ft.tables.iter().filter(|t| t.table == sel.table) {
for c in t.cells.iter().filter(|c| sel.range.contains(c.row, c.col)) {
let q = [
@@ -950,7 +950,7 @@ fn draw_text_selection(
for (fi, ft) in cs.frames.iter().enumerate() {
let Some((a, _)) = item_canvas_xf(doc, layout, ft.frame) else { continue };
let Some(it) = doc.item(ft.frame) else { continue };
- let m = a * it.xf;
+ let m = a * it.text_xf();
// Show the frame edge while typing.
for poly in path_screen(it, xf, a) {
painter.add(egui::Shape::line(poly, Stroke::new(1.0, layer_color(doc, it).gamma_multiply(0.6))));
@@ -992,7 +992,7 @@ fn draw_text_selection(
&& let Some(ft) = cs.frames.get(fi)
&& let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame))
{
- let m = a * it.xf;
+ let m = a * it.text_xf();
let blink = (painter.ctx().input(|i| i.time) * 1.6) as i64 % 2 == 0;
if blink {
let p0 = xf.to_screen(m * Point::new(x, bl - asc));
@@ -1023,7 +1023,7 @@ fn draw_cell_selection(
let Some((fi, origin, text)) = found else { return };
let Some(ft) = cs.frames.get(fi) else { return };
let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame)) else { return };
- let m = a * it.xf * designcraft_geom::Affine::translate(origin.to_vec2());
+ let m = a * it.text_xf() * designcraft_geom::Affine::translate(origin.to_vec2());
let range = ts.range();
if !range.is_empty()
&& let Some(cft) = text.frames.first()
@@ -1051,7 +1051,7 @@ fn draw_cell_selection(
None => compose::cell_caret(cs, cell.table, cell.row, cell.col, ts.focus),
}
{
- let m = a * it.xf;
+ let m = a * it.text_xf();
let blink = (painter.ctx().input(|i| i.time) * 1.6) as i64 % 2 == 0;
if blink {
painter.line_segment(
@@ -1437,7 +1437,7 @@ fn draw_hidden_characters(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc
let cs = app.session.cache.get(doc, story.id, None);
for ft in &cs.frames {
let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame)) else { continue };
- let m = a * it.xf;
+ let m = a * it.text_xf();
let col = layer_color(doc, it);
for l in &ft.lines {
let size = (l.ascent * 0.75 * xf.zoom).clamp(6.0, 40.0) as f32;
@@ -1489,7 +1489,7 @@ fn draw_dynamic_spelling(app: &DesignApp, ctx: &egui::Context, painter: &egui::P
let red = Stroke::new(1.0, Color32::from_rgb(230, 30, 30));
for ft in &cs.frames {
let (Some((a, _)), Some(it)) = (item_canvas_xf(doc, layout, ft.frame), doc.item(ft.frame)) else { continue };
- let m = a * it.xf;
+ let m = a * it.text_xf();
for l in &ft.lines {
for r in bad.iter().filter(|r| r.start < l.range.end && r.end > l.range.start) {
let gs: Vec<_> = l.glyphs.iter().filter(|g| g.len > 0 && g.byte >= r.start && g.byte < r.end).collect();
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index a5b528bdf..0e7f70de8 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -128,7 +128,8 @@ pub fn control_bar(app: &mut DesignApp, ui: &mut egui::Ui) {
)
.show(ui, |ui| {
ui.horizontal(|ui| {
- let text_mode = app.session.tool_id() == "type" || app.session.active().is_some_and(|d| d.selection.text.is_some());
+ let text_mode =
+ matches!(app.session.tool_id(), "type" | "verticalType") || app.session.active().is_some_and(|d| d.selection.text.is_some());
if text_mode {
control_text(app, ui);
} else {
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index e0cfba3f5..8c4db5f50 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -374,6 +374,10 @@ pub const MENUS: &[(&str, &[&str])] = &[
"-",
"cmd:footnote.insert",
"cmd:endnote.insert",
+ ">Story Direction",
+ "cmd:object.textFrameOptions|Horizontal|{\"vertical\": false}",
+ "cmd:object.textFrameOptions|Vertical|{\"vertical\": true}",
+ "<",
">Track Changes",
"cmd:changes.track",
"cmd:changes.acceptAll",
diff --git a/docs/parity.md b/docs/parity.md
index 645060193..9c0f9a723 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -11,7 +11,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
|---|---|---|---|---|---|
| P0 | 102 | 100 | 2 | 0 | 99% |
| P1 | 97 | 94 | 3 | 0 | 98% |
-| P2 | 76 | 43 | 30 | 3 | 76% |
+| P2 | 76 | 43 | 31 | 2 | 77% |
| Area | Parity |
|---|---|
@@ -23,7 +23,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Fill, stroke, colour | 99% |
| Effects & transparency | 75% |
| Placing & links | 91% |
-| Type & text frames | 96% |
+| Type & text frames | 97% |
| Typography | 98% |
| Styles | 97% |
| Tables | 98% |
@@ -186,7 +186,7 @@ Open P0 items: Vector/page formats (PDF/AI/SVG/EPS place), Export to PDF (print)
| Type & text frames | Overset detection & indicator | P0 | D |
| Type & text frames | Text Frame Options | P0 | D |
| Type & text frames | Type on a path | P1 | D |
-| Type & text frames | Vertical type | P2 | M |
+| Type & text frames | Vertical type | P2 | P |
| Type & text frames | Story Editor | P1 | D |
| Type & text frames | Track Changes | P2 | D |
| Type & text frames | Notes | P2 | D |