Skip to content

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

Merge PR #798

Brandon Thomasbd023252b244
diff --cc ROADMAP.md
index 6a412a42f,04addb11e..c4483f3c9
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -131,65 -127,10 +131,66 @@@ list) · [roadmap.md](docs/roadmap.md)
## Progress log
+- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.
+
Newest first.
+- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
+- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
+- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
+- **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.
+- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.
+- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.
+- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.
+- **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.
+- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.
+- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.
+- **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.
+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+- **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.
+- **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.
+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+- **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.
+- **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.
+- **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page/Spread, New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.
+- **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.
+- **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.
+
+- **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.
+- **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.
+- **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.
+- **2026-10-13** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. No readiness percentage change.
+- **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.
+- **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.
+- **2026-10-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.
+- **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.
+- **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer
+ solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.
+- **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. No readiness percentage change.
+- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load
+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
+ frame just added; click the linked frame or double-click a port to break the thread.
+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers
+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No
+ readiness percentage change.
+- **2026-10-14** · Georgian interface (`ka`, Edit ▸ Interface Language ▸ ქართული): every catalog key
+ translated, count captions as `noun: n`.
+- **2026-10-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. No readiness percentage change.
+- **2026-10-13** · Control-channel clicks and drags validate positive counts and the complete pending-event budget before queuing input (#732). Oversized requests leave pending gestures intact, preventing unbounded click-count allocation. No readiness percentage change.
+- **2026-10-13** · Backspace between two consecutive tables, pasting a table next to a table anchor, and pasting several paragraphs right before one keep every table on its own anchor paragraph. Previously a table was dropped or left without its anchor, and the saved file failed to reopen. No readiness percentage change.
+- **2026-10-13** · Dialogs and the About window move when you drag their title row, so the page behind them can be seen. A dragged dialog may go partly off-screen, but its title row stays reachable; each dialog opens centred, and again after the window is resized. No readiness percentage change.
+- **2026-10-13** · Command scripts look up only a well-formed `$N.path` / `$last.path` reference; other strings starting with `$`, such as a GREP replacement of `$1` and a nonbreaking space, stay as written, and `$$` writes a literal `$` (#749). No readiness percentage change.
+- **2026-10-13** · An explicit recovery folder (`file.recovery.save` with `dir`) never overwrites or deletes another running app's checkpoints. Document uids start at 1 in every process, so two apps saving recovery to one chosen folder replaced or removed each other's `<uid>.designcraft`. A run replaces or removes only the entries it wrote or recovered there, refuses an occupied uid, and refuses a folder whose run lock another app holds. No readiness percentage change.
+- **2026-10-13** · Path edits (`path.setAnchor`, `path.moveAnchors`, `path.appendAnchor`, `path.reverse`, `path.close`, anchor add/delete/convert, Erase, Smooth and Scissors) refuse a path that is locked, sits in a locked group or on a locked layer (#735). Properties links to the Stroke, Character, Paragraph, Effects, Text Wrap and Info panels open them in a customized panel layout too (#736). No readiness percentage change.
+- **2026-10-13** · IDML export keeps parent item overrides: each page lists its overridden parent items and the local copy keeps its link to the parent item, so a reopened IDML file shows only the local copy (#725). No readiness percentage change.
+- **2026-10-13** · macOS: a command chosen with the mouse in the menu bar runs at once. It used to wait for the next mouse move or key press over the window, so File › Open, Place and Save As seemed to take 10–20 seconds to open their dialogs. No readiness percentage change.
+- **2026-10-13** · Text recomposes when the document baseline grid changes, when a layer holding a text-wrap object is shown or hidden, or when a section's start number, numbering style, prefix or marker changes; the composition cache keyed only on the section count and item identities and kept the old layout. No readiness percentage change.
+ - **2026-10-13** · Reflowable EPUB and HTML export include tables (header and footer rows, merged cells), footnotes (a linked note after the paragraph that refers to it) and endnotes (a linked section at the end of the book). No readiness percentage change.
- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.
+- **2026-10-12** · Text strokes can sit behind the fill: the stroke lies wholly outside the letters at its full weight on screen, in PNG and in PDF, set from the Properties panel or Character Style Options. IDML `StrokeAlignment` on text imports and exports as this setting, so imported text with outside-aligned strokes keeps its letter shapes (#619). No readiness percentage change.
+- **2026-10-12** · Placed Word documents keep their bullets and numbering (#626): `numbering.xml` levels become bullet or numbered paragraphs with Word's number formats, label text, start numbers, restarts and list indents, also when a paragraph style carries the list. No readiness percentage change.
- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.
diff --cc crates/epub/src/lib.rs
index 5cdf14184,cedcbff76..cd14ac5ba
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -443,71 -430,96 +448,169 @@@ fn class_selector(tag: &str, class: &st
Some(selector)
}
- /// One story as XHTML paragraphs (anchored objects left out; see [`story_html_with`]).
- pub fn story_html(doc: &Document, sid: StoryId) -> String {
- story_html_with(doc, sid, None, &mut |_| String::new())
+ /// Nesting limit for stories inside stories (table cells, footnotes, tables in cells), so a deeply
+ /// nested or cyclic document can't recurse without bound.
+ const MAX_DEPTH: usize = 8;
+
+ /// Writes stories with their tables and notes, numbering notes across the stories of one export.
+ struct StoryWriter<'a> {
+ doc: &'a Document,
+ pc: BTreeMap<&'a str, String>,
+ cc: BTreeMap<&'a str, String>,
+ /// EPUB structural semantics (`epub:type`); plain HTML doesn't declare the namespace.
+ epub: bool,
+ /// Notes written so far, for unique element ids.
+ footnote_ids: u32,
+ endnote_ids: u32,
+ /// Number shown on the next footnote and endnote of the current story.
+ next_footnote: u32,
+ next_endnote: u32,
+ /// Endnotes met so far: (number, list item markup).
+ endnotes: Vec<(u32, String)>,
}
- /// One story as XHTML paragraphs, each anchored object written where it is anchored as the
- /// markup `object` returns for it. With `ids`, every heading (`h1`–`h6`) gets an `id`,
- /// `{prefix}-p{paragraph index}`: the targets of the table of contents.
- fn story_html_with(
- doc: &Document,
- sid: StoryId,
- ids: Option<&str>,
- object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String,
- ) -> String {
- let Some(st) = doc.story(sid) else { return String::new() };
- let (pc, cc) = (para_classes(&doc.styles), char_classes(&doc.styles));
- let mut out = String::new();
- // Consecutive `li` paragraphs share one list (`ol` for a numbered style, `ul` for a bulleted
- // one, an unmarked `ul` when the style has no list type of its own, e.g. typed bullets), and
- // consecutive `pre` paragraphs of one style one block, their lines separated by newlines.
- let mut list: Option<&str> = None;
- let mut pre: Option<(String, bool)> = None;
- for (pi, r) in st.para_ranges().iter().enumerate() {
- let pf = &st.paras[pi];
- // Export Tagging: the style's element and class.
- let (tag, class) = export_mapping(&doc.styles, &pf.style, false, &pc);
- let text_empty = st.text[r.clone()].trim().is_empty();
- let props = doc.styles.resolve_para(pf).0;
- let rtl = props.direction == designcraft_doc::TextDirection::RightToLeft;
- let continues_pre = tag == "pre" && pre.as_ref() == Some(&(class.clone(), rtl));
- if !continues_pre && pre.take().is_some() {
- out.push_str("</pre>\n");
+ impl<'a> StoryWriter<'a> {
+ fn new(doc: &'a Document, epub: bool) -> Self {
+ StoryWriter {
+ doc,
+ pc: para_classes(&doc.styles),
+ cc: char_classes(&doc.styles),
+ epub,
+ footnote_ids: 0,
+ endnote_ids: 0,
+ next_footnote: 1,
+ next_endnote: 1,
+ endnotes: Vec::new(),
}
- let list_tag = (tag == "li").then_some(match props.list_type {
- designcraft_doc::ListType::Numbers => "ol",
- designcraft_doc::ListType::Bullets => "ul",
- designcraft_doc::ListType::None => "ul style=\"list-style:none\"",
- });
- if list != list_tag {
- if let Some(l) = list {
- let _ = writeln!(out, "</{}>", l.split(' ').next().unwrap_or(l));
+ }
+
+ fn epub_type(&self, t: &str) -> String {
+ if self.epub { format!(" epub:type=\"{t}\"") } else { String::new() }
+ }
+
+ /// One document story: paragraphs, tables, and each footnote after the paragraph that refers
+ /// to it.
- fn story(&mut self, sid: StoryId) -> String {
++ /// With `ids`, every heading (`h1`–`h6`) gets an `id`, `{prefix}-p{paragraph index}` (the
++ /// targets of the table of contents), and each `h1` starts a chapter. Each anchored object is
++ /// written where it is anchored as the markup `object` returns for it.
++ fn story(&mut self, sid: StoryId, ids: Option<&str>, object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String) -> String {
+ let Some(st) = self.doc.story(sid) else { return String::new() };
+ self.next_footnote = self.doc.footnote_start(sid);
+ self.next_endnote = self.doc.endnote_start(sid);
+ let mut out = String::new();
- self.paragraphs(st, 0, "", &mut out);
++ self.paragraphs(st, 0, "", ids, object, &mut out);
+ out
+ }
+
- /// `st`'s paragraphs. `lead` (a note's number) starts the first paragraph.
- fn paragraphs(&mut self, st: &Story, depth: usize, lead: &str, out: &mut String) {
++ /// `st`'s paragraphs. `lead` (a note's number) starts the first paragraph. Consecutive `li`
++ /// paragraphs share one list (`ol` for a numbered style, `ul` for a bulleted one, an unmarked
++ /// `ul` when the style has no list type of its own, e.g. typed bullets), and consecutive `pre`
++ /// paragraphs of one style one block, their lines separated by newlines.
++ fn paragraphs(
++ &mut self,
++ st: &Story,
++ depth: usize,
++ lead: &str,
++ ids: Option<&str>,
++ object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String,
++ out: &mut String,
++ ) {
+ let doc = self.doc;
+ let mut lead = lead;
- for (r, pf) in st.para_ranges().into_iter().zip(&st.paras) {
++ let mut list: Option<&str> = None;
++ let mut pre: Option<(String, bool)> = None;
++ // Closes an open `pre` block and list, before anything that can't go inside them.
++ fn close(out: &mut String, list: &mut Option<&str>, pre: &mut Option<(String, bool)>) {
++ if pre.take().is_some() {
++ out.push_str("</pre>\n");
+ }
- if let Some(l) = list_tag {
- let _ = writeln!(out, "<{l}>");
++ if let Some(l) = list.take() {
++ let _ = writeln!(out, "</{}>", l.split(' ').next().unwrap_or(l));
+ }
- list = list_tag;
+ }
- if continues_pre {
- out.push('\n');
- } else {
- let id = match ids {
- Some(prefix) if heading_level(tag).is_some() => format!(" id=\"{prefix}-p{pi}\""),
- _ => String::new(),
- };
- if ids.is_some() && heading_level(tag) == Some(1) {
- out.push_str(CHAPTER_MARK);
++ for (pi, (r, pf)) in st.para_ranges().into_iter().zip(&st.paras).enumerate() {
+ let Some(text) = st.text.get(r.clone()) else { continue };
+ let table = pf.table.and_then(|id| st.tables.get(&id)).filter(|_| text.contains(story::TABLE_ANCHOR));
+ let only_table = table.is_some() && text.chars().all(|c| c == story::TABLE_ANCHOR || c.is_whitespace());
+ if !only_table || !lead.is_empty() {
+ // Export Tagging: the style's element and class.
+ let (tag, class) = export_mapping(&doc.styles, &pf.style, false, &self.pc);
- let rtl = doc.styles.resolve_para(pf).0.direction == designcraft_doc::TextDirection::RightToLeft;
- let _ = write!(out, "<{tag} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });
++ let props = doc.styles.resolve_para(pf).0;
++ let rtl = props.direction == designcraft_doc::TextDirection::RightToLeft;
++ let continues_pre = tag == "pre" && lead.is_empty() && pre.as_ref() == Some(&(class.clone(), rtl));
++ if !continues_pre && pre.take().is_some() {
++ out.push_str("</pre>\n");
++ }
++ let list_tag = (tag == "li").then_some(match props.list_type {
++ designcraft_doc::ListType::Numbers => "ol",
++ designcraft_doc::ListType::Bullets => "ul",
++ designcraft_doc::ListType::None => "ul style=\"list-style:none\"",
++ });
++ if list != list_tag {
++ if let Some(l) = list {
++ let _ = writeln!(out, "</{}>", l.split(' ').next().unwrap_or(l));
++ }
++ if let Some(l) = list_tag {
++ let _ = writeln!(out, "<{l}>");
++ }
++ list = list_tag;
++ }
++ if continues_pre {
++ out.push('\n');
++ } else {
++ let id = match ids {
++ Some(prefix) if heading_level(tag).is_some() => format!(" id=\"{prefix}-p{pi}\""),
++ _ => String::new(),
++ };
++ if ids.is_some() && heading_level(tag) == Some(1) {
++ out.push_str(CHAPTER_MARK);
++ }
++ let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });
++ }
+ out.push_str(lead);
+ if lead.is_empty() && text.trim().is_empty() {
+ out.push_str("&#160;");
+ }
+ lead = "";
+ let mut after = String::new();
+ if !only_table {
- self.runs(st, r, depth, out, &mut after);
++ self.runs(st, r, depth, object, out, &mut after);
++ }
++ if tag == "pre" {
++ // Closed when the next paragraph isn't a line of the same block.
++ pre = Some((class, rtl));
++ } else {
++ let _ = writeln!(out, "</{tag}>");
++ }
++ if !after.is_empty() {
++ close(out, &mut list, &mut pre);
++ out.push_str(&after);
+ }
- let _ = writeln!(out, "</{tag}>");
- out.push_str(&after);
+ }
+ if let Some(t) = table
+ && depth < MAX_DEPTH
+ {
- self.table(t, depth + 1, out);
++ close(out, &mut list, &mut pre);
++ self.table(t, depth + 1, object, out);
}
- let _ = write!(out, "<{tag}{id} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" });
- }
- if text_empty {
- out.push_str("&#160;");
}
++ close(out, &mut list, &mut pre);
+ }
+
+ /// 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) {
++ fn runs(
++ &mut self,
++ st: &Story,
++ para: std::ops::Range<usize>,
++ depth: usize,
++ object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String,
++ out: &mut String,
++ after: &mut String,
++ ) {
+ let doc = self.doc;
for (rr, f) in st.runs() {
- let a = rr.start.max(r.start);
- let b = rr.end.min(r.end);
+ let a = rr.start.max(para.start);
+ let b = rr.end.min(para.end);
if a >= b {
continue;
}
@@@ -515,35 -527,26 +618,33 @@@
if f.over.conditions.as_deref().is_some_and(|c| doc.conditions_hide(c)) || f.over.change == Some(designcraft_doc::ChangeMark::Deleted) {
continue;
}
- let raw = &st.text[a..b];
- // Text with variables substituted; each anchored object's markup in place of its mark.
- let text = |seg: &str| {
- if seg.chars().any(|c| designcraft_doc::vars::var_index(c).is_some()) {
- let sub: String = seg
- .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();
- story_markup(&sub)
- } else {
- story_markup(seg)
- }
- };
- let mut mark = st.text.get(..a).map_or(0, |t| t.matches(designcraft_doc::OBJECT_MARK).count());
+ let Some(raw) = st.text.get(a..b) else { continue };
let mut t = String::new();
- for (i, seg) in raw.split(designcraft_doc::OBJECT_MARK).enumerate() {
- if i > 0 {
+ let mut seg_start = 0;
++ // Each anchored object's markup in place of its mark.
++ let mut mark = st.text.get(..a).map_or(0, |t| t.matches(designcraft_doc::OBJECT_MARK).count());
+ for (i, c) in raw.char_indices() {
- if c != FOOTNOTE_REF && c != ENDNOTE_REF {
++ if c != FOOTNOTE_REF && c != ENDNOTE_REF && c != designcraft_doc::OBJECT_MARK {
+ continue;
+ }
+ t.push_str(&run_text(doc, raw.get(seg_start..i).unwrap_or_default()));
+ seg_start = i + c.len_utf8();
- if depth < MAX_DEPTH {
++ if c == designcraft_doc::OBJECT_MARK {
+ if let Some(o) = st.objects.get(mark) {
+ t.push_str(&object(o));
+ }
+ mark += 1;
++ } else if depth < MAX_DEPTH {
+ if c == FOOTNOTE_REF {
- self.footnote(st, a + i, depth, &mut t, after);
++ self.footnote(st, a + i, depth, object, &mut t, after);
+ } else {
- self.endnote(st, a + i, depth, &mut t);
++ self.endnote(st, a + i, depth, object, &mut t);
+ }
}
- t.push_str(&text(seg));
}
+ t.push_str(&run_text(doc, raw.get(seg_start..).unwrap_or_default()));
let (ctag, cls) = if f.style != story::NO_CHAR_STYLE {
- let (tag, class) = export_mapping(&doc.styles, &f.style, true, &cc);
+ let (tag, class) = export_mapping(&doc.styles, &f.style, true, &self.cc);
(tag, format!(" class=\"{}\"", xml_attr(&class)))
} else {
("span", String::new())
@@@ -556,155 -559,139 +657,290 @@@
let _ = write!(out, "<{ctag}{cls}{style_attr}>{t}</{ctag}>");
}
}
- if tag == "pre" {
- // Closed when the next paragraph isn't a line of the same block.
- pre = Some((class, rtl));
- } else {
- let _ = writeln!(out, "</{tag}>");
+ }
+
+ /// The footnote whose reference is at byte `pos` of `st`: a note reference in `out`, the note
+ /// itself in `after`.
- fn footnote(&mut self, st: &Story, pos: usize, depth: usize, out: &mut String, after: &mut String) {
++ fn footnote(
++ &mut self,
++ st: &Story,
++ pos: usize,
++ depth: usize,
++ object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String,
++ out: &mut String,
++ after: &mut String,
++ ) {
+ let Some(note) = st.notes.get(st.notes_before(pos)) else { return };
+ let doc = self.doc;
+ let o = &doc.footnote_options;
+ let n = self.next_footnote;
+ self.next_footnote = n.saturating_add(1);
+ self.footnote_ids = self.footnote_ids.saturating_add(1);
+ let id = self.footnote_ids;
+ let _ = write!(
+ out,
+ "<sup><a{} role=\"doc-noteref\" id=\"fnref-{id}\" href=\"#fn-{id}\">{}</a></sup>",
+ self.epub_type("noteref"),
+ xml_text(&o.label(n, false))
+ );
+ let lead = format!("<a href=\"#fnref-{id}\">{}</a> ", xml_text(&o.label(n, true)));
+ let mut body = String::new();
- self.paragraphs(&note.text, depth + 1, &lead, &mut body);
++ self.paragraphs(&note.text, depth + 1, &lead, None, object, &mut body);
+ let _ = write!(after, "<aside{} role=\"doc-footnote\" id=\"fn-{id}\">\n{body}</aside>\n", self.epub_type("footnote"));
+ }
+
+ /// The endnote whose reference is at byte `pos` of `st`: a note reference in `out`; the note
+ /// joins the endnotes section.
- fn endnote(&mut self, st: &Story, pos: usize, depth: usize, out: &mut String) {
++ fn endnote(
++ &mut self,
++ st: &Story,
++ pos: usize,
++ depth: usize,
++ object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String,
++ out: &mut String,
++ ) {
+ let Some(note) = st.endnotes.get(st.endnotes_before(pos)) else { return };
+ let n = self.next_endnote;
+ self.next_endnote = n.saturating_add(1);
+ self.endnote_ids = self.endnote_ids.saturating_add(1);
+ let id = self.endnote_ids;
+ let label = xml_text(&self.doc.endnote_options.label(n));
+ let _ = write!(out, "<sup><a{} role=\"doc-noteref\" id=\"enref-{id}\" href=\"#en-{id}\">{label}</a></sup>", self.epub_type("noteref"));
+ let mut body = String::new();
- self.paragraphs(&note.text, depth + 1, &format!("<a href=\"#enref-{id}\">{label}</a> "), &mut body);
++ self.paragraphs(&note.text, depth + 1, &format!("<a href=\"#enref-{id}\">{label}</a> "), None, object, &mut body);
+ let item = format!("<li{} id=\"en-{id}\">\n{body}</li>\n", self.epub_type("endnote"));
+ self.endnotes.push((n, item));
+ }
+
+ /// The endnotes met so far, in number order, as one section (empty when there are none).
+ fn endnotes_section(&mut self) -> String {
+ if self.endnotes.is_empty() {
+ return String::new();
}
+ self.endnotes.sort_by_key(|(n, _)| *n);
+ let doc = self.doc;
+ let o = &doc.endnote_options;
+ let mut out = format!("<section{} role=\"doc-endnotes\" id=\"endnotes\">\n", self.epub_type("endnotes"));
+ if !o.heading.trim().is_empty() {
+ let (tag, class) = export_mapping(&doc.styles, &o.heading_style, false, &self.pc);
+ let _ = writeln!(out, "<{tag} class=\"{}\">{}</{tag}>", xml_attr(&class), xml_text(&o.heading));
+ }
+ out.push_str("<ol style=\"list-style: none; padding-left: 0\">\n");
+ for (_, item) in &self.endnotes {
+ out.push_str(item);
+ }
+ out.push_str("</ol>\n</section>\n");
+ out
}
- if pre.is_some() {
- out.push_str("</pre>\n");
+
+ /// A table: header rows as `thead`, footer rows as `tfoot`, merged cells as row and column
+ /// spans (kept within their row group).
- fn table(&mut self, t: &Table, depth: usize, out: &mut String) {
++ fn table(&mut self, t: &Table, depth: usize, object: &mut dyn FnMut(&designcraft_doc::AnchoredObject) -> String, out: &mut String) {
+ let (nr, nc) = (t.nrows(), t.ncols());
+ if nr.checked_mul(nc) != Some(t.cells.len()) {
+ return;
+ }
+ let (h, f) = (t.header_rows(), t.footer_rows());
+ let body_end = nr.saturating_sub(f).max(h);
+ let mut covered = vec![false; t.cells.len()];
+ out.push_str("<table>\n");
+ for (rows, group, cell_tag) in [(0..h, "thead", "th"), (h..body_end, "tbody", "td"), (body_end..nr, "tfoot", "td")] {
+ if rows.is_empty() {
+ continue;
+ }
+ let _ = writeln!(out, "<{group}>");
+ for r in rows.clone() {
+ out.push_str("<tr>");
+ for c in 0..nc {
+ let i = r * nc + c;
+ if covered.get(i).copied().unwrap_or(true) {
+ continue;
+ }
+ let Some(cell) = t.cells.get(i) else { continue };
+ let rs = (cell.row_span.max(1) as usize).min(rows.end - r);
+ let cs = (cell.col_span.max(1) as usize).min(nc - c);
+ for rr in r..r + rs {
+ for cc in c..c + cs {
+ if let Some(slot) = covered.get_mut(rr * nc + cc) {
+ *slot = true;
+ }
+ }
+ }
+ let _ = write!(out, "<{cell_tag}");
+ if rs > 1 {
+ let _ = write!(out, " rowspan=\"{rs}\"");
+ }
+ if cs > 1 {
+ let _ = write!(out, " colspan=\"{cs}\"");
+ }
+ out.push('>');
- self.paragraphs(&cell.text, depth, "", out);
++ self.paragraphs(&cell.text, depth, "", None, object, out);
+ let _ = writeln!(out, "</{cell_tag}>");
+ }
+ out.push_str("</tr>\n");
+ }
+ let _ = writeln!(out, "</{group}>");
+ }
+ out.push_str("</table>\n");
}
- if let Some(l) = list {
- let _ = writeln!(out, "</{}>", l.split(' ').next().unwrap_or(l));
+ }
+
+ /// Run text with variables replaced by their values.
+ fn run_text(doc: &Document, raw: &str) -> String {
+ 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();
+ story_markup(&sub)
+ } else {
+ story_markup(raw)
}
- out
+ }
+
+ /// One story as XHTML: paragraphs, tables, and each footnote after the paragraph that refers to
-/// it. Endnote references link to the endnotes section that the full export ends with.
++/// it (anchored objects left out). Endnote references link to the endnotes section that the
++/// full export ends with.
+ pub fn story_html(doc: &Document, sid: StoryId) -> String {
- StoryWriter::new(doc, true).story(sid)
++ StoryWriter::new(doc, true).story(sid, None, &mut |_| String::new())
+}
+
+/// Where the EPUB body splits into chapter files: before each `h1`.
+const CHAPTER_MARK: &str = "<!--dc:chapter-->";
+
+/// The body split at its [`CHAPTER_MARK`]s into chapter bodies, each with its sections closed
+/// and the one a split goes through reopened in the next; a part with nothing but the start of a
+/// section (a story that opens with its `h1`) moves that start into the next part.
+fn split_chapters(body: &str) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ let mut carry: Option<String> = None;
+ for piece in body.split(CHAPTER_MARK) {
+ let mut part = carry.take().unwrap_or_default();
+ part.push_str(piece);
+ if let Some(open) = part.rfind("<section").filter(|i| !part[*i..].contains("</section>")) {
+ let tag_end = part[open..].find('>').map_or(part.len(), |e| open + e + 1);
+ if part[tag_end..].trim().is_empty() {
+ carry = Some(part[open..].to_string());
+ part.truncate(open);
+ } else {
+ part.push_str("</section>\n");
+ carry = Some("<section>\n".to_string());
+ }
+ }
+ if !part.trim().is_empty() {
+ out.push(part);
+ }
+ }
+ if let Some(rest) = carry.filter(|c| !c.trim().is_empty())
+ && let Some(last) = out.last_mut()
+ {
+ // Only an opening tag can be left over; close it where it stands.
+ last.push_str(&rest);
+ last.push_str("</section>\n");
+ }
+ if out.is_empty() {
+ out.push(String::new());
+ }
+ out
+}
+
+/// `chapter` (the file `own`) with each in-document link (`href="#id"`) to an element in another
+/// chapter file pointed at that file.
+fn link_across_chapters(chapter: &str, own: &str, files: &BTreeMap<String, String>) -> String {
+ const HREF: &str = "href=\"#";
+ let mut out = String::with_capacity(chapter.len());
+ let mut rest = chapter;
+ while let Some(i) = rest.find(HREF) {
+ out.push_str(rest.get(..i).unwrap_or_default());
+ let tail = rest.get(i + HREF.len()..).unwrap_or_default();
+ let id = tail.split('"').next().unwrap_or_default();
+ match files.get(id) {
+ Some(file) if file != own => {
+ let _ = write!(out, "href=\"{file}#");
+ }
+ _ => out.push_str(HREF),
+ }
+ rest = tail;
+ }
+ out.push_str(rest);
+ out
+}
+
+/// The package file of chapter `k` (0-based): `content.xhtml`, then `content2.xhtml`, ….
+fn chapter_file(k: usize) -> String {
+ if k == 0 { "content.xhtml".to_string() } else { format!("content{}.xhtml", k + 1) }
+}
+
+/// The level of a heading element (`h1` → 1 … `h6` → 6).
+fn heading_level(tag: &str) -> Option<u8> {
+ tag.strip_prefix('h').and_then(|n| n.parse::<u8>().ok()).filter(|n| (1..=6).contains(n))
+}
+
+/// Table of contents entries (target, label, level): the `h1`–`h3` paragraphs of the stories in
+/// reading order, or, in a document without headings, each story's first paragraph (level 1).
+fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, String, u8)> {
+ let pc = para_classes(&doc.styles);
+ let label = |t: &str| -> String { t.chars().filter(|c| !('\u{E000}'..='\u{E0FF}').contains(c)).take(80).collect::<String>().trim().to_string() };
+ let mut headings = Vec::new();
+ let mut firsts = Vec::new();
+ for (k, b) in order.iter().enumerate() {
+ let Block::Story(sid) = b else { continue };
+ let Some(st) = doc.story(*sid) else { continue };
+ let first = label(st.text.split('\n').next().unwrap_or(""));
+ if !first.is_empty() {
+ firsts.push((format!("s{k}"), first, 1));
+ }
+ for (pi, r) in st.para_ranges().iter().enumerate() {
+ let Some(pf) = st.paras.get(pi) else { continue };
+ let (tag, _) = export_mapping(&doc.styles, &pf.style, false, &pc);
+ let Some(level) = heading_level(tag).filter(|l| *l <= 3) else { continue };
+ let text = label(st.text.get(r.clone()).unwrap_or(""));
+ if !text.is_empty() {
+ headings.push((format!("s{k}-p{pi}"), text, level));
+ }
+ }
+ }
+ if headings.is_empty() { firsts } else { headings }
+}
+
+/// The table of contents as nested `li`/`ol` items (the content of the navigation's outer
+/// `ol`): a deeper level goes into the previous item, skipped levels count as one.
+fn nav_list(entries: &[(String, String, u8)], files: &BTreeMap<String, String>) -> String {
+ let mut out = String::new();
+ let mut open: Vec<u8> = Vec::new();
+ for (target, label, level) in entries {
+ let file = files.get(target).map_or("content.xhtml", String::as_str);
+ let item = format!("<li><a href=\"{file}#{target}\">{}</a>", xml_text(label));
+ match open.last().copied() {
+ None => open.push(*level),
+ Some(top) if *level > top => {
+ out.push_str("<ol>");
+ open.push(*level);
+ }
+ Some(_) => {
+ // Close the levels whose parent is as deep as this entry or deeper.
+ while open.len() > 1 && open.len().checked_sub(2).and_then(|i| open.get(i)).is_some_and(|parent| *parent >= *level) {
+ open.pop();
+ out.push_str("</li></ol>");
+ }
+ out.push_str("</li>");
+ if let Some(t) = open.last_mut() {
+ *t = (*t).min(*level);
+ }
+ }
+ }
+ out.push_str(&item);
+ }
+ for i in (0..open.len()).rev() {
+ out.push_str("</li>");
+ if i > 0 {
+ out.push_str("</ol>");
+ }
+ }
+ out
}
/// Reading order of document content: (page, y, x) of each story's first frame and of graphics.
@@@ -838,49 -781,73 +1074,53 @@@ fn graphic_html<'a>
#[allow(clippy::type_complexity)]
fn body_html<'a>(
doc: &'a Document,
- epub: bool,
img_src: &dyn Fn(&str, &str, &[u8]) -> String,
- heading_ids: bool,
-) -> (String, BTreeMap<String, (&'a str, &'a [u8])>, Vec<(String, String)>) {
++ epub: bool,
+) -> (String, BTreeMap<String, (&'a str, &'a [u8])>, Vec<(String, String, u8)>) {
let order = reading_order(doc);
+ let mut writer = StoryWriter::new(doc, epub);
let mut body = String::new();
let mut images: BTreeMap<String, (&str, &[u8])> = BTreeMap::new();
- let toc = toc_entries(doc, &order);
- let mut toc: Vec<(String, String)> = Vec::new();
++ let mut toc = toc_entries(doc, &order);
for (k, b) in order.iter().enumerate() {
match b {
+ // The endnote frame's text is generated from the endnotes, which end the body as a
+ // linked section instead.
+ Block::Story(sid) if doc.endnote_story == Some(*sid) => {}
Block::Story(sid) => {
let anchor = format!("s{k}");
- // First paragraph text as the TOC label.
- if let Some(st) = doc.story(*sid) {
- let first: String =
- st.text.split('\n').next().unwrap_or("").chars().filter(|c| !('\u{E000}'..='\u{E0FF}').contains(c)).take(60).collect();
- if !first.trim().is_empty() {
- toc.push((anchor.clone(), first));
- }
- }
- let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", writer.story(*sid));
- }
- Block::Image(iid) => {
- let Some(Content::Graphic(g)) = doc.item(*iid).map(|i| &i.content) else { continue };
- let Some(a) = doc.assets.get(&g.asset) else { continue };
- if a.data.is_empty() {
- continue;
- }
- let mime = safe_mime(&a.mime);
- // Video and sound: an HTML5 player (with the poster, when there is one).
- if let Some(kind) = designcraft_doc::media_kind(mime) {
- let name = format!("media/{}.{}", g.asset.0, ext(mime));
- images.insert(name.clone(), (mime, a.data.as_slice()));
- let m = doc.item(*iid).and_then(|i| i.media.clone()).unwrap_or_default();
- let mut attrs = String::new();
- for (on, attr) in
- [(m.controls, " controls=\"controls\""), (m.play_on_page_load, " autoplay=\"autoplay\""), (m.looping, " loop=\"loop\"")]
- {
- if on {
- attrs.push_str(attr);
+ // Anchored objects go where they are anchored: their graphics in the text, an
+ // above-line object as a block of its own.
+ let mut object = |o: &designcraft_doc::AnchoredObject| {
+ let mut out = String::new();
+ o.item.walk(&mut |it| {
+ if let Some((markup, _)) = graphic_html(doc, it, &mut images, img_src) {
+ out.push_str(&markup);
}
- }
- if let Some(pa) = m.poster.and_then(|p| doc.assets.get(&p)) {
- let poster_mime = safe_mime(&pa.mime);
- let pn = format!("images/{}.{}", pa.id.0, ext(poster_mime));
- images.insert(pn.clone(), (poster_mime, pa.data.as_slice()));
- if kind == "video" {
- attrs.push_str(&format!(" poster=\"{}\"", xml_attr(&img_src(&pn, poster_mime, &pa.data))));
+ });
+ match &o.position {
+ designcraft_doc::AnchorPosition::AboveLine { align, .. } if !out.is_empty() => {
+ let align = match align {
+ designcraft_doc::anchored::AnchorAlign::Left => "left",
+ designcraft_doc::anchored::AnchorAlign::Center => "center",
+ designcraft_doc::anchored::AnchorAlign::Right => "right",
+ };
+ format!("<span class=\"anchored\" style=\"display:block;text-align:{align}\">{out}</span>")
}
+ _ => out,
}
- let _ = writeln!(
- body,
- "<figure><{kind} src=\"{}\"{attrs}>{}</{kind}></figure>",
- xml_attr(&img_src(&name, mime, &a.data)),
- xml_text(&a.name)
- );
+ };
- let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", story_html_with(doc, *sid, heading_ids.then_some(anchor.as_str()), &mut object));
++ let _ = write!(body, "<section id=\"{anchor}\">\n{}</section>\n", writer.story(*sid, epub.then_some(anchor.as_str()), &mut object));
+ }
+ Block::Image(iid) => {
+ let Some(it) = doc.item(*iid) else { continue };
+ let Some((markup, media)) = graphic_html(doc, it, &mut images, img_src) else { continue };
+ if media {
+ let _ = writeln!(body, "<figure>{markup}</figure>");
continue;
}
- let name = format!("images/{}.{}", g.asset.0, ext(mime));
- images.insert(name.clone(), (mime, a.data.as_slice()));
- // Alt text from Object Export Options, else the file name.
- let alt = doc.item(*iid).map(|i| i.alt_text.as_str()).filter(|t| !t.is_empty()).unwrap_or(&a.name);
// Object Export Options: alignment and a page break before.
- let eo = doc.item(*iid).map(|i| i.export_options.clone()).unwrap_or_default();
+ let eo = &it.export_options;
let mut css = String::new();
if matches!(eo.align.as_str(), "left" | "center" | "right") {
css.push_str(&format!("text-align:{};", eo.align));
@@@ -893,6 -861,14 +1133,14 @@@
}
}
}
+ let endnotes = writer.endnotes_section();
+ if !endnotes.is_empty() {
+ let heading = &doc.endnote_options.heading;
+ if !heading.trim().is_empty() {
- toc.push(("endnotes".into(), heading.clone()));
++ toc.push(("endnotes".into(), heading.clone(), 1));
+ }
+ body.push_str(&endnotes);
+ }
(body, images, toc)
}