Skip to content

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

Merge #802: File › Open Recent: recent documents in the menu and on the start screen

aionggc6921a77cb1f
diff --cc ROADMAP.md
index b684216f0,9cf408a43..b7f2bb5e7
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -1,8 -1,8 +1,8 @@@
# DesignCraft roadmap
-**Stage: pre-alpha** · next: alpha, ~0% and ~15–25 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
+**Stage: pre-alpha** · next: alpha, ~5–7 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
- > **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (.indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent) · **Target:** Adobe InDesign 2026
++> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026
DesignCraft aims at full Adobe InDesign parity, and to be better: faster, open (documented JSON
format + IDML), scriptable by agents (MCP), and available on the web.
@@@ -128,83 -129,9 +128,84 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+ - **2026-10-13** · File ▸ Open Recent lists the documents last opened or saved (newest first, no duplicates; Save a Copy and exports don't count), with Clear Recent Files; the start screen shows the last eight, below the community card, as cards with a picture of the first page: saving puts one in the file (`preview.png`), so the start screen reads it without opening the document. A file that is gone is dimmed and says so when chosen, and stays listed. Preferences ▸ File Handling sets how many are kept (default 20, 0–100). `file.openRecent {index}`, `file.recentFiles`, `file.clearRecent` (#706). No readiness percentage change.
+- **2026-10-13** · Dropping an `.ase` file on the window loads its swatches, as Load Swatches does (the drop failed with "Can't Place the File"). No readiness percentage change.
+- **2026-10-13** · Text takes gradient swatches: a gradient fill or stroke on characters spans the text frame's box (on a path: the path's), on screen and in PDF. No readiness percentage change.
+- **2026-10-13** · Gradient swatches work on strokes: drawn across the path's box on screen and in PDF (they drew nothing), set with `object.gradient {target: stroke}` and in the Gradient panel when the Stroke box is in front; the stroke's gradient vector moves with the shape and round-trips through IDML. No readiness percentage change.
+- **2026-10-13** · The Gradient panel follows InDesign's layout (thumbnail, Type, Location, Angle, Reverse, ramp with midpoint diamonds) and takes swatches dragged from the Swatches panel: dropped on a stop they colour it, elsewhere they add a stop. Stops keep their CMYK through panel edits; `object.gradient` stops accept a `swatch`. No readiness percentage change.
+- **2026-10-13** · New Swatch works as InDesign's: a gradient made in the Gradient panel becomes "New Gradient Swatch" (still applied), an unnamed colour a listed swatch, a named swatch a "copy" (`swatch.new`); `swatch.create {gradient}` makes a gradient swatch from colour swatches. 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** · `.indd` and `.indt` documents open through File › Open, drop, the web inbox, `file.open`, `file.openBytes`, `file.openIdml` and the CLI: [storytold/indd-utils](https://github.com/storytold/indd-utils) converts them to IDML in memory and the IDML importer reads the result, on desktop and web. Converter warnings come first in the open result; an unreadable file is an open error (#21, #114). No readiness percentage change until a real-file corpus measures it.
+- **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** · 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** · PDF export leaves out form fields, buttons and video or sound that don't print: inside a hidden group, on a hidden or non-printing layer, or marked non-printing. Page content and interactive elements follow one inclusion rule. 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** · 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-13** · Word import: table cells read text by the same rules as body text, so deleted text, moved-away text and field codes stay out (#721). Word's Normal comes in as its own paragraph style "Normal" over the document defaults, so text formatted only by Normal keeps its look; it conflicts only with a document's own Normal, and the style map can send it to [Basic Paragraph] (#722). 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** · 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** · The Story Editor stays with the document its story belongs to: it hides while another document is active and closes with its document, so its edits never reach another document's story with the same id (#729). Undo restores the selection from before the command and Redo the one after it (#716). No readiness percentage change.
+- **2026-10-13** · Saving never reports success without a file: a document that can't be written is an error from Save, Save As, Save a Copy, Package, snippet export and the web serializer, leaving the existing file, the unsaved state and the recovery checkpoint as they were. Placed files over 4 GiB are written with zip64 sizes. A web Save whose browser download can't start reports the error and keeps the document unsaved (#741, #708). No readiness percentage change.
+- **2026-10-13** · Colour management runs on craft-libs' `craft-cms`. The default CMYK working space is its Coated FOGRA39 profile (Generic CMYK and Device CMYK stay selectable); CMYK swatches show relative colorimetric with the settings' black point compensation, and PDF/X-4 output intents embed the working CMYK profile (FOGRA39 by default). Profile names the built-in stands in for resolve to it; other unknown names are an error, and saved settings naming one start with the default. 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** · 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-12** · Placed Excel tables and Excel data-merge records keep numeric precision, including small values, and preserve numeric-looking cached formula strings as text. 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** · HTML and reflowable EPUB order grouped stories and graphics by their transformed spread position, including nested groups and rotated frames. Explicit Article order is unchanged. No readiness percentage change.
+- **2026-10-13** · A selected placed graphic shows its own brown bounding box with handles: dragging one resizes the graphic inside its frame (Shift keeps proportions, Alt from the centre) and leaves the frame as it is; `transform.set` takes the graphic's new spread `bounds`. Builds on #415 and #550. No readiness percentage change.
+- **2026-10-13** · Create Outlines makes one compound path per line (and per text colour within a line), grouped, as InDesign does: Ungroup then leaves each line on its own to be spaced and made into one compound path again. A single line in one colour stays a single compound path. No readiness percentage change.
+- **2026-10-13** · Ungroup only takes groups apart: a frame with pasted-in content stays whole (and selected), is named by its shape in the Layers and Properties panels, and offers Convert Shape rather than Ungroup. Non-groups stay selected. 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** · 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-12** · The engine's atomic writer, used by saves and exports (documents, snippets, books, libraries, swatches, XML, interchange, MCP, desktop and CLI writes), delegates to craft-libs/craft-atomic. Failed writes retain the original; new files follow the umask and replaced files keep their permissions. Recovery checkpoints and package output keep their own no-follow writers. No readiness percentage change.
+- **2026-10-13** · New Document has Preview (off by default, kept for the session): a document with the window's settings shows in the workspace and follows them once typing pauses. Create keeps it with a clean undo history and refuses invalid fields; Close removes it and shows the previous document again. The preview takes no Untitled number and writes no recovery data; one edited by a menu or script stays open as a document. No readiness percentage change.
+- **2026-10-13** · Object styles carry effects (drop shadow, feather, inner and outer shadows and glows, bevel, satin, gradient and directional feather). New styles from a selection keep its effects, `style.object.edit` changes a style's effects and every item that follows them, `style.object.clearOverrides` returns items to their style, and new frames take their default style's effects. IDML carries only the drop shadow and feather, for ObjectStyles (with their effects category and BasedOn chain) as for items (#653). No readiness percentage change.
+- **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change.
+- **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. No readiness percentage change.
+- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.
+- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.
+- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.
+- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.
+- **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.
+- **2026-10-12** · Text in oval, polygon and other non-rectangular text frames follows the frame's outline: each line is set in the part of its band inside the shape, one inset away from the outline, in every column and in vertical frames; text wrap still applies on top (#646). No readiness percentage change.
+- **2026-10-12** · Colour entry: the Color Picker's hex, R/G/B and C/M/Y/K fields and the Color panel's number fields keep typed text until it is complete; panel and picker values are applied on a fixed scale (`{model, …}` colours in 0..1), so M 1 is 1 %. Picking keeps a CMYK colour CMYK; dialogs leave the page behind them undimmed; colours that round to the same swatch name share one swatch (#323). No readiness percentage change.
+- **2026-10-12** · Placed photos show in their own colours: embedded ICC profiles (Adobe RGB, ProPhoto, P3, grey) are converted to sRGB on screen, and CMYK JPEGs (including YCCK), CMYK TIFFs and CMYK PSDs go through their embedded CMYK profile or the working CMYK space with the colour settings' intent and black-point compensation, instead of the profile-free formula. Unreadable profiles are ignored. 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** · 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** · Type tool: Option/Alt+Left/Right kerns the pair at the caret (manual kerning) or tracks a selection by the Kerning/Tracking increment (Preferences › Units & Increments, 20/1000 em), five times with Cmd/Ctrl; moving by words is Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere, and Option/Alt+Shift+Left/Right still selects by words (#621). No readiness percentage change.
+- **2026-10-12** · Autoflow on Place threads one frame per page column (right to left in a right-to-left story), so text no longer runs across the gutter; pages Smart Text Reflow adds get a primary frame with the page's columns (#625). No readiness percentage change.
+- **2026-10-12** · Vector art copied in Illustrator, VectorCraft, Figma or Inkscape pastes as editable paths, as InDesign pastes Illustrator art: the SVG those apps put on the clipboard becomes paths with their fills, strokes (weight, caps, joins, dashes) and opacity, groups stay groups and text comes in as outlines, centred in the view (`edit.pasteSvg`, `ui.paste`). Edit › Paste reads the system clipboard when nothing was copied in DesignCraft. No readiness percentage change.
+- **2026-10-12** · Pages panel: double-clicking a parent shows that parent and selects only its row; parent rows show rendered thumbnails. Commands name parents by id, full name, or a prefix only one parent has; an unknown or ambiguous name is an error instead of clearing the page's parent (#624). No readiness percentage change.
+- **2026-10-12** · With the Type tool, dragging a table's column or row border resizes it (the double-arrow cursor shows over a border): later columns and rows move along, Shift keeps the table size, and Shift on the right or bottom edge scales every column or row. A dragged row becomes At Least; one undo step per drag, Esc cancels; works in rotated frames and turned spreads. Scripts use `table.resizeBorder`. No readiness percentage change.
+- **2026-10-12** · The Tools panel's Fill/Stroke keys work: D (default fill and stroke), X (fill or stroke in front), Shift+X (swap per object, tints included) and / (Apply None), as `color.*` commands; swap and default are one undo step (`object.swapFillStroke`, `object.defaultFillStroke`); the Color panel follows the proxy's fill/stroke choice. No readiness percentage change.
+- **2026-10-12** · With a placed graphic selected (Direct Selection), the Transform values act on the graphic inside its frame, as in InDesign: a tilted frame's image can be straightened to 0°. No readiness percentage change.
+- **2026-10-11** · Font menu laid out like InDesign's: filters (classification, favourites,
+ recently added), families opening to their styles, the selected text as the sample in three
+ sizes, Recently Used fonts, Show Similar Fonts and each font's format.
+- **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.
+- **2026-10-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.
+- **2026-10-12** · Load Styles: the Paragraph Styles and Character Styles panels load styles from another DesignCraft document or an IDML file, with the styles, swatches and lists they name; a dialog picks the styles and what happens to one the document defines differently (`style.load`). No readiness percentage change.
+- **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. 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-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.
+- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.
+- **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.
+- **2026-10-12** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.
+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.
+- **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change.
+- **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.
+- **2026-10-12** · Text frame auto-size: Height Only, Width Only, Height and Width (also keeping proportions) frames grow and shrink to fit their text after edits, around their reference point, with minimum sizes and No Line Breaks, in the same undo step (#180). No readiness percentage change.
+- **2026-10-12** · Text Frame Options › Balance Columns (`object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`) evens out the columns of the frame a story ends in, from its last column break on; frames the text runs on from fill normally (#609). 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** · 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** · Windows: dragging the window across monitors with different display scales keeps its size instead of growing until it crashes (winit pinned to its 0.30.x backport of the fix). The GPU surface may be as large as the adapter's largest texture (16384 px on DirectX 12, Vulkan and Metal hardware) instead of 8192, and a wgpu error is logged instead of closing the app. 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.
- **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.
diff --cc apps/designcraft/src/native_menu.rs
index 88f7be5c3,40e06e405..3ab86d3fc
--- a/apps/designcraft/src/native_menu.rs
+++ b/apps/designcraft/src/native_menu.rs
@@@ -20,11 -19,17 +20,21 @@@ enum Handle
pub struct NativeMenu {
_menu: Menu,
items: HashMap<String, (String, Value, Handle)>,
+ events: Receiver<MenuEvent>,
last_refresh: f64,
+ /// The interface language the titles are in and whether CJK features are shown: the menu is
+ /// rebuilt when either changes.
+ shown_for: (String, bool),
+ /// File › Open Recent, rebuilt when the list of recent files changes.
+ recent: Option<RecentMenu>,
+ }
+
+ struct RecentMenu {
+ submenu: Submenu,
+ /// The files shown, and the native items standing for them (with their trailing separator).
+ shown: Vec<String>,
+ ids: Vec<String>,
+ separator: Option<PredefinedMenuItem>,
}
/// Accelerator for "Cmd+Shift+]" (modifier-less shortcuts stay in the app so typing works).
@@@ -53,29 -45,33 +63,30 @@@ impl NativeMenu
let menu = Menu::new();
let mut items = HashMap::new();
let mut counter = 0usize;
+ let mut recent = None;
- // Application menu.
+ // Application menu: our own About splash (with the community links) instead of the stock
+ // panel, and Settings… (Edit › Preferences… on the other platforms).
let app_menu = Submenu::new("DesignCraft", true);
- // Our own About splash (with the community links) instead of the stock panel.
- let about = MenuItem::with_id("dc-about", "About DesignCraft", true, None);
- let discord = MenuItem::with_id("dc-discord", "Join the ArtCraft Discord…", true, None);
- // Not the predefined Quit: it terminates the app at once, past the unsaved-changes prompt.
- let quit = MenuItem::with_id("dc-quit", designcraft_ui_egui::i18n::tr(&app.ui.language, "Quit DesignCraft"), true, accel("Cmd+Q"));
- let _ = app_menu.append_items(&[
- &about,
- &discord,
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::services(None),
- &PredefinedMenuItem::separator(),
- &PredefinedMenuItem::hide(None),
- &PredefinedMenuItem::hide_others(None),
- &PredefinedMenuItem::show_all(None),
- &PredefinedMenuItem::separator(),
- &quit,
- ]);
- items.insert("dc-about".into(), ("help.about".into(), serde_json::Value::Null, Handle::Plain(about)));
- items.insert("dc-discord".into(), ("help.discord".into(), serde_json::Value::Null, Handle::Plain(discord)));
- items.insert("dc-quit".into(), ("app.quit".into(), serde_json::Value::Null, Handle::Plain(quit)));
+ for entry in menus::MAC_APP_MENU {
+ let _ = match *entry {
+ AppMenuItem::Cmd { id, label, command } => {
+ let sc = shortcut(command).and_then(accel);
+ let item = MenuItem::with_id(id, designcraft_ui_egui::i18n::tr(&app.ui.language, label), true, sc);
+ let appended = app_menu.append(&item);
+ items.insert(id.into(), (command.into(), Value::Null, Handle::Plain(item)));
+ appended
+ }
+ AppMenuItem::Sep => app_menu.append(&PredefinedMenuItem::separator()),
+ AppMenuItem::Services => app_menu.append(&PredefinedMenuItem::services(None)),
+ AppMenuItem::Hide => app_menu.append(&PredefinedMenuItem::hide(None)),
+ AppMenuItem::HideOthers => app_menu.append(&PredefinedMenuItem::hide_others(None)),
+ AppMenuItem::ShowAll => app_menu.append(&PredefinedMenuItem::show_all(None)),
+ };
+ }
let _ = menu.append(&app_menu);
- for (title, entries) in menus::menu_tree() {
+ for (title, entries) in menus::native_menu_tree() {
let sub = Submenu::new(designcraft_ui_egui::i18n::tr(&app.ui.language, title), true);
- build(app, &sub, &entries, &mut items, &mut counter);
+ build(app, &sub, &entries, &mut items, &mut counter, title, &mut recent);
let _ = menu.append(&sub);
}
menu.init_for_nsapp();
@@@ -87,7 -83,44 +98,51 @@@
(p.is_null() && accel(sc).is_some()).then(|| id.clone())
})
.collect();
- Self { _menu: menu, items, events, last_refresh: 0.0, shown_for: (app.ui.language.clone(), designcraft_ui_egui::cjk_features(app)) }
+ let recent = recent.map(|submenu| RecentMenu { submenu, shown: Vec::new(), ids: Vec::new(), separator: None });
- Self { _menu: menu, items, last_refresh: 0.0, recent }
++ Self {
++ _menu: menu,
++ items,
++ events,
++ last_refresh: 0.0,
++ shown_for: (app.ui.language.clone(), designcraft_ui_egui::cjk_features(app)),
++ recent,
++ }
+ }
+
+ /// Put the current recent files at the top of File › Open Recent when they changed.
+ fn refresh_recent(&mut self, app: &DesignApp) {
+ let Some(r) = self.recent.as_mut() else { return };
+ if r.shown == app.session.prefs.recent_files {
+ return;
+ }
+ for id in r.ids.drain(..) {
+ if let Some((_, _, Handle::Plain(item))) = self.items.remove(&id) {
+ let _ = r.submenu.remove(&item);
+ }
+ }
+ if let Some(sep) = r.separator.take() {
+ let _ = r.submenu.remove(&sep);
+ }
+ let mut position = 0;
+ for it in menus::recent_items(app) {
+ match it {
+ Item::Cmd { label, id, params, .. } => {
+ let mid = format!("dc-recent{position}");
+ let item = MenuItem::with_id(mid.clone(), label, true, None);
+ let _ = r.submenu.insert(&item, position);
+ self.items.insert(mid.clone(), (id, params, Handle::Plain(item)));
+ r.ids.push(mid);
+ }
+ Item::Sep => {
+ let sep = PredefinedMenuItem::separator();
+ let _ = r.submenu.insert(&sep, position);
+ r.separator = Some(sep);
+ }
+ Item::Sub(..) => continue,
+ }
+ position += 1;
+ }
+ r.shown = app.session.prefs.recent_files.clone();
}
pub fn poll(&mut self, app: &mut DesignApp, ctx: &egui::Context) {
@@@ -128,11 -164,13 +192,15 @@@ fn build
}
Item::Sub(label, children) => {
let sub = Submenu::new(designcraft_ui_egui::i18n::tr(&app.ui.language, label), true);
- build(app, &sub, children, items, counter);
+ let path = format!("{path}/{label}");
+ build(app, &sub, children, items, counter, &path, recent);
+ if path == menus::OPEN_RECENT {
+ *recent = Some(sub.clone());
+ }
let _ = parent.append(&sub);
}
+ // Hidden CJK commands; `NativeMenu::poll` rebuilds the bar when Show CJK Features changes.
+ Item::Cmd { id, .. } if !menus::shown(app, id) => {}
Item::Cmd { label, id, params, shortcut } => {
*counter += 1;
let mid = format!("dc{counter}");
diff --cc crates/engine/src/cmd/file.rs
index d655b2065,4c9e7e36b..f9c620c83
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -13,43 -13,31 +13,53 @@@ use crate::{DocState, EngineError, Resu
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"),
- "{preset?: \"Letter\"|\"A4\"|…, width?, height?, pages?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, title?}",
+ "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?}",
always, file_new),
cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample),
- cmd!(query "file.presets", "Document Presets", [], None, "{}", always, |_, _| Ok(serde_json::to_value(PRESETS).unwrap_or_default())),
+ cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true`)", always, |s, _| {
+ let mut presets: Vec<Value> = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect();
+ presets.extend(
+ s.prefs
+ .document_presets
+ .iter()
+ .map(|p| json!({"name": p.title, "intent": p.intent, "width": p.width, "height": p.height, "units": p.units, "saved": true})),
+ );
+ Ok(Value::Array(presets))
+ }),
+ cmd!(noundo "file.savePreset", "Save Document Preset", [], None,
+ "{name, …the settings file.new takes} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused",
+ always, save_preset),
+ cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| {
+ let name = str_param(p, "name").unwrap_or_default().trim().to_string();
+ let before = s.prefs.document_presets.len();
+ s.prefs.document_presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));
+ if s.prefs.document_presets.len() == before {
+ return Err(bad("file.deletePreset", format!("no saved preset `{name}`")));
+ }
+ ok()
+ }),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),
- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped (and, for .idml, package parts missing)}",
+ "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing}",
always, file_open),
- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package", always, file_open_bytes),
+ cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt → {index, warnings}", always, file_open_bytes),
+ cmd!(noundo "file.openRecent", "Open Recent File", [], None,
+ "{index} — reopen entry `index` of File › Open Recent (as file.open); a file that is gone is an error and stays listed",
+ has_recent, file_open_recent),
+ cmd!(query "file.recentFiles", "Recent Files", [], None, "{} → [{path, name, exists}] File › Open Recent, most recent first", always, |s, _| {
+ Ok(Value::Array(s.prefs.recent_files.iter().map(|p| recent_entry(p)).collect()))
+ }),
+ cmd!(noundo "file.clearRecent", "Clear Recent Files", ["File", "Open Recent"], None, "{} — empty File › Open Recent", has_recent, |s, _| {
+ s.prefs.recent_files.clear();
+ ok()
+ }),
- cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?}", has_doc, file_save),
- cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, file_save),
- cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state", has_doc, |s, p| {
- let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?.to_string();
+ cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),
+ cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),
+ cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, |s, p| {
+ let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?;
+ let path = with_document_extension(path);
let mut copy = (*s.doc()?.doc).clone();
super::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path));
- let bytes = to_bytes(&copy)?;
+ let bytes = to_bytes_with_preview(&copy, &s.cache);
#[cfg(not(target_arch = "wasm32"))]
crate::atomic::write_file(&path, &bytes)?;
Ok(json!({"path": path, "bytes": bytes.len()}))
@@@ -131,193 -119,35 +141,209 @@@
]
}
-pub fn to_bytes(d: &Document) -> Vec<u8> {
- designcraft_format::save(d).unwrap_or_default()
+#[cfg(test)]
+thread_local! {
+ /// Makes [`to_bytes`] fail on this thread, standing in for writer errors that need gigabytes to reach.
+ pub(crate) static FAIL_TO_BYTES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// The document as `.designcraft` bytes, or an error when it can't be written; never an empty file.
+pub fn to_bytes(d: &Document) -> Result<Vec<u8>> {
+ #[cfg(test)]
+ if FAIL_TO_BYTES.with(std::cell::Cell::get) {
+ return Err(EngineError::Other("could not write the document: injected failure".into()));
+ }
+ designcraft_format::save(d).map_err(|e| EngineError::Other(format!("could not write the document: {e}")))
+}
+
+/// `path` ending in `.designcraft`: the extension is added when it is missing or another one, so
+/// the file opens from the file manager. A path without a file name is left for the write to fail.
+pub fn with_document_extension(path: &str) -> String {
+ let p = std::path::Path::new(path);
+ let ext = p.extension().and_then(|e| e.to_str());
+ if p.file_name().is_none() || ext.is_some_and(|e| e.eq_ignore_ascii_case(designcraft_format::EXTENSION)) {
+ return path.to_string();
+ }
+ format!("{path}.{}", designcraft_format::EXTENSION)
+}
+
+/// Whether `bytes` are a document `file.open` reads: a DesignCraft package or an IDML package.
+pub fn is_document(bytes: &[u8]) -> bool {
+ designcraft_idml::is_idml(bytes) || designcraft_format::is_designcraft(bytes)
}
+ /// The longer side of the first-page picture saved in the file, in pixels.
+ const PREVIEW_PX: f64 = 320.0;
+
+ /// [`to_bytes`] with a picture of the first page, which the start screen shows next to the file
+ /// in its recent files. A page that can't be drawn just leaves the picture out.
+ fn to_bytes_with_preview(d: &Document, cache: &crate::Cache) -> Vec<u8> {
+ let preview = d.page_loc(0).and_then(|(si, pi)| {
+ let b = d.spreads.get(si)?.pages.get(pi)?.bounds();
+ let side = b.width().max(b.height());
+ (side.is_finite() && side > 0.0).then_some(PREVIEW_PX / side)
+ });
+ let png =
+ preview.and_then(|scale| designcraft_render::Renderer::new().render_page(d, cache, 0, scale, false, &Default::default())).map(|r| r.to_png());
+ designcraft_format::save_with_preview(d, png.as_deref()).unwrap_or_default()
+ }
+
pub fn from_bytes(b: &[u8]) -> Result<Document> {
- designcraft_format::load(b).map_err(|e| EngineError::Other(e.to_string()))
+ load_bytes(b).map(|(d, _)| d)
}
-fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
+/// Read `.designcraft` bytes and repair what a hand-edited file can get wrong without failing the
+/// open, with a warning for each repair.
+fn load_bytes(b: &[u8]) -> Result<(Document, Vec<String>)> {
+ let mut d = designcraft_format::load(b).map_err(|e| EngineError::Other(e.to_string()))?;
+ let warnings = d.fix_parent_bases();
+ Ok((d, warnings))
+}
+
+/// The longest saved preset name, and how many presets are kept.
+const MAX_PRESET_NAME: usize = 100;
+const MAX_PRESETS: usize = 500;
+
+/// A built-in document preset or a saved one, by name (case ignored).
+fn find_preset(s: &Session, name: &str) -> Option<NewDocument> {
+ NewDocument::from_preset(name).or_else(|| s.prefs.document_presets.iter().find(|p| p.title.eq_ignore_ascii_case(name.trim())).cloned())
+}
+
+/// The settings `file.new` makes a document with for `p`: its preset, then the settings over it.
+fn new_document_settings(s: &Session, p: &Value) -> Result<NewDocument> {
let mut nd = match str_param(p, "preset") {
- Some(name) => NewDocument::from_preset(name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?,
+ Some(name) => find_preset(s, name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?,
None => NewDocument::default(),
};
+ apply_settings(&mut nd, p);
+ check_size("file.new", &nd)?;
+ Ok(nd)
+}
+
+fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut nd = new_document_settings(s, p)?;
+ s.untitled += 1;
+ nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| format!("Untitled-{}", s.untitled));
+ let d = Document::new(&nd);
+ let i = s.add_document(DocState::new(d, None));
+ Ok(json!({"index": i}))
+}
+
+impl Session {
+ /// New Document's Preview: a document made as `file.new` would make it with `p`, shown while
+ /// the New Document window is open. It replaces the previous preview document in its tab and
+ /// takes no Untitled number, no undo step and no recovery entry. Settings `file.new` refuses
+ /// leave the previous preview as it was. Returns the preview document's uid.
+ pub fn preview_new_document(&mut self, p: &Value) -> Result<u64> {
+ let mut nd = new_document_settings(self, p)?;
+ let previous = match self.new_document_preview {
+ Some((_, previous)) => previous,
+ None => self.active().map(|d| d.uid),
+ };
+ let shown = self.new_document_preview.and_then(|(old, _)| self.docs.iter().position(|d| d.uid == old));
+ // A preview edited or saved by a menu or script while the window is open has become a
+ // document of its own: it stays, and the preview gets a tab of its own.
+ let replace = shown.filter(|&i| self.docs.get(i).is_some_and(|d| !d.is_dirty() && d.path.is_none()));
+ if replace.is_none() && shown.is_some() {
+ self.untitled += 1;
+ }
+ nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| self.next_untitled_title());
+ let st = DocState::new(Document::new(&nd), None);
+ let uid = st.uid;
+ match replace.and_then(|i| self.docs.get_mut(i).map(|d| (i, d))) {
+ Some((i, d)) => {
+ *d = st;
+ self.active = Some(i);
+ }
+ None => {
+ // Pushed without `add_document`: the document that was active stays as it is.
+ self.docs.push(st);
+ self.active = Some(self.docs.len() - 1);
+ }
+ }
+ self.new_document_preview = Some((uid, previous));
+ Ok(uid)
+ }
+
+ /// The uid of New Document's preview document, while one is shown.
+ pub fn new_document_preview(&self) -> Option<u64> {
+ self.new_document_preview.map(|(uid, _)| uid)
+ }
+
+ /// End New Document's preview. Its document goes, and if it was still the active document,
+ /// the one that was active before it is active again. A preview that a menu or script has
+ /// edited or saved stays open as a document, with an Untitled number. Returns the uid of the
+ /// document removed. Without a preview it does nothing.
+ pub fn end_new_document_preview(&mut self) -> Option<u64> {
+ let (uid, previous) = self.new_document_preview.take()?;
+ let i = self.docs.iter().position(|d| d.uid == uid)?;
+ let d = self.docs.get(i)?;
+ if d.is_dirty() || d.path.is_some() {
+ self.untitled += 1;
+ return None;
+ }
+ self.docs.remove(i);
+ self.active = match self.active {
+ Some(a) if a == i => previous.and_then(|p| self.docs.iter().position(|d| d.uid == p)).or_else(|| self.docs.len().checked_sub(1)),
+ Some(a) if a > i => Some(a - 1),
+ a => a,
+ };
+ Some(uid)
+ }
+
+ /// Create in the New Document window, with the settings the preview shows: the preview
+ /// document becomes the new document, as `file.new` would make it (the next Untitled number,
+ /// no undo history). Returns its index, or `None` when there is no unedited preview to keep.
+ pub fn keep_new_document_preview(&mut self) -> Option<usize> {
+ let (uid, _) = self.new_document_preview?;
+ let i = self.docs.iter().position(|d| d.uid == uid && !d.is_dirty() && d.path.is_none())?;
+ self.new_document_preview = None;
+ self.untitled += 1;
+ if let Some(d) = self.docs.get_mut(i) {
+ d.history.undo.clear();
+ d.history.redo.clear();
+ }
+ self.active = Some(i);
+ Some(i)
+ }
+}
+
+fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("file.savePreset", "missing `name`"))?.to_string();
+ if name.chars().count() > MAX_PRESET_NAME {
+ return Err(bad("file.savePreset", format!("a preset name has at most {MAX_PRESET_NAME} characters")));
+ }
+ if NewDocument::from_preset(&name).is_some() {
+ return Err(bad("file.savePreset", format!("`{name}` is a built-in preset")));
+ }
+ let mut nd = NewDocument::default();
+ apply_settings(&mut nd, p);
+ check_size("file.savePreset", &nd)?;
+ nd.title = name.clone();
+ let presets = &mut s.prefs.document_presets;
+ presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));
+ if presets.len() >= MAX_PRESETS {
+ return Err(bad("file.savePreset", format!("at most {MAX_PRESETS} saved presets")));
+ }
+ presets.push(nd);
+ Ok(json!({"name": name}))
+}
+
+fn check_size(cmd: &str, nd: &NewDocument) -> Result<()> {
+ if !(nd.width > 0.0 && nd.height > 0.0 && nd.width <= 15552.0 && nd.height <= 15552.0) {
+ return Err(bad(cmd, "page size out of range (0 < size ≤ 216 in)"));
+ }
+ Ok(())
+}
+
+/// The document settings in `p` (as file.new takes them) over `nd`.
+fn apply_settings(nd: &mut NewDocument, p: &Value) {
+ if let Some(intent) = p.get("intent").and_then(|v| serde_json::from_value(v.clone()).ok()) {
+ nd.intent = intent;
+ }
+ if let Some(units) = p.get("units").and_then(|v| serde_json::from_value(v.clone()).ok()) {
+ nd.units = units;
+ }
nd.width = f64_or(p, "width", nd.width);
nd.height = f64_or(p, "height", nd.height);
nd.pages = p.get("pages").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(nd.pages).clamp(1, 9999);
@@@ -459,12 -334,13 +549,13 @@@ fn file_save(s: &mut Session, p: &Value
super::datamerge::refresh_relative_paths(&mut saved, std::path::Path::new(&path));
let paths_changed = saved.data_merge != st.doc.data_merge;
let saved = if paths_changed { Arc::new(saved) } else { st.doc.clone() };
- let bytes = to_bytes(&saved)?;
+ let bytes = to_bytes_with_preview(&saved, &s.cache);
#[cfg(not(target_arch = "wasm32"))]
crate::atomic::write_file(&path, &bytes)?;
+ let st = s.doc_mut()?;
if paths_changed {
st.doc = saved;
- st.revision = st.revision.saturating_add(1);
+ st.bump_revision();
}
st.path = Some(path.clone());
st.saved_revision = st.revision;
@@@ -1716,81 -1081,118 +1808,195 @@@ mod document_fonts_tests
assert!(glyph_faces(&s).iter().all(|(_, f)| f.family == FAMILY));
let _ = std::fs::remove_dir_all(&dir);
}
+
+ #[test]
+ fn bold_and_italic_link_the_document_fonts_styles() {
+ const FAMILY: &str = "DocFont Linked";
+ let dir = temp_dir("linked");
+ std::fs::write(dir.join(DOCUMENT_FONTS_FOLDER).join("linked.ttf"), font_with(FAMILY, &['H', 'e', 'l', 'o']).unwrap()).unwrap();
+ let path = dir.join("Linked.designcraft");
+ write_document(&path, FAMILY);
+
+ let mut s = Session::new();
+ open(&mut s, &path);
+ let sid = *s.doc().unwrap().doc.stories.keys().next().unwrap();
+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
+ // The family is the document's alone: its Regular is the style without bold or italic.
+ let r = s.execute("type.bold", &json!({"on": false})).unwrap();
+ assert_eq!(r["fontStyle"], "Regular", "{r}");
+ let r = s.execute("type.italic", &json!({"on": false})).unwrap();
+ assert_eq!(r["fontStyle"], "Regular", "{r}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod extension_tests {
+ use serde_json::json;
+
+ use super::{is_document, with_document_extension};
+ use crate::Session;
+
+ #[test]
+ fn the_document_extension_is_added_when_missing_or_different() {
+ assert_eq!(with_document_extension("/a/Brochure"), "/a/Brochure.designcraft");
+ assert_eq!(with_document_extension("/a/Brochure.idml"), "/a/Brochure.idml.designcraft");
+ assert_eq!(with_document_extension("/a/v1.2 Brochure"), "/a/v1.2 Brochure.designcraft");
+ assert_eq!(with_document_extension("/a/Brochure.DesignCraft"), "/a/Brochure.DesignCraft");
+ assert_eq!(with_document_extension("/a/.."), "/a/..");
+ }
+
+ #[test]
+ fn save_adds_the_extension_and_open_recognises_files_by_content() {
+ let dir = std::env::temp_dir().join(format!("dc-file-extension-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+
+ let bare = dir.join("Brochure");
+ let written = dir.join("Brochure.designcraft");
+ let r = s.execute("file.saveAs", &json!({"path": bare.to_string_lossy()})).unwrap();
+ assert_eq!(r["path"], json!(written.to_string_lossy()), "{r}");
+ assert!(written.is_file() && !bare.exists());
+ assert_eq!(s.doc().unwrap().path.as_deref(), written.to_str());
+ let r = s.execute("file.saveACopy", &json!({"path": dir.join("Copy").to_string_lossy()})).unwrap();
+ assert_eq!(r["path"], json!(dir.join("Copy.designcraft").to_string_lossy()), "{r}");
+
+ // A native file without the extension opens, and Save writes back to that same file.
+ std::fs::rename(&written, &bare).unwrap();
+ let mut t = Session::new();
+ t.execute("file.open", &json!({"path": bare.to_string_lossy()})).unwrap();
+ let r = t.execute("file.save", &json!({})).unwrap();
+ assert_eq!(r["path"], json!(bare.to_string_lossy()), "{r}");
+ assert!(!written.exists());
+
+ // An IDML package without the extension opens as IDML, unsaved.
+ let idml = dir.join("Package");
+ std::fs::write(&idml, designcraft_idml::export_idml(&s.doc().unwrap().doc)).unwrap();
+ assert!(is_document(&std::fs::read(&idml).unwrap()) && is_document(&std::fs::read(&bare).unwrap()));
+ t.execute("file.open", &json!({"path": idml.to_string_lossy()})).unwrap();
+ assert_eq!(t.doc().unwrap().path, None);
+
+ let notes = dir.join("Notes");
+ std::fs::write(&notes, b"plain text").unwrap();
+ assert!(!is_document(b"plain text"));
+ let e = t.execute("file.open", &json!({"path": notes.to_string_lossy()})).unwrap_err();
+ assert!(e.to_string().contains("not a DesignCraft or IDML file"), "{e}");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
+
+ #[cfg(test)]
+ mod recent_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ fn temp_dir(name: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("dc-recent-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn saved(s: &mut Session, path: &std::path::Path) -> String {
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap();
+ path.to_string_lossy().to_string()
+ }
+
+ /// Opening and saving put a file at the front once; Save a Copy doesn't count.
+ #[test]
+ fn open_and_save_order_the_list_without_duplicates() {
+ let dir = temp_dir("order");
+ let mut s = Session::new();
+ let a = saved(&mut s, &dir.join("a.designcraft"));
+ let b = saved(&mut s, &dir.join("b.designcraft"));
+ assert_eq!(s.prefs.recent_files, [b.clone(), a.clone()]);
+ s.execute("file.open", &json!({"path": a})).unwrap();
+ assert_eq!(s.prefs.recent_files, [a.clone(), b.clone()], "reopening moves it to the front, once");
+ s.execute("file.saveACopy", &json!({"path": dir.join("copy.designcraft").to_string_lossy()})).unwrap();
+ assert_eq!(s.prefs.recent_files, [a.clone(), b.clone()], "a copy isn't a recent file");
+ let rows = s.execute("file.recentFiles", &json!({})).unwrap();
+ assert_eq!(rows[0], json!({"path": a, "name": "a.designcraft", "exists": true}));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn open_recent_reopens_and_a_missing_file_is_an_error_that_keeps_it_listed() {
+ let dir = temp_dir("open");
+ let mut s = Session::new();
+ let a = saved(&mut s, &dir.join("a.designcraft"));
+ let b = saved(&mut s, &dir.join("b.designcraft"));
+ let r = s.execute("file.openRecent", &json!({"index": 1})).unwrap();
+ assert_eq!(s.documents()[r["index"].as_u64().unwrap() as usize].path.as_deref(), Some(a.as_str()));
+ assert_eq!(s.prefs.recent_files, [a.clone(), b.clone()]);
+ std::fs::remove_file(&b).unwrap();
+ let e = s.execute("file.openRecent", &json!({"index": 1})).unwrap_err();
+ assert!(e.to_string().contains("can't be found"), "{e}");
+ assert_eq!(s.prefs.recent_files, [a.clone(), b.clone()], "a disk that isn't connected comes back");
+ assert_eq!(s.execute("file.recentFiles", &json!({})).unwrap()[1]["exists"], false);
+ // Hostile indices are errors, never panics.
+ for index in [json!(2), json!(u64::MAX), json!(-1), json!("0"), json!(null)] {
+ assert!(s.execute("file.openRecent", &json!({"index": index})).is_err(), "{index}");
+ }
+ s.execute("file.clearRecent", &json!({})).unwrap();
+ assert!(s.prefs.recent_files.is_empty());
+ assert!(s.execute("file.openRecent", &json!({"index": 0})).is_err(), "disabled when empty");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// Saving puts a small picture of the first page in the file, which the start screen reads
+ /// without opening the document.
+ #[test]
+ fn saved_files_carry_a_first_page_preview() {
+ let dir = temp_dir("preview");
+ let mut s = Session::new();
+ let a = saved(&mut s, &dir.join("a.designcraft"));
+ let p = super::recent_preview(&a).expect("a preview");
+ assert_eq!(p.width.max(p.height), super::PREVIEW_PX as u32);
+ assert_eq!(p.rgba.len(), (p.width * p.height * 4) as usize);
+ assert!(p.rgba.as_chunks::<4>().0.iter().any(|px| px[3] == 255), "the page is drawn, not left transparent");
+ let copy = dir.join("copy.designcraft");
+ s.execute("file.saveACopy", &json!({"path": copy.to_string_lossy()})).unwrap();
+ assert!(super::recent_preview(&copy.to_string_lossy()).is_some(), "Save a Copy has one too");
+ // Files without one (saved before previews), missing files and other files have none.
+ let old = dir.join("old.designcraft");
- std::fs::write(&old, super::to_bytes(&s.doc().unwrap().doc)).unwrap();
++ std::fs::write(&old, super::to_bytes(&s.doc().unwrap().doc).unwrap()).unwrap();
+ for path in [old, dir.join("gone.designcraft"), dir.clone()] {
+ assert!(super::recent_preview(&path.to_string_lossy()).is_none(), "{path:?}");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn the_list_keeps_at_most_the_preferred_count() {
+ let mut s = Session::new();
+ for i in 0..30 {
+ s.prefs.note_recent_file(&format!("/work/{i}.designcraft"));
+ }
+ assert_eq!(s.prefs.recent_files.len(), 20, "default: 20");
+ assert_eq!(s.prefs.recent_files[0], "/work/29.designcraft");
+ s.execute("prefs.set", &json!({"recentFilesMax": 3})).unwrap();
+ assert_eq!(s.prefs.recent_files, ["/work/29.designcraft", "/work/28.designcraft", "/work/27.designcraft"]);
+ assert_eq!(s.execute("prefs.set", &json!({"recentFilesMax": 4_000_000_000u64})).unwrap()["recentFilesMax"], crate::MAX_RECENT_FILES);
+ assert!(s.execute("prefs.set", &json!({"recentFilesMax": -1})).is_err());
+ s.execute("prefs.set", &json!({"recentFilesMax": 0})).unwrap();
+ s.prefs.note_recent_file("/work/new.designcraft");
+ assert!(s.prefs.recent_files.is_empty(), "0 keeps no list");
+ }
+
+ /// The list is a preference: it survives the round trip through prefs.json.
+ #[test]
+ fn the_list_survives_a_restart() {
+ let mut s = Session::new();
+ s.prefs.note_recent_file("/work/a.designcraft");
+ let saved = serde_json::to_vec(&s.prefs).unwrap();
+ let back: crate::Prefs = serde_json::from_slice(&saved).unwrap();
+ assert_eq!(back.recent_files, ["/work/a.designcraft"]);
+ assert_eq!(back.recent_files_max, 20);
+ let old: crate::Prefs = serde_json::from_slice(br#"{"recoveryMinutes": 2.0}"#).unwrap();
+ assert!(old.recent_files.is_empty(), "older prefs.json without the list still load");
+ }
+ }
diff --cc crates/engine/src/cmd/mod.rs
index e5cc5d327,80fc298f1..59b97c273
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@@ -328,7 -310,5 +328,7 @@@ pub fn file_from(b: &[u8]) -> Result<de
}
pub(crate) use datamerge::sync_placeholders;
pub(crate) use file::load_document_fonts;
- pub use file::{base64_decode, base64_encode, from_bytes, is_document, to_bytes, with_document_extension};
-pub use file::{RecentPreview, base64_decode, base64_encode, from_bytes, recent_preview, to_bytes};
++pub use file::{RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension};
+pub use layout::chapter_numbering;
+pub use paste_svg::is_svg_markup;
pub(crate) use place_text::autoflow as place_text_autoflow;
diff --cc crates/engine/src/cmd/package.rs
index 847f83c9d,8587db47a..e29373b17
--- a/crates/engine/src/cmd/package.rs
+++ b/crates/engine/src/cmd/package.rs
@@@ -642,7 -590,10 +642,10 @@@ mod tests
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": text.len()})).unwrap();
s.execute("type.char", &json!({"fontFamily": NAMED, "fontStyle": "Regular"})).unwrap();
let src = dir.join("src").join("Fallback.designcraft");
- s.execute("file.save", &json!({"path": src.to_string_lossy()})).unwrap();
+ // Written without File › Save's preview: drawing it before the document's fonts load would
+ // pull in a system font that covers these characters (Unifont CSUR does) and draws them
+ // ahead of the document's own fonts in this process.
- std::fs::write(&src, crate::cmd::to_bytes(&s.doc().unwrap().doc)).unwrap();
++ std::fs::write(&src, crate::cmd::to_bytes(&s.doc().unwrap().doc).unwrap()).unwrap();
let mut s = Session::new();
assert_eq!(s.execute("file.open", &json!({"path": src.to_string_lossy()})).unwrap()["documentFonts"], 3);
diff --cc crates/engine/src/cmd/prefs.rs
index cbd0e1ece,c74192c83..76e1ce2e2
--- a/crates/engine/src/cmd/prefs.rs
+++ b/crates/engine/src/cmd/prefs.rs
@@@ -50,7 -48,7 +50,7 @@@ pub fn specs() -> Vec<CommandSpec>
"Preferences",
[],
None,
- "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?, highlightHj?, highlightKeeps?, highlightCustomTracking?, highlightSubstitutedFonts?, richBlackOutput?, favoriteFonts?: [family], showFontNamesInEnglish?, cjkFeatures?: bool|null (CJK-only menu items and dialogs shown; null follows the interface language), linkTextFiles? (Create Links When Placing Text Files)} → all application preferences",
- "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?, highlightHj?, highlightKeeps?, highlightCustomTracking?, highlightSubstitutedFonts?, richBlackOutput?, favoriteFonts?: [family], showFontNamesInEnglish?, recoveryMinutes?, recentFilesMax?: 0–100} → all application preferences",
++ "{showHiddenCharacters?, typographersQuotes?, polygonSides?, starInset?, scaleStrokes?, dimensionsIncludeStroke?, transformationsAreTotals?, absolutePageNumbers?, highlightHj?, highlightKeeps?, highlightCustomTracking?, highlightSubstitutedFonts?, richBlackOutput?, favoriteFonts?: [family], showFontNamesInEnglish?, cjkFeatures?: bool|null (CJK-only menu items and dialogs shown; null follows the interface language), linkTextFiles? (Create Links When Placing Text Files), recoveryMinutes?, recentFilesMax?: 0–100} → all application preferences",
super::always,
|s, p| {
let cur = serde_json::to_value(&s.prefs).map_err(|e| bad("prefs.set", e.to_string()))?;
diff --cc crates/engine/src/lib.rs
index 1dbbb4291,05e10ebd1..2d9791454
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -231,11 -201,31 +231,36 @@@ pub struct Prefs
pub show_note_anchors: bool,
/// Preferences › File Handling: minutes between document recovery saves.
pub recovery_minutes: f64,
+ /// File › New › Document › Save Document Preset: saved document presets, by name (`title`).
+ pub document_presets: Vec<designcraft_doc::build::NewDocument>,
+ /// Preferences › File Handling › Create Links When Placing Text Files: placed text files are
+ /// linked (Links panel) unless `file.place` says otherwise.
+ pub link_text_files: bool,
+ /// File › Open Recent: documents opened or saved, most recent first.
+ pub recent_files: Vec<String>,
+ /// Preferences › File Handling › Number of Recent Items to Display (0 keeps no list).
+ pub recent_files_max: u32,
+ }
+
+ /// The most recent files Preferences lets File › Open Recent keep.
+ pub const MAX_RECENT_FILES: u32 = 100;
+
+ impl Prefs {
+ /// Move `path` to the front of File › Open Recent (no duplicates, at most `recent_files_max`).
+ pub fn note_recent_file(&mut self, path: &str) {
+ if path.is_empty() {
+ return;
+ }
+ self.recent_files.retain(|p| p != path);
+ self.recent_files.insert(0, path.to_string());
+ self.trim_recent_files();
+ }
+
+ /// Drop the entries beyond `recent_files_max` (capped at `MAX_RECENT_FILES`).
+ pub fn trim_recent_files(&mut self) {
+ self.recent_files_max = self.recent_files_max.min(MAX_RECENT_FILES);
+ self.recent_files.truncate(self.recent_files_max as usize);
+ }
}
/// A starter autocorrect list (common English typing slips).
@@@ -286,7 -274,8 +311,9 @@@ impl Default for Prefs
show_added_text: true,
show_note_anchors: true,
recovery_minutes: 0.5,
+ link_text_files: false,
+ recent_files: Vec::new(),
+ recent_files_max: 20,
}
}
}
diff --cc crates/format/src/lib.rs
index 803c72a6a,149945ef3..293ad8f48
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@@ -5,9 -5,9 +5,10 @@@
//! - `assets/<id>.<ext>`: embedded placed files, byte-for-byte: one per distinct file, and only
//! the ones the document references (see [`Document::compact_assets`])
//! - `meta.json`: format version and generator
+ //! - `preview.png` (optional): a small picture of the first page, for the start screen's recent files
//!
-//! Older single-file JSON documents (assets as base64 in `assetData`) still open.
+//! Older single-file JSON documents (assets as base64 in `assetData`) still open. Documents
+//! from older format versions are upgraded on load so they lay out as they did.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
@@@ -47,14 -47,11 +48,19 @@@ fn ext_for(mime: &str) -> &'static str
/// Serialize a document to `.designcraft` bytes. The file holds each distinct placed file once
/// and leaves out assets nothing references; `doc` itself keeps them (undo can bring them back).
pub fn save(doc: &Document) -> Result<Vec<u8>, FormatError> {
- save_with_large_entries_from(doc, LARGE_ENTRY)
+ save_with_preview(doc, None)
+ }
+
+ /// [`save`], plus `preview` (PNG bytes) as `preview.png`.
+ pub fn save_with_preview(doc: &Document, preview: Option<&[u8]>) -> Result<Vec<u8>, FormatError> {
++ save_with_large_entries_from(doc, preview, LARGE_ENTRY)
+}
+
+/// Asset entries this size or larger are written with zip64 sizes. Zip rejects an entry over
+/// 4 GiB written without them; the margin covers deflate output that is larger than its input.
+const LARGE_ENTRY: usize = (u32::MAX as usize).saturating_sub(64 << 20);
+
- fn save_with_large_entries_from(doc: &Document, large_entry: usize) -> Result<Vec<u8>, FormatError> {
++fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_entry: usize) -> Result<Vec<u8>, FormatError> {
let mut compact = doc.clone();
compact.compact_assets();
let doc = &compact;
@@@ -87,15 -87,25 +97,34 @@@
Ok(buf.into_inner())
}
+/// The file name extension of a DesignCraft document.
+pub const EXTENSION: &str = "designcraft";
+
+/// Whether `bytes` are a DesignCraft document package: a zip holding `document.json`. Files
+/// without an extension are recognised by this (the legacy JSON form is too generic to sniff).
+pub fn is_designcraft(bytes: &[u8]) -> bool {
+ bytes.starts_with(b"PK") && zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|z| z.index_for_name("document.json").is_some())
+}
+
+ /// The zip entry holding the first page's picture.
+ pub const PREVIEW: &str = "preview.png";
+
+ /// The PNG bytes of a `.designcraft` file's preview, reading only the zip's directory and that
+ /// entry. None for files without one (saved before previews, or legacy JSON) or that aren't ours.
+ pub fn read_preview<R: Read + std::io::Seek>(file: R) -> Option<Vec<u8>> {
+ let mut z = zip::ZipArchive::new(file).ok()?;
+ let mut f = z.by_name(PREVIEW).ok()?;
+ // A preview is small; a huge entry is not one we wrote.
+ if f.size() > MAX_PREVIEW_BYTES {
+ return None;
+ }
+ let mut v = Vec::new();
+ f.read_to_end(&mut v).ok()?;
+ Some(v)
+ }
+
+ const MAX_PREVIEW_BYTES: u64 = 4 << 20;
+
/// Read `.designcraft` bytes (zip, or the legacy single JSON file).
pub fn load(bytes: &[u8]) -> Result<Document, FormatError> {
if bytes.starts_with(b"PK") {
@@@ -364,136 -322,6 +393,136 @@@ mod tests
assert_eq!(back.stories, d.stories);
}
+ /// `doc` as format 1 wrote it.
+ fn save_v1(doc: &Document) -> Vec<u8> {
+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
+ z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();
+ z.write_all(br#"{"format": "designcraft", "version": 1}"#).unwrap();
+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();
+ z.write_all(&serde_json::to_vec(doc).unwrap()).unwrap();
+ z.finish().unwrap().into_inner()
+ }
+
+ fn para_style(name: &str, based_on: Option<&str>, keep_all_lines: Option<bool>) -> designcraft_doc::ParagraphStyle {
+ designcraft_doc::ParagraphStyle {
+ name: name.into(),
+ based_on: based_on.map(str::to_string),
+ next_style: None,
+ para: designcraft_doc::ParaAttrs { keep_lines_together: Some(true), keep_all_lines, ..Default::default() },
+ chars: Default::default(),
+ shortcut: String::new(),
+ }
+ }
+
+ /// Format 1 resolved an unset Keep Lines Together mode as all lines: those documents still
+ /// do after loading, wherever the mode comes from. New documents keep lines at start/end.
+ #[test]
+ fn format_1_keep_lines_without_mode_stays_all_lines() {
+ let mut d = Document::new(&NewDocument::default());
+ let st = d.styles_mut();
+ st.paragraph.push(para_style("Root", None, None));
+ st.paragraph.push(para_style("Child", Some("Root"), None));
+ st.paragraph.push(para_style("Explicit", None, Some(false)));
+ st.paragraph.push(para_style("Under explicit", Some("Explicit"), None));
+ st.paragraph.push(para_style("Loop A", Some("Loop B"), None));
+ st.paragraph.push(para_style("Loop B", Some("Loop A"), None));
+ let lid = d.default_layer();
+ let names = [designcraft_doc::story::BASIC_PARAGRAPH, "Root", "Child", "Explicit", "Under explicit", "Loop A", "Loop B", "Missing"];
+ let text = names.join("\n");
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, &text, ParaFormat::default()).unwrap();
+ {
+ let s = d.story_mut(sid).unwrap();
+ for (p, name) in s.paras.iter_mut().zip(names) {
+ p.style = name.into();
+ p.para.keep_lines_together = Some(true);
+ }
+ s.insert_note(1, "Note", ParaFormat { style: "Missing".into(), ..Default::default() });
+ }
+ let back = load(&save_v1(&d)).unwrap();
+ let resolve = |f: &ParaFormat| back.styles.resolve_para(f).0;
+ let story = back.story(sid).unwrap();
+ for (p, name) in story.paras.iter().zip(names) {
+ let pp = resolve(p);
+ assert!(pp.keep_lines_together);
+ assert_eq!(pp.keep_all_lines, !name.contains("xplicit"), "{name}");
+ }
+ assert!(resolve(&story.notes[0].text.paras[0]).keep_all_lines, "footnote with a missing style");
+ assert!(back.styles.resolve_para_style("Loop A").0.keep_all_lines && back.styles.resolve_para_style("Loop B").0.keep_all_lines);
+ // Pinned where the chains start; explicit and inheriting styles are left as they were.
+ assert_eq!(back.styles.para("Root").unwrap().para.keep_all_lines, Some(true));
+ assert_eq!(back.styles.para("Child").unwrap().para.keep_all_lines, None);
+ assert_eq!(back.styles.para("Under explicit").unwrap().para.keep_all_lines, None);
+ // The current format keeps the new default: at start/end of paragraph.
+ let now = load(&save(&d).unwrap()).unwrap();
+ let p = &now.story(sid).unwrap().paras[0];
+ assert!(!now.styles.resolve_para(p).0.keep_all_lines);
+ assert!(!designcraft_doc::ParaProps::default().keep_all_lines);
+ }
+
+ /// Format 1 wrote paragraph rules, text frame options and numbered lists in full, so their
+ /// old defaults (black rules, auto-size from the top centre, lists continuing across stories)
+ /// load as saved. New documents take InDesign's.
+ #[test]
+ fn format_1_rules_frames_and_lists_load_as_saved() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let old_rule = designcraft_doc::Rule { on: true, color: designcraft_doc::color::swatch::BLACK.into(), ..Default::default() };
+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "Ruled", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(old_rule.clone());
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.auto_size_ref = 1;
+ d.settings.lists.push(designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: true });
+ let back = load(&save_v1(&d)).unwrap();
+ assert_eq!(back.story(sid).unwrap().paras[0].para.rule_above, Some(old_rule));
+ assert_eq!(back.item(fid).unwrap().text_frame().unwrap().options.auto_size_ref, 1);
+ assert!(back.settings.lists[0].continue_across_stories);
+ assert_eq!(designcraft_doc::Rule::default().color, designcraft_doc::TEXT_COLOR);
+ assert_eq!(designcraft_doc::TextFrameOptions::default().auto_size_ref, 4);
+ assert!(!designcraft_doc::NumberedList::default().continue_across_stories);
+ }
+
+ /// Format 1 set drop caps without Align Left Edge: those documents still do where nothing set
+ /// it. New documents align the drop cap's left edge.
+ #[test]
+ fn format_1_drop_caps_stay_unaligned() {
+ let mut d = Document::new(&NewDocument::default());
+ let st = d.styles_mut();
+ st.paragraph.push(para_style("Opener", None, None));
+ st.paragraph.push(designcraft_doc::ParagraphStyle {
+ para: designcraft_doc::ParaAttrs { drop_cap_align_left: Some(true), ..Default::default() },
+ ..para_style("Aligned", None, None)
+ });
+ let lid = d.default_layer();
+ let (_, sid) =
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "One\nTwo\nThree", ParaFormat::default()).unwrap();
+ {
+ let s = d.story_mut(sid).unwrap();
+ for (p, name) in s.paras.iter_mut().zip(["Opener", "Aligned", "Missing"]) {
+ p.style = name.into();
+ p.para.drop_cap_lines = Some(2);
+ p.para.drop_cap_chars = Some(1);
+ }
+ }
+ let back = load(&save_v1(&d)).unwrap();
+ let aligned: Vec<bool> = back.story(sid).unwrap().paras.iter().map(|p| back.styles.resolve_para(p).0.drop_cap_align_left).collect();
+ assert_eq!(aligned, [false, true, false]);
+ let now = load(&save(&d).unwrap()).unwrap();
+ assert!(now.styles.resolve_para(&now.story(sid).unwrap().paras[0]).0.drop_cap_align_left);
+ }
+
+ /// Assets over the zip size limit are written with zip64 sizes (scaled down here: the real
+ /// threshold is near 4 GiB); smaller ones are written exactly as before.
+ #[test]
+ fn large_assets_are_written_with_zip64_sizes_and_open_again() {
+ let mut d = Document::new(&NewDocument::default());
+ let aid = png_asset(&mut d, &[5; 64]);
+ place(&mut d, aid, 0.0);
+ let normal = save(&d).unwrap();
- assert_eq!(normal, save_with_large_entries_from(&d, 65).unwrap(), "an asset under the threshold is unchanged");
- let large = save_with_large_entries_from(&d, 64).unwrap();
++ assert_eq!(normal, save_with_large_entries_from(&d, None, 65).unwrap(), "an asset under the threshold is unchanged");
++ let large = save_with_large_entries_from(&d, None, 64).unwrap();
+ assert!(large.len() > normal.len(), "the asset entry carries zip64 sizes");
+ assert_eq!(*load(&large).unwrap().assets[&aid].data, vec![5; 64]);
+ }
+
#[test]
fn saves_hold_each_used_file_once() {
let mut d = Document::new(&NewDocument::default());
@@@ -607,27 -435,19 +636,40 @@@
assert!(load(&serde_json::to_vec(&v).unwrap()).unwrap().settings.glyph_fallback);
}
+ /// A saved tab list over the limits loads repaired, as an imported one does: a non-finite
+ /// position (saved as `null`) dropped, positions clamped, leaders cut, the count capped.
+ #[test]
+ fn saved_tab_lists_load_sanitized() {
+ use designcraft_doc::{MAX_TAB_LEADER, MAX_TAB_POSITION, MAX_TAB_STOPS, TabAlign, TabStop};
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 300.0), lid, "a\tb", ParaFormat::default()).unwrap();
+ let stop = |position: f64| TabStop { position, align: TabAlign::Right, leader: "0123456789".into(), align_on: String::new() };
+ let mut tabs: Vec<TabStop> = (0..500).rev().map(|i| stop(i as f64 * 40.0)).collect();
+ tabs.push(stop(f64::NAN));
+ d.story_mut(sid).unwrap().paras[0].para.tabs = Some(tabs);
+ let bytes = save(&d).unwrap();
+ let back = load(&bytes).unwrap();
+ let tabs = back.stories[&sid].paras[0].para.tabs.clone().unwrap();
+ assert_eq!(tabs.len(), MAX_TAB_STOPS);
+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");
+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.position <= MAX_TAB_POSITION && t.leader.chars().count() <= MAX_TAB_LEADER));
+ assert_eq!(tabs.last().map(|t| t.position), Some(3960.0), "the first stops by position");
+ }
+
+ #[test]
+ fn the_preview_is_read_back_without_the_document() {
+ let d = Document::new(&NewDocument::default());
+ let png = b"\x89PNG fake".to_vec();
+ let bytes = save_with_preview(&d, Some(&png)).unwrap();
+ assert_eq!(read_preview(Cursor::new(&bytes)), Some(png));
+ assert!(load(&bytes).is_ok(), "the preview doesn't get in the way of opening");
+ // Files without one, legacy JSON and garbage have none.
+ assert_eq!(read_preview(Cursor::new(save(&d).unwrap())), None);
+ assert_eq!(read_preview(Cursor::new(b"{}".to_vec())), None);
+ assert_eq!(read_preview(Cursor::new(Vec::new())), None);
+ }
+
#[test]
fn rejects_garbage_and_newer_versions() {
assert!(load(b"nope").is_err());
diff --cc crates/ui-egui/src/dialogs.rs
index e148089fb,9df5f1a51..09cad7ccc
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -1142,8 -829,13 +1142,16 @@@ fn preferences(app: &crate::DesignApp,
}
});
ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Recent Items to Display:"));
+ let mut v = d.n("recentFilesMax").unwrap_or(20.0);
+ if ui.add(egui::DragValue::new(&mut v).range(0.0..=f64::from(designcraft_engine::MAX_RECENT_FILES)).speed(0.2)).changed() {
+ d.fields.insert("recentFilesMax".into(), json!(v.round()));
+ }
+ });
++ ui.add_space(6.0);
+ ui.label(crate::rtl::widget(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Links")).font(semibold(12.0))));
+ check(ui, d, "linkTextFiles", crate::i18n::tr(&app.ui.language, "Create Links When Placing Text Files"));
}
"type" => {
crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Type Options")).font(semibold(12.0)));
@@@ -2544,9 -2001,12 +2552,10 @@@ pub fn confirm(app: &mut DesignApp) ->
}
}
"preferences" => {
- app.run(
- "prefs.set",
- json!({"scaleStrokes": d.b("scaleStrokes"), "dimensionsIncludeStroke": d.b("dimensionsIncludeStroke"), "transformationsAreTotals": d.b("transformationsAreTotals"), "absolutePageNumbers": d.b("absolutePageNumbers"), "highlightHj": d.b("highlightHj"), "highlightKeeps": d.b("highlightKeeps"), "highlightCustomTracking": d.b("highlightCustomTracking"), "highlightSubstitutedFonts": d.b("highlightSubstitutedFonts"), "richBlackOutput": d.b("richBlackOutput"), "typographersQuotes": d.b("typographersQuotes"), "showFontNamesInEnglish": d.b("showFontNamesInEnglish"), "smartTextReflow": d.b("smartTextReflow"),
+ let mut prefs = json!({"scaleStrokes": d.b("scaleStrokes"), "dimensionsIncludeStroke": d.b("dimensionsIncludeStroke"), "transformationsAreTotals": d.b("transformationsAreTotals"), "absolutePageNumbers": d.b("absolutePageNumbers"), "highlightHj": d.b("highlightHj"), "highlightKeeps": d.b("highlightKeeps"), "highlightCustomTracking": d.b("highlightCustomTracking"), "highlightSubstitutedFonts": d.b("highlightSubstitutedFonts"), "richBlackOutput": d.b("richBlackOutput"), "typographersQuotes": d.b("typographersQuotes"), "showFontNamesInEnglish": d.b("showFontNamesInEnglish"), "smartTextReflow": d.b("smartTextReflow"),
"autocorrect": d.b("autocorrect"), "showAddedText": d.b("showAddedText"), "showNoteAnchors": d.b("showNoteAnchors"),
- "recoveryMinutes": d.n("recoveryMinutes").unwrap_or(0.5),
+ "recoveryMinutes": d.n("recoveryMinutes").unwrap_or(0.5), "linkTextFiles": d.b("linkTextFiles"),
+ "recentFilesMax": d.n("recentFilesMax").unwrap_or(20.0).clamp(0.0, f64::from(designcraft_engine::MAX_RECENT_FILES)) as u32,
"autocorrectList": d.s("autocorrectText").lines().filter_map(|l| {
let (a, b) = l.split_once('→').or_else(|| l.split_once("->"))?;
let (a, b) = (a.trim().to_lowercase(), b.trim().to_string());
diff --cc crates/ui-egui/src/i18n/ar.rs
index ebe080a76,f4251a0aa..413e44c45
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@@ -1002,12 -963,13 +1002,17 @@@ pub(super) const TABLE: &[(&str, &str)
("Right-click: stroke, groups", "نقرة يمنى: الحد والمجموعات"),
("Rotate 90° Clockwise", "تدوير 90° مع عقارب الساعة"),
("Ruler Units", "وحدات المسطرة"),
+ ("Origin:", "نقطة الأصل:"),
+ ("Spine", "الكعب"),
+ ("Lock Zero Point", "قفل نقطة الصفر"),
+ ("Unlock Zero Point", "إلغاء قفل نقطة الصفر"),
("Save Swatches for Exchange…", "حفظ عينات الألوان للتبادل…"),
("Save recovery data every:", "حفظ بيانات الاسترداد كل:"),
+ ("Open Recent", "فتح الملفات الأخيرة"),
+ ("Open Recent File", "فتح ملف حديث"),
+ ("Clear Recent Files", "مسح الملفات الأخيرة"),
+ ("Recent files", "الملفات الأخيرة"),
+ ("Number of Recent Items to Display:", "عدد العناصر الأخيرة المعروضة:"),
("Saves which bars show and where the panels are.", "يحفظ الأشرطة الظاهرة ومواضع اللوحات."),
("Search:", "البحث:"),
(
diff --cc crates/ui-egui/src/i18n/pt_br.rs
index 10617e7b0,3c101fcb9..de7e449af
--- a/crates/ui-egui/src/i18n/pt_br.rs
+++ b/crates/ui-egui/src/i18n/pt_br.rs
@@@ -1003,15 -971,16 +1003,20 @@@ pub(super) const TABLE: &[(&str, &str)
("Right-click: stroke, groups", "Clique direito: traçado, grupos"),
("Rotate 90° Clockwise", "Girar 90° no sentido horário"),
("Ruler Units", "Unidades da régua"),
+ ("Origin:", "Origem:"),
+ ("Spine", "Lombada"),
+ ("Lock Zero Point", "Bloquear ponto zero"),
+ ("Unlock Zero Point", "Desbloquear ponto zero"),
("Save Swatches for Exchange…", "Salvar amostras para intercâmbio…"),
("Save recovery data every:", "Salvar dados de recuperação a cada:"),
+ ("Open Recent", "Abrir recentes"),
+ ("Open Recent File", "Abrir arquivo recente"),
+ ("Clear Recent Files", "Limpar arquivos recentes"),
+ ("Recent files", "Arquivos recentes"),
+ ("Number of Recent Items to Display:", "Número de itens recentes a exibir:"),
("Saves which bars show and where the panels are.", "Salva quais barras são exibidas e onde ficam os painéis."),
("Search:", "Pesquisar:"),
- ("Select an object to color its fill or stroke.", "Selecione um objeto para colorir seu preenchimento ou traçado."),
+ ("Select an object or text to color its fill or stroke.", "Selecione um objeto ou texto para colorir seu preenchimento ou traçado."),
("Select an object to give its fill a gradient.", "Selecione um objeto para dar um gradiente ao seu preenchimento."),
("Select an object to make it a button.", "Selecione um objeto para transformá-lo em botão."),
("Select an object.", "Selecione um objeto."),
diff --cc crates/ui-egui/src/menus.rs
index 90b26f843,b9744f4b7..e0af5bedc
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -4548,67 -3671,71 +4614,135 @@@ mod tests
assert!(!open, "an open submenu closes when its row becomes fully clipped");
}
+ #[test]
+ fn mac_settings_follow_about_in_the_app_menu_and_leave_edit() {
+ let pos = |command: &str| MAC_APP_MENU.iter().position(|m| matches!(m, AppMenuItem::Cmd { command: c, .. } if *c == command));
+ let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") };
+ assert!(about < settings);
+ assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep));
+ assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Sep));
+ let label = |command: &str| {
+ MAC_APP_MENU.iter().find_map(|m| match m {
+ AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label),
+ _ => None,
+ })
+ };
+ assert_eq!(label("app.preferences"), Some("Settings…"));
+ assert_ne!(crate::i18n::tr("de", "Settings…"), "Settings…");
+ let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::<Vec<_>>();
+ assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}");
+
+ let edit = |tree: Vec<(&'static str, Vec<Item>)>| {
+ let mut out = Vec::new();
+ walk(&tree.into_iter().find(|(t, _)| *t == "Edit").map(|(_, e)| e).unwrap_or_default(), &mut out);
+ out.into_iter().map(|(_, id, _)| id).collect::<Vec<_>>()
+ };
+ assert!(edit(menu_tree()).iter().any(|id| id == "app.preferences"), "the in-window Edit menu keeps Preferences");
+ let native = native_menu_tree();
+ let mut all = Vec::new();
+ for (_, entries) in &native {
+ walk(entries, &mut all);
+ }
+ assert!(!all.iter().any(|(_, id, _)| id == "app.preferences"), "the macOS menu bar has Settings only in the app menu");
+ assert!(edit(native_menu_tree()).iter().any(|id| id == "app.keyboardShortcuts"));
+ for (title, entries) in &native {
+ assert!(!matches!(entries.first(), Some(Item::Sep)) && !matches!(entries.last(), Some(Item::Sep)), "{title}: separator at an end");
+ assert!(entries.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep])), "{title}: doubled separator");
+ }
+ }
+
+ /// Web save: a download that couldn't start is an error and leaves the document unsaved; one
+ /// that started marks it saved.
+ #[test]
+ fn web_save_marks_the_document_saved_only_after_the_download_starts() {
+ let dir = tempfile::tempdir().unwrap();
+ // The title names a temporary path: on native, file.saveAs writes where the web build doesn't.
+ let title = dir.path().join("doc").to_string_lossy().to_string();
+ let fails = std::rc::Rc::new(std::cell::Cell::new(true));
+ let f = fails.clone();
+ let services = crate::Services {
+ download: Some(Box::new(move |_: &str, _: &[u8]| if f.get() { Err("blocked".into()) } else { Ok(()) })),
+ ..Default::default()
+ };
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);
+ app.run("file.new", json!({"title": title})).unwrap();
+ app.run("frame.create", json!({"rect": [36, 36, 300, 200]})).unwrap();
+ assert!(app.session.active().unwrap().is_dirty());
+
+ let e = app.run("app.save", json!({})).unwrap_err();
+ assert!(e.contains("blocked"), "{e}");
+ assert!(app.session.active().unwrap().is_dirty(), "a failed download leaves the document unsaved");
+
+ fails.set(false);
+ app.run("app.save", json!({})).unwrap();
+ assert!(!app.session.active().unwrap().is_dirty());
+ }
++
+ fn start_screen_texts(app: &mut crate::DesignApp) -> Vec<String> {
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx, "");
+ let mut shapes = Vec::new();
+ for _ in 0..3 {
+ let input =
+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };
+ let mut out = ctx.run_ui(input, |ui| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ shapes = out.shapes;
+ }
+ shapes
+ .iter()
+ .filter_map(|s| match &s.shape {
+ egui::Shape::Text(t) => Some(t.galley.text().to_string()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// File › Open Recent: the files first (`app.openRecent {index}`), then Clear Recent Files.
+ #[test]
+ fn open_recent_lists_the_files_then_clear() {
+ let tree = menu_tree();
+ let file = &tree.iter().find(|(m, _)| *m == "File").unwrap().1;
+ let Some(Item::Sub(name, children)) = file.get(2) else { panic!("Open Recent after Open…: {:?}", file.get(2)) };
+ assert_eq!(format!("File/{name}"), OPEN_RECENT);
+ assert!(matches!(children.as_slice(), [Item::Cmd { id, .. }] if id == "file.clearRecent"));
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ assert!(recent_items(&app).is_empty());
+ assert!(!menu_enabled(&app, "file.clearRecent"));
+ app.session.prefs.note_recent_file("/work/a.designcraft");
+ app.session.prefs.note_recent_file("/work/b.idml");
+ let items = recent_items(&app);
+ let labels: Vec<_> = items
+ .iter()
+ .map(|i| match i {
+ Item::Cmd { label, id, params, .. } => format!("{label} {id} {params}"),
+ Item::Sep => "-".into(),
+ Item::Sub(..) => "sub".into(),
+ })
+ .collect();
+ assert_eq!(labels, ["b.idml app.openRecent {\"index\":0}", "a.designcraft app.openRecent {\"index\":1}", "-"]);
+ assert!(menu_enabled(&app, "file.clearRecent"));
+ assert!(menu_enabled(&app, "app.openRecent"));
+ }
+
+ /// A recent file that is gone says so in an alert (and the start screen still lists it).
+ #[test]
+ fn open_recent_of_a_missing_file_alerts_and_the_start_screen_lists_recent_files() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ assert!(!start_screen_texts(&mut app).iter().any(|t| t == "Recent files"), "no section without recent files");
+ app.session.prefs.note_recent_file("/nonexistent/dc-recent/gone.designcraft");
+ assert!(app.run("app.openRecent", json!({"index": 0})).is_err());
+ let d = app.ui.dialog.take().expect("an alert");
+ assert_eq!(d.fields["title"], "Can't Open the File");
+ assert_eq!(d.fields["file"], "gone.designcraft");
+ assert!(d.fields["message"].as_str().unwrap().contains("can't be found"));
+ assert!(app.run("app.openRecent", json!({"index": 9})).is_err(), "out of range: an error, not a panic");
+ app.ui.dialog = None;
+ let texts = start_screen_texts(&mut app);
+ assert!(texts.iter().any(|t| t == "Recent files"), "{texts:?}");
+ assert!(texts.iter().any(|t| t == "gone"), "the card names it without `.designcraft`: {texts:?}");
+ }
}
diff --cc docs/target-app-parity.md
index 60623efe4,019b2510d..af06935fb
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# DesignCraft parity with Adobe InDesign
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (.indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md)
summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature