Skip to content

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

continued work

Brandon Thomasb4c52c249b63
diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs
index 60629d5d6..e88d32b0c 100644
--- a/crates/compose/src/cache.rs
+++ b/crates/compose/src/cache.rs
@@ -10,6 +10,7 @@ use std::sync::{Arc, Mutex};
use designcraft_doc::{Document, Item, Story, StoryId, Styles, WrapMode};
+use crate::vars::RunningIndex;
use crate::{ComposeOptions, ComposedStory};
type Key = (StoryId, Option<String>);
@@ -24,6 +25,24 @@ struct Entry {
#[derive(Default)]
pub struct Cache {
map: Mutex<(HashMap<Key, Entry>, u64)>,
+ /// Running-header index with the document signature it was built for.
+ running: Mutex<Option<(u64, Arc<RunningIndex>)>>,
+}
+
+/// Identity of everything a running header can depend on (stories, spreads, styles, variables).
+fn doc_signature(doc: &Document) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ for (id, st) in &doc.stories {
+ (id.0, Arc::as_ptr(st) as usize, st.rev).hash(&mut h);
+ }
+ for sp in &doc.spreads {
+ (Arc::as_ptr(sp) as usize).hash(&mut h);
+ }
+ (Arc::as_ptr(&doc.styles) as usize).hash(&mut h);
+ format!("{:?}", doc.text_variables).hash(&mut h);
+ doc.sections.len().hash(&mut h);
+ h.finish()
}
impl Cache {
@@ -34,8 +53,21 @@ impl Cache {
/// The composed story, from cache or freshly composed.
pub fn get(&self, doc: &Document, sid: StoryId, page_name: Option<&str>) -> Arc<ComposedStory> {
let Some(story) = doc.stories.get(&sid) else { return Arc::new(ComposedStory { story: sid, ..Default::default() }) };
- let (sig, keep_items) = signature(doc, story);
+ let (mut sig, keep_items) = signature(doc, story);
let key = (sid, page_name.map(str::to_string));
+ let with_vars = crate::vars::has_vars(story);
+ let running = with_vars && crate::vars::has_running(doc, story);
+ if with_vars {
+ // Variables depend on the page count, sections and definitions (and running headers on
+ // the whole document).
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ format!("{:?}", doc.text_variables).hash(&mut h);
+ sig.extend([doc.page_count(), h.finish() as usize]);
+ if running {
+ sig.push(doc_signature(doc) as usize);
+ }
+ }
{
let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
g.1 += 1;
@@ -47,7 +79,13 @@ impl Cache {
return e.out.clone();
}
}
- let out = Arc::new(crate::compose_story(doc, sid, &ComposeOptions { page_name: page_name.map(str::to_string) }));
+ // Parent-page items are composed per page; variables need that page's index.
+ let page = match page_name {
+ Some(n) if with_vars => (0..doc.page_count()).find(|&i| doc.page_name(i) == n),
+ _ => None,
+ };
+ let running = running.then(|| self.running_index(doc));
+ let out = Arc::new(crate::compose_story(doc, sid, &ComposeOptions { page_name: page_name.map(str::to_string), page, running }));
let mut g = self.map.lock().unwrap_or_else(|e| e.into_inner());
let stamp = g.1;
if g.0.len() > 4096 {
@@ -59,6 +97,20 @@ impl Cache {
pub fn clear(&self) {
self.map.lock().unwrap_or_else(|e| e.into_inner()).0.clear();
+ *self.running.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ }
+
+ /// The running-header index for `doc` (rebuilt when the document changes).
+ pub fn running_index(&self, doc: &Document) -> Arc<RunningIndex> {
+ let sig = doc_signature(doc);
+ if let Some((s, r)) = &*self.running.lock().unwrap_or_else(|e| e.into_inner())
+ && *s == sig
+ {
+ return r.clone();
+ }
+ let r = Arc::new(RunningIndex::build(doc, &|sid| self.get(doc, sid, None)));
+ *self.running.lock().unwrap_or_else(|e| e.into_inner()) = Some((sig, r.clone()));
+ r
}
}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 2d32f955e..a253d38db 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -13,6 +13,7 @@ pub mod breaker;
mod cache;
pub mod hyphen;
pub mod shape;
+pub mod vars;
use std::collections::HashMap;
use std::ops::Range;
@@ -145,6 +146,8 @@ pub struct FrameSpec {
pub opts: TextFrameOptions,
pub exclusions: Vec<Exclusion>,
pub page_name: Option<String>,
+ /// Absolute document page the frame is on (None on parent pages).
+ pub page: Option<usize>,
/// Baseline grid in inner space: (first grid line y, increment).
pub grid: Option<(f64, f64)>,
/// The frame is on a left page (for towards/away-from-spine alignment).
@@ -172,6 +175,10 @@ impl FrameSpec {
pub struct ComposeOptions {
/// Page name for page-number markers when the story is composed for a specific page (parent items).
pub page_name: Option<String>,
+ /// Absolute page for text variables when composed for a specific page (parent items).
+ pub page: Option<usize>,
+ /// Running-header index (needed when the story contains running-header variables).
+ pub running: Option<std::sync::Arc<vars::RunningIndex>>,
}
/// Build the frame specs of a story from the document (geometry, wrap, page names, grid).
@@ -203,26 +210,26 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec<FrameSpec> {
exclusions.push(Exclusion { rect: inner, mode: other.wrap.mode });
}
}
- let (page_name, left_page) = match (loc.spread, spread) {
+ let (page_name, page, left_page) = match (loc.spread, spread) {
(designcraft_doc::SpreadRef::Doc(si), Some(sp)) => {
let c = item.bounds().center();
let pi = sp.page_at_x(c.x).unwrap_or(0);
let abs = doc.first_page_of_spread(si) + pi;
- (Some(doc.page_name(abs)), sp.pages.get(pi).is_some_and(|p| p.side == designcraft_doc::PageSide::Left))
+ (Some(doc.page_name(abs)), Some(abs), sp.pages.get(pi).is_some_and(|p| p.side == designcraft_doc::PageSide::Left))
}
(designcraft_doc::SpreadRef::Parent(pi), Some(sp)) => {
let prefix = sp.parent.as_ref().map(|p| p.prefix.clone()).unwrap_or_else(|| "A".into());
let _ = pi;
- (Some(prefix), false)
+ (Some(prefix), None, false)
}
- _ => (None, false),
+ _ => (None, None, false),
};
let g = &doc.settings.baseline_grid;
let (inc, start) = tf.options.baseline_grid.unwrap_or((g.increment, g.start));
// Grid lines are at spread y = start + n·inc (page tops are y = 0); map into inner space (translation only).
let ty = xf.translation().y;
let grid = (inc > 0.0).then_some((start - ty, inc));
- out.push(FrameSpec { id: fid, area: item.text_area(), opts: tf.options.clone(), exclusions, page_name, grid, left_page });
+ out.push(FrameSpec { id: fid, area: item.text_area(), opts: tf.options.clone(), exclusions, page_name, page, grid, left_page });
}
out
}
@@ -257,6 +264,8 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
let mut line_cap: Vec<Option<usize>> = vec![None; np];
let mut restores = 0usize;
let mut pi = 0;
+ let var_story = vars::has_vars(story);
+ let mut var_cache: std::collections::HashMap<Option<usize>, std::sync::Arc<Vec<String>>> = Default::default();
'paras: while pi < np {
let prange = para_ranges[pi].clone();
let snap = Snapshot::take(&out, &cur, list_counter);
@@ -266,9 +275,17 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
let pf = &story.paras[pi];
let (pp, base_chars) = doc.styles.resolve_para(pf);
// Bullets & numbering: generated prefix (shaped as its own glyphs, mapped to the paragraph start).
+ let cur_frame = frames.get(cur.fi.min(frames.len().saturating_sub(1)));
+ let var_values = if var_story {
+ let page = opts.page.or_else(|| cur_frame.and_then(|f| f.page));
+ var_cache.entry(page).or_insert_with(|| std::sync::Arc::new(vars::values(doc, page, opts.running.as_deref()))).clone()
+ } else {
+ Default::default()
+ };
let sub = SubstCtx {
- page_name: opts.page_name.clone().or_else(|| frames.get(cur.fi.min(frames.len().saturating_sub(1))).and_then(|f| f.page_name.clone())),
+ page_name: opts.page_name.clone().or_else(|| cur_frame.and_then(|f| f.page_name.clone())),
section_marker: None,
+ vars: var_values,
};
let mut table = StyleTable { styles: &mut styles_tab };
let mut sp = shape::shape_para(db, &doc.styles, story, pi, prange.clone(), &base_chars, pp.auto_leading, &sub, &mut table);
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 0c9c8257b..70da7f445 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -66,6 +66,8 @@ pub struct ShapedPara {
pub struct SubstCtx {
pub page_name: Option<String>,
pub section_marker: Option<String>,
+ /// Text variable values by index (on the page being composed).
+ pub vars: Arc<Vec<String>>,
}
pub(crate) struct StyleTable<'a> {
@@ -189,10 +191,21 @@ fn shape_run(
| story::PAGE_BREAK
| story::INDENT_HERE
| story::RIGHT_INDENT_TAB
- );
+ ) || designcraft_doc::vars::var_index(c).is_some();
if special {
flush(seg_start, i, &seg_face, out);
seg_start = i + c.len_utf8();
+ if let Some(vi) = designcraft_doc::vars::var_index(c) {
+ match sub.vars.get(vi).filter(|v| !v.is_empty()) {
+ Some(v) => shape_segment(db, text, i..i + c.len_utf8(), Some(v), p, &primary, auto_leading, style, out),
+ None => {
+ let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
+ g.adv = 0.0;
+ out.push(g);
+ }
+ }
+ continue;
+ }
match c {
story::PAGE_NUMBER | story::NEXT_PAGE_NUMBER | story::PREV_PAGE_NUMBER | story::SECTION_MARKER => {
let s = if c == story::SECTION_MARKER {
diff --git a/crates/compose/src/vars.rs b/crates/compose/src/vars.rs
new file mode 100644
index 000000000..c3f178fde
--- /dev/null
+++ b/crates/compose/src/vars.rs
@@ -0,0 +1,140 @@
+//! Text variable resolution at composition time, including running headers (which depend on
+//! where paragraphs of a style land in the composed document).
+
+use std::collections::{BTreeMap, HashMap};
+use std::sync::Arc;
+
+use designcraft_doc::vars::{Use, VarKind, var_index};
+use designcraft_doc::{Document, SpreadRef, Story, StoryId};
+
+use crate::ComposedStory;
+
+/// Does the story contain any text variable instance?
+pub fn has_vars(st: &Story) -> bool {
+ st.text.chars().any(|c| var_index(c).is_some())
+}
+
+/// Does the story contain a running-header variable instance?
+pub fn has_running(doc: &Document, st: &Story) -> bool {
+ st.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. })))
+}
+
+/// Per (style, is character style): page → (first text, last text) on that page.
+#[derive(Debug, Default)]
+pub struct RunningIndex {
+ map: HashMap<(String, bool), BTreeMap<usize, (String, String)>>,
+}
+
+fn clean(s: &str) -> String {
+ let t: String =
+ s.chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).map(|c| if c == '\t' || c == '\u{2028}' { ' ' } else { c }).collect();
+ t.trim().to_string()
+}
+
+/// (absolute page, y, x) of story byte `pos` in a composed story.
+fn place(doc: &Document, cs: &ComposedStory, pos: usize) -> Option<(usize, i64, i64)> {
+ let (fi, x, baseline, ..) = crate::caret(cs, pos)?;
+ let ft = cs.frames.get(fi)?;
+ let loc = doc.find(ft.frame)?;
+ let SpreadRef::Doc(si) = loc.spread else { return None };
+ let b = doc.item(ft.frame)?.bounds();
+ let pi = doc.spreads.get(si)?.page_at_x(b.center().x).unwrap_or(0);
+ Some((doc.first_page_of_spread(si) + pi, ((b.y0 + baseline) * 10.0) as i64, ((b.x0 + x) * 10.0) as i64))
+}
+
+impl RunningIndex {
+ /// Index the paragraphs / runs that running-header variables refer to. `get` composes a story
+ /// (normally through the cache); stories that themselves contain running headers are skipped.
+ pub fn build(doc: &Document, get: &dyn Fn(StoryId) -> Arc<ComposedStory>) -> RunningIndex {
+ let wanted: Vec<(String, bool)> = doc
+ .text_variables
+ .iter()
+ .filter_map(|v| match &v.kind {
+ VarKind::RunningHeader { style, character, .. } => Some((style.clone(), *character)),
+ _ => None,
+ })
+ .collect();
+ let mut hits: HashMap<(String, bool), Vec<((usize, i64, i64), String)>> = HashMap::new();
+ if wanted.is_empty() {
+ return RunningIndex::default();
+ }
+ for (sid, st) in &doc.stories {
+ if has_running(doc, st) {
+ continue;
+ }
+ let para_hit = st.paras.iter().any(|f| wanted.iter().any(|(s, c)| !c && *s == f.style));
+ let char_hit = wanted.iter().any(|(_, c)| *c) && st.runs().any(|(_, f)| wanted.iter().any(|(s, c)| *c && *s == f.style));
+ if !para_hit && !char_hit {
+ continue;
+ }
+ let cs = get(*sid);
+ if para_hit {
+ for (pi, r) in st.para_ranges().into_iter().enumerate() {
+ let key = (st.paras[pi].style.clone(), false);
+ if !wanted.contains(&key) {
+ continue;
+ }
+ let text = clean(&st.text[r.clone()]);
+ if text.is_empty() {
+ continue;
+ }
+ if let Some(at) = place(doc, &cs, r.start) {
+ hits.entry(key).or_default().push((at, text));
+ }
+ }
+ }
+ if char_hit {
+ for (r, f) in st.runs() {
+ let key = (f.style.clone(), true);
+ if !wanted.contains(&key) {
+ continue;
+ }
+ let text = clean(&st.text[r.clone()]);
+ if text.is_empty() {
+ continue;
+ }
+ if let Some(at) = place(doc, &cs, r.start) {
+ hits.entry(key).or_default().push((at, text));
+ }
+ }
+ }
+ }
+ let mut map = HashMap::new();
+ for (key, mut v) in hits {
+ v.sort_by_key(|(at, _)| *at);
+ let mut pages: BTreeMap<usize, (String, String)> = BTreeMap::new();
+ for ((page, ..), text) in v {
+ pages.entry(page).and_modify(|e| e.1 = text.clone()).or_insert((text.clone(), text));
+ }
+ map.insert(key, pages);
+ }
+ RunningIndex { map }
+ }
+
+ /// The running header for `page`: the first/last on the page, else the last before it.
+ pub fn value(&self, style: &str, character: bool, use_: Use, page: usize) -> String {
+ let Some(pages) = self.map.get(&(style.to_string(), character)) else { return String::new() };
+ if let Some((first, last)) = pages.get(&page) {
+ return if use_ == Use::FirstOnPage { first.clone() } else { last.clone() };
+ }
+ pages.range(..page).next_back().map(|(_, (_, last))| last.clone()).unwrap_or_default()
+ }
+}
+
+/// Values of every variable on `page`.
+pub fn values(doc: &Document, page: Option<usize>, running: Option<&RunningIndex>) -> Vec<String> {
+ doc.text_variables
+ .iter()
+ .enumerate()
+ .map(|(i, v)| match &v.kind {
+ VarKind::RunningHeader { style, use_, character } => {
+ let body = match (running, page) {
+ (Some(r), Some(p)) => r.value(style, *character, *use_, p),
+ _ => String::new(),
+ };
+ format!("{}{}{}", v.before, body, v.after)
+ }
+ _ => doc.variable_value(i, page).unwrap_or_default(),
+ })
+ .collect()
+}
diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs
index 605655334..451628c55 100644
--- a/crates/doc/src/build.rs
+++ b/crates/doc/src/build.rs
@@ -139,6 +139,9 @@ impl Document {
bookmarks: vec![],
user_words: vec![],
toc: None,
+ text_variables: crate::vars::defaults(),
+ created: crate::vars::now(),
+ modified: 0,
next_id: 0,
};
let lid = LayerId(d.alloc());
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 3450f8d50..bd3e962d5 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -17,6 +17,7 @@ pub mod page;
pub mod selection;
pub mod story;
pub mod styles;
+pub mod vars;
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -125,6 +126,8 @@ pub struct DocSettings {
pub bleed_color: [u8; 3],
pub slug_color: [u8; 3],
pub keyboard_increment: f64,
+ /// Chapter number (Numbering & Section Options › Document Chapter Numbering).
+ pub chapter_number: u32,
}
impl Default for DocSettings {
@@ -147,6 +150,7 @@ impl Default for DocSettings {
bleed_color: [255, 72, 103],
slug_color: [100, 188, 221],
keyboard_increment: 1.0,
+ chapter_number: 1,
}
}
}
@@ -238,6 +242,14 @@ pub struct Document {
/// The generated table of contents (Layout → Table of Contents), kept for Update.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub toc: Option<Toc>,
+ /// Text variable definitions (instances in stories are `vars::var_char(index)`).
+ #[serde(default = "vars::defaults")]
+ pub text_variables: Vec<vars::TextVariable>,
+ /// Creation / last save time (Unix seconds, UTC).
+ #[serde(default)]
+ pub created: i64,
+ #[serde(default)]
+ pub modified: i64,
pub next_id: u64,
}
diff --git a/crates/doc/src/vars.rs b/crates/doc/src/vars.rs
new file mode 100644
index 000000000..119b1dbd0
--- /dev/null
+++ b/crates/doc/src/vars.rs
@@ -0,0 +1,229 @@
+//! Text variables (Type → Text Variables): named values inserted into stories as a single
+//! character (`U+E100 + index`) and resolved at composition, per page where it matters.
+
+use serde::{Deserialize, Serialize};
+
+use crate::Document;
+
+/// First character of the variable-instance range; instance `i` refers to `doc.text_variables[i]`.
+pub const VAR_BASE: u32 = 0xE100;
+pub const VAR_MAX: usize = 256;
+
+/// The story character for variable index `i`.
+pub fn var_char(i: usize) -> Option<char> {
+ (i < VAR_MAX).then(|| char::from_u32(VAR_BASE + i as u32)).flatten()
+}
+
+/// The variable index of a story character, if it is a variable instance.
+pub fn var_index(c: char) -> Option<usize> {
+ let u = c as u32;
+ (VAR_BASE..VAR_BASE + VAR_MAX as u32).contains(&u).then(|| (u - VAR_BASE) as usize)
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Use {
+ #[default]
+ FirstOnPage,
+ LastOnPage,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "camelCase")]
+pub enum VarKind {
+ Custom {
+ text: String,
+ },
+ /// The last page number of the document (or of the section).
+ LastPageNumber {
+ #[serde(default)]
+ section: bool,
+ },
+ ChapterNumber,
+ /// Document title (InDesign: file name).
+ FileName {
+ #[serde(default)]
+ extension: bool,
+ },
+ /// Date formats use `yyyy`, `MM`, `MMMM`, `MMM`, `dd`, `d`, `HH`, `mm`.
+ CreationDate {
+ format: String,
+ },
+ ModificationDate {
+ format: String,
+ },
+ OutputDate {
+ format: String,
+ },
+ /// The first/last paragraph (or character-style run) on the page using `style`;
+ /// pages without one carry the last value from earlier pages.
+ RunningHeader {
+ style: String,
+ #[serde(default, rename = "use")]
+ use_: Use,
+ /// `style` names a character style instead of a paragraph style.
+ #[serde(default)]
+ character: bool,
+ },
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TextVariable {
+ pub name: String,
+ #[serde(flatten)]
+ pub kind: VarKind,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub before: String,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub after: String,
+}
+
+impl TextVariable {
+ pub fn new(name: &str, kind: VarKind) -> TextVariable {
+ TextVariable { name: name.into(), kind, before: String::new(), after: String::new() }
+ }
+}
+
+/// InDesign's predefined variables.
+pub fn defaults() -> Vec<TextVariable> {
+ vec![
+ TextVariable::new("Chapter Number", VarKind::ChapterNumber),
+ TextVariable::new("Creation Date", VarKind::CreationDate { format: "MM/dd/yy".into() }),
+ TextVariable::new("File Name", VarKind::FileName { extension: false }),
+ TextVariable::new("Last Page Number", VarKind::LastPageNumber { section: false }),
+ TextVariable::new("Modification Date", VarKind::ModificationDate { format: "MMMM d, yyyy h:mm aa".into() }),
+ TextVariable::new("Output Date", VarKind::OutputDate { format: "MM/dd/yy".into() }),
+ TextVariable::new(
+ "Running Header",
+ VarKind::RunningHeader { style: crate::story::BASIC_PARAGRAPH.into(), use_: Use::FirstOnPage, character: false },
+ ),
+ ]
+}
+
+/// Seconds since the Unix epoch (0 where the platform has no clock).
+pub fn now() -> i64 {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ 0
+ }
+}
+
+/// (year, month 1–12, day 1–31) from days since 1970-01-01 (H. Hinnant's public-domain algorithm).
+fn civil(days: i64) -> (i64, u32, u32) {
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z.rem_euclid(146_097);
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
+ (yoe + era * 400 + i64::from(m <= 2), m, d)
+}
+
+const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
+
+/// Format Unix seconds (UTC) with an InDesign-style pattern.
+pub fn format_date(secs: i64, fmt: &str) -> String {
+ let (y, mo, d) = civil(secs.div_euclid(86_400));
+ let sod = secs.rem_euclid(86_400);
+ let (h, mi) = ((sod / 3600) as u32, ((sod % 3600) / 60) as u32);
+ let tokens: [(&str, String); 13] = [
+ ("yyyy", format!("{y:04}")),
+ ("yy", format!("{:02}", y.rem_euclid(100))),
+ ("MMMM", MONTHS[(mo - 1) as usize].into()),
+ ("MMM", MONTHS[(mo - 1) as usize][..3].into()),
+ ("MM", format!("{mo:02}")),
+ ("M", mo.to_string()),
+ ("dd", format!("{d:02}")),
+ ("d", d.to_string()),
+ ("HH", format!("{h:02}")),
+ ("H", h.to_string()),
+ ("h", (if h % 12 == 0 { 12 } else { h % 12 }).to_string()),
+ ("mm", format!("{mi:02}")),
+ ("aa", (if h < 12 { "AM" } else { "PM" }).into()),
+ ];
+ let mut out = String::new();
+ let mut rest = fmt;
+ 'outer: while !rest.is_empty() {
+ for (t, v) in &tokens {
+ if let Some(r) = rest.strip_prefix(t) {
+ out.push_str(v);
+ rest = r;
+ continue 'outer;
+ }
+ }
+ let c = rest.chars().next().unwrap_or(' ');
+ out.push(c);
+ rest = &rest[c.len_utf8()..];
+ }
+ out
+}
+
+impl Document {
+ /// The value of variable `i` on absolute page `page`, except running headers (which need the
+ /// composed document; see the compose crate). `None` for unknown indices and running headers.
+ pub fn variable_value(&self, i: usize, page: Option<usize>) -> Option<String> {
+ let v = self.text_variables.get(i)?;
+ let body = match &v.kind {
+ VarKind::Custom { text } => text.clone(),
+ VarKind::LastPageNumber { section } => {
+ let n = self.page_count();
+ if n == 0 {
+ return Some(String::new());
+ }
+ let last = if *section {
+ let p = page.unwrap_or(0);
+ let next = self.sections.iter().map(|s| s.start).filter(|s| *s > p).min().unwrap_or(n);
+ next.saturating_sub(1)
+ } else {
+ n - 1
+ };
+ self.page_name(last)
+ }
+ VarKind::ChapterNumber => self.settings.chapter_number.max(1).to_string(),
+ VarKind::FileName { extension } => {
+ if *extension {
+ format!("{}.designcraft", self.title)
+ } else {
+ self.title.clone()
+ }
+ }
+ VarKind::CreationDate { format } => format_date(self.created, format),
+ VarKind::ModificationDate { format } => format_date(if self.modified > 0 { self.modified } else { self.created }, format),
+ VarKind::OutputDate { format } => format_date(now(), format),
+ VarKind::RunningHeader { .. } => return None,
+ };
+ Some(format!("{}{}{}", v.before, body, v.after))
+ }
+
+ pub fn variable(&self, name: &str) -> Option<usize> {
+ self.text_variables.iter().position(|v| v.name == name)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dates() {
+ // 2026-10-01 14:05 UTC
+ let t = 1_790_863_500;
+ assert_eq!(format_date(t, "yyyy-MM-dd HH:mm"), "2026-10-01 14:05");
+ assert_eq!(format_date(t, "MMMM d, yyyy h:mm aa"), "October 1, 2026 2:05 PM");
+ assert_eq!(format_date(0, "MM/dd/yy"), "01/01/70");
+ assert_eq!(format_date(951_782_400, "yyyy-MM-dd"), "2000-02-29");
+ }
+
+ #[test]
+ fn chars() {
+ assert_eq!(var_index(var_char(3).unwrap()), Some(3));
+ assert_eq!(var_index('\u{E000}'), None);
+ }
+}
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 2584d0bcd..59912b5d2 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -15,6 +15,7 @@ pub mod spelling;
mod style;
pub mod text;
mod toc;
+mod variables;
use designcraft_doc::{ItemId, SpreadRef};
use designcraft_geom::{Point, Rect};
@@ -117,6 +118,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layout::specs());
v.extend(inspect::specs());
v.extend(find::specs());
+ v.extend(variables::specs());
v.extend(toc::specs());
v.extend(spelling::specs());
v.extend(datamerge::specs());
diff --git a/crates/engine/src/cmd/toc.rs b/crates/engine/src/cmd/toc.rs
index 7083e497e..d6ed53d6a 100644
--- a/crates/engine/src/cmd/toc.rs
+++ b/crates/engine/src/cmd/toc.rs
@@ -73,7 +73,7 @@ pub fn collect(d: &Document, entries: &[TocEntry], skip: Option<StoryId>) -> Vec
let Some(e) = entries.iter().find(|e| e.style == st.paras[pi].style) else { continue };
let text: String = st.text[r.clone()]
.chars()
- .filter(|c| !('\u{E000}'..='\u{E0FF}').contains(c))
+ .filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c))
.map(|c| if c == '\t' || c == '\u{2028}' { ' ' } else { c })
.collect();
let text = text.trim().to_string();
diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs
new file mode 100644
index 000000000..bbcfaf0a1
--- /dev/null
+++ b/crates/engine/src/cmd/variables.rs
@@ -0,0 +1,177 @@
+//! Type → Text Variables: define, list, delete and insert variables.
+
+use designcraft_doc::vars::{TextVariable, VarKind, var_char};
+use serde_json::{Value, json};
+
+use super::{CommandSpec, bad, cmd, has_doc, str_param};
+use crate::{Result, Session};
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(query "variables.list", "Text Variables", [], None, "{} → [{index, name, type, …, value (page 1)}]", has_doc, |s, _| {
+ let d = &s.doc()?.doc;
+ Ok(Value::Array(
+ d.text_variables
+ .iter()
+ .enumerate()
+ .map(|(i, v)| {
+ let mut o = serde_json::to_value(v).unwrap_or_default();
+ o["index"] = json!(i);
+ o["value"] = json!(d.variable_value(i, Some(0)));
+ o
+ })
+ .collect(),
+ ))
+ }),
+ cmd!(
+ "variables.define",
+ "Define Text Variable…",
+ ["Type", "Text Variables"],
+ None,
+ "{name, type: custom|lastPageNumber|chapterNumber|fileName|creationDate|modificationDate|outputDate|runningHeader, text?, format?, style?, use?: firstOnPage|lastOnPage, character?, section?, extension?, before?, after?} — creates or replaces by name",
+ has_doc,
+ define
+ ),
+ cmd!(
+ "variables.delete",
+ "Delete Text Variable",
+ [],
+ None,
+ "{name} — instances become plain text of their current value",
+ has_doc,
+ |s, p| {
+ let name = str_param(p, "name").ok_or_else(|| bad("variables.delete", "missing name"))?.to_string();
+ s.edit(|d, _| {
+ let i = d.variable(&name).ok_or_else(|| bad("variables.delete", format!("no variable `{name}`")))?;
+ // Replace instances with their value (first page context), then shift higher indices down.
+ let value = d.variable_value(i, Some(0)).unwrap_or_default();
+ let n = d.text_variables.len();
+ let ids: Vec<_> = d.stories.keys().copied().collect();
+ for sid in ids {
+ let Some(st) = d.story(sid) else { continue };
+ if !st.text.chars().any(|c| designcraft_doc::vars::var_index(c).is_some_and(|k| k >= i)) {
+ continue;
+ }
+ let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?;
+ let target = var_char(i).unwrap_or(' ').to_string();
+ while let Some(pos) = st.text.find(&target) {
+ st.replace(pos..pos + target.len(), &value);
+ }
+ for k in i + 1..n {
+ let (from, to) = (var_char(k).unwrap_or(' ').to_string(), var_char(k - 1).unwrap_or(' ').to_string());
+ while let Some(pos) = st.text.find(&from) {
+ st.replace(pos..pos + from.len(), &to);
+ }
+ }
+ }
+ d.text_variables.remove(i);
+ Ok(Value::Null)
+ })
+ }
+ ),
+ cmd!(
+ "variables.insert",
+ "Insert Variable",
+ ["Type", "Text Variables"],
+ None,
+ "{name} — at the text insertion point",
+ super::has_text,
+ |s, p| {
+ let name = str_param(p, "name").ok_or_else(|| bad("variables.insert", "missing name"))?;
+ let i = s.doc()?.doc.variable(name).ok_or_else(|| bad("variables.insert", format!("no variable `{name}`")))?;
+ let c = var_char(i).ok_or_else(|| bad("variables.insert", "too many variables"))?;
+ s.execute("text.insert", &json!({"text": c.to_string()}))
+ }
+ ),
+ ]
+}
+
+fn define(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").ok_or_else(|| bad("variables.define", "missing name"))?.to_string();
+ let fmt = || str_param(p, "format").unwrap_or("MM/dd/yy").to_string();
+ let kind = match str_param(p, "type").unwrap_or("custom") {
+ "custom" => VarKind::Custom { text: str_param(p, "text").unwrap_or("").into() },
+ "lastPageNumber" => VarKind::LastPageNumber { section: p.get("section").and_then(Value::as_bool).unwrap_or(false) },
+ "chapterNumber" => VarKind::ChapterNumber,
+ "fileName" => VarKind::FileName { extension: p.get("extension").and_then(Value::as_bool).unwrap_or(false) },
+ "creationDate" => VarKind::CreationDate { format: fmt() },
+ "modificationDate" => VarKind::ModificationDate { format: fmt() },
+ "outputDate" => VarKind::OutputDate { format: fmt() },
+ "runningHeader" => VarKind::RunningHeader {
+ style: str_param(p, "style").ok_or_else(|| bad("variables.define", "runningHeader needs `style`"))?.into(),
+ use_: if str_param(p, "use") == Some("lastOnPage") { designcraft_doc::vars::Use::LastOnPage } else { Default::default() },
+ character: p.get("character").and_then(Value::as_bool).unwrap_or(false),
+ },
+ t => return Err(bad("variables.define", format!("unknown type `{t}`"))),
+ };
+ let mut v = TextVariable::new(&name, kind);
+ v.before = str_param(p, "before").unwrap_or("").into();
+ v.after = str_param(p, "after").unwrap_or("").into();
+ s.edit(|d, _| {
+ let i = match d.variable(&name) {
+ Some(i) => {
+ d.text_variables[i] = v.clone();
+ i
+ }
+ None => {
+ if d.text_variables.len() >= designcraft_doc::vars::VAR_MAX {
+ return Err(bad("variables.define", "too many variables"));
+ }
+ d.text_variables.push(v.clone());
+ d.text_variables.len() - 1
+ }
+ };
+ Ok(json!({"index": i}))
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn running_header_on_parent_page_follows_headings() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Heading"})).ok();
+ // Headings on pages 1 and 3 (page 2 carries page 1's).
+ for (page, text) in [(0, "Alpha"), (2, "Epsilon")] {
+ let sp = s.doc().unwrap().doc.page_loc(page).unwrap().0;
+ let r = s.execute("frame.create", &json!({"spread": sp, "rect": [72, 200, 400, 260], "content": "text", "text": text})).unwrap();
+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;
+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 1})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": "Heading"})).unwrap();
+ }
+ s.execute("variables.define", &json!({"name": "Chapter Head", "type": "runningHeader", "style": "Heading"})).unwrap();
+ s.execute("variables.define", &json!({"name": "Total", "type": "custom", "text": "of "})).unwrap();
+ // A header frame on the parent with "<running header> · <page> / <last page>".
+ let r = s
+ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": ""}))
+ .unwrap();
+ let fid = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ let sid = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;
+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
+ s.execute("variables.insert", &json!({"name": "Chapter Head"})).unwrap();
+ s.execute("text.insert", &json!({"text": " · "})).unwrap();
+ s.execute("variables.insert", &json!({"name": "Last Page Number"})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ assert!(matches!(d.find(fid).unwrap().spread, designcraft_doc::SpreadRef::Parent(0)));
+ // Visible glyphs of the header composed for each page: "Alpha · 3" vs "Epsilon · 3".
+ let shown = |page: usize| -> usize {
+ let cs = s.cache.get(&d, sid, Some(&d.page_name(page)));
+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()
+ };
+ let (p1, p2, p3) = (shown(0), shown(1), shown(2));
+ assert_eq!(p1, p2, "page 2 carries page 1's header");
+ assert_eq!(p3, p1 + 2, "Epsilon is two letters longer than Alpha");
+ let idx = s.cache.running_index(&d);
+ assert_eq!(idx.value("Heading", false, Default::default(), 0), "Alpha");
+ assert_eq!(idx.value("Heading", false, Default::default(), 1), "Alpha");
+ assert_eq!(idx.value("Heading", false, Default::default(), 2), "Epsilon");
+ let list = s.execute("variables.list", &json!({})).unwrap();
+ assert!(list.as_array().unwrap().iter().any(|v| v["name"] == "Last Page Number" && v["value"] == "3"));
+ // Deleting a variable flattens its instances to text.
+ s.execute("variables.delete", &json!({"name": "Last Page Number"})).unwrap();
+ assert!(s.doc().unwrap().doc.story(sid).unwrap().text.ends_with(" · 3"));
+ }
+}
diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs
index be55f7c68..3b3aadc4a 100644
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@ -45,7 +45,7 @@ fn esc(s: &str) -> String {
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
- '\u{E000}'..='\u{E0FF}' => {}
+ '\u{E000}'..='\u{E1FF}' => {}
'\u{2028}' => o.push_str("<br/>"),
'\u{AD}' => o.push_str("&#173;"),
c => o.push(c),
@@ -221,7 +221,19 @@ pub fn story_html(doc: &Document, sid: StoryId) -> String {
if a >= b {
continue;
}
- let t = esc(&st.text[a..b]);
+ let raw = &st.text[a..b];
+ let t = if raw.chars().any(|c| designcraft_doc::vars::var_index(c).is_some()) {
+ let sub: String = raw
+ .chars()
+ .map(|c| match designcraft_doc::vars::var_index(c) {
+ Some(i) => doc.variable_value(i, None).unwrap_or_default(),
+ None => c.to_string(),
+ })
+ .collect();
+ esc(&sub)
+ } else {
+ esc(raw)
+ };
let cls = if f.style != story::NO_CHAR_STYLE { format!(" class=\"{}\"", slug(&f.style)) } else { String::new() };
let style = override_css(doc, &f.over);
let style_attr = if style.is_empty() { String::new() } else { format!(" style=\"{style}\"") };
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index ca67d76cd..16f89d516 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -1355,6 +1355,9 @@ impl<'r> Importer<'r> {
bookmarks: vec![],
user_words: vec![],
toc: None,
+ text_variables: designcraft_doc::vars::defaults(),
+ created: designcraft_doc::vars::now(),
+ modified: 0,
next_id: self.next_id,
};
Ok(d)
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index f917818bc..0ffec8bf4 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -23,7 +23,7 @@ use crate::export::{Exporter, solid_fill, tf, to_path};
/// Private-use characters DesignCraft stores for markers (page numbers, section markers, breaks).
fn is_marker(c: char) -> bool {
- ('\u{E000}'..='\u{E0FF}').contains(&c)
+ ('\u{E000}'..='\u{E1FF}').contains(&c)
}
fn same_run(a: &PlacedGlyph, b: &PlacedGlyph) -> bool {