DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge atomic-save: MCP: exported files replace the target atomically (#436)
aiongg2fae23fcc6ee
diff --cc Cargo.tomlindex d95e49a9a,35a1ed711..0fe2ca16a--- a/Cargo.toml+++ b/Cargo.toml@@@ -66,10 -65,10 +66,12 @@@ krilla = { version = "0.8", features =hayro = "0.7"quick-xml = "0.38"zip = { version = "3", default-features = false, features = ["deflate"] }+# INDD/INDT → IDML conversion for File › Open (indd-utils, tracking its main branch; MIT OR Apache-2.0, no dependencies).+indd = { git = "https://github.com/aiongg/indd-utils", branch = "main" }# ui+ # Shared frontend components; keep this dependency above the engine boundary.+ craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }egui = "0.36"egui_extras = { version = "0.36", default-features = false, features = ["svg"] }eframe = { version = "0.36", default-features = false }diff --cc ROADMAP.mdindex a83bf7ffa,9a0f71e70..b7e207e61--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -129,16 -129,7 +129,17 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+- **2026-10-11** · Live corners: the yellow widget on a selected rectangle frame shows corner+ diamonds; dragging one rounds the corners, Alt-click steps the corner shape (#186).+- **2026-10-11** · Optical kerning (#181): pairs are spaced from their outlines (ink gap per band,+ pulled towards the font's stem gap, bounded) instead of silently using the font's kern pairs.+- **2026-10-11** · New Document laid out like InDesign's (#325): Recent, Saved, Print, Web and+ Mobile preset tabs beside the preset's details; saved document presets live in the engine+ (`file.savePreset`, `file.deletePreset`, `file.new {preset}`); `file.new` takes intent, units,+ start page and per-edge bleed and slug.+- **2026-10-11** · macOS: fonts that font services and managers activate (Adobe Fonts,+ RightFont) are listed, read from the files CoreText has available (#261, #327).+ - **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.- **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLIsmoke-tested under QEMU).- **2026-10-10** · Readiness per audience: full ~47% (method aligned with the standard, wasdiff --cc apps/designcraft/src/main.rsindex 2bfc959e6,35a5686f4..0a56b79c7--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@@ -82,31 -68,6 +83,17 @@@ impl eframe::App for App}}+/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as+/// typed). winit's IME toggle only clears its own copy, so the IME would type it again.+#[cfg(target_os = "macos")]+fn discard_marked_text() {+ if let Some(mtm) = objc2::MainThreadMarker::new()+ && let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)+ {+ ic.discardMarkedText();+ }+}+- /// The per-user settings directory: `ui.json`, `prefs.json`, `gpu.json` and `logs/` live here.- fn config_dir() -> Option<std::path::PathBuf> {- if cfg!(target_os = "macos") {- std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/DesignCraft"))- } else if cfg!(windows) {- std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("DesignCraft"))- } else {- std::env::var_os("XDG_CONFIG_HOME")- .map(std::path::PathBuf::from)- .or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))- .map(|c| c.join("designcraft"))- }- }-/// `DESIGNCRAFT_NO_PREFS`: read and write nothing in the settings directory (tests, demos).fn no_prefs() -> bool {std::env::var_os("DESIGNCRAFT_NO_PREFS").is_some()@@@ -360,37 -259,13 +347,37 @@@ fn main() -> std::process::ExitCodeoptions.viewport = options.viewport.with_icon(icon);}// The graphics backend, decided before the window exists: a driver that faults takes the- // process down before any Rust code can catch it (see `gpu`).- let gpu = gpu::Startup::begin(if no_prefs() { None } else { profile::config_dir().map(|d| d.join(gpu::FILE)) }, env!("CARGO_PKG_VERSION"));- if let Some(s) = &gpu- && let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup- {- create.instance_descriptor.backends = s.backends();+ // process down before any Rust code can catch it (see `gpu::backend`).+ let fallback = gpu::backend::Fallback::begin(- if no_prefs() { None } else { config_dir().map(|d| d.join(gpu::backend::FILE)) },++ if no_prefs() { None } else { profile::config_dir().map(|d| d.join(gpu::backend::FILE)) },+ env!("CARGO_PKG_VERSION"),+ &gpu::backend::skipped_backends(&skip),+ );+ let instance_backends = fallback.as_ref().map(gpu::backend::Fallback::backends);+ let startup = std::sync::Arc::new(gpu::Startup::new(fallback, skip.clone()));+ // The adapter: the GPU that drives the (primary) display unless `WGPU_POWER_PREF` chooses a+ // kind; a GPU without a monitor reset its driver and took every monitor down. Logged first:+ // the first question in every black-window report.+ let power_env = eframe::wgpu::PowerPreference::from_env();+ let power = gpu::power_preference(power_env);+ let displays = gpu::preferred_displays(power_env);+ let chosen_gpu = !gpu::automatic(power_env);+ if chosen_gpu {+ log::info!("graphics processor chosen by WGPU_POWER_PREF ({power:?}): which GPU drives the display isn't considered");+ } else {+ let listed: Vec<String> = displays.iter().map(ToString::to_string).collect();+ log::info!("display GPUs (PCI vendor:device): {}", if listed.is_empty() { "unknown".to_string() } else { listed.join(", ") });+ }+ if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {+ if let Some(backends) = instance_backends {+ create.instance_descriptor.backends = backends;+ }+ create.instance_descriptor.flags = gpu::instance_flags();+ // Only adapters that can show the window, in the order `gpu` gives.+ create.native_adapter_selector = Some(gpu::selector(power, displays, startup.clone()));}+ gpu::watch_panics();+ gpu::watch_first_frame(startup.clone());// winit has no file drag-and-drop on Wayland (only on X11), so dropping images from the file// manager showed a "no" cursor. Run through XWayland when it's there; DESIGNCRAFT_WAYLAND=1// keeps the native Wayland backend.@@@ -401,97 -276,54 +388,97 @@@b.with_x11();}));}- eframe::run_native(- "DesignCraft",- options,- Box::new(move |cc| {- let mut gpu = gpu;- if let Some(rs) = &cc.wgpu_render_state {- // What a bug report needs to know about the graphics driver.- let info = rs.adapter.get_info();- log::info!("graphics: {} on {:?} ({:?}; driver {} {})", info.name, info.backend, info.device_type, info.driver, info.driver_info);- if let (Some(s), Some(backend)) = (gpu.as_mut(), gpu::Backend::of(info.backend)) {- s.started_with(backend);+ // Registered before the event loop starts, so it catches the Finder event that launched the app+ // as well as later ones. Lives until the event loop returns; the app creator only borrows it.+ #[cfg(target_os = "macos")]+ let apple_events = apple_events::AppleEvents::install();+ #[cfg(target_os = "macos")]+ let events = &apple_events;+ let created = startup.clone();+ // A panic that ends the window (egui-wgpu's own) is caught here: never a crash.+ let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ eframe::run_native(+ "DesignCraft",+ options,+ Box::new(move |cc| {+ let mut restarted = None;+ if let Some(rs) = &cc.wgpu_render_state {+ // What a bug report needs to know about the graphics driver.+ let info = rs.adapter.get_info();+ log::info!(+ "graphics: {} on {:?} ({:?}; driver {} {}; power preference {power:?})",+ info.name,+ info.backend,+ info.device_type,+ info.driver,+ info.driver_info+ );+ created.started_with(info.backend);+ created.created(&cc.egui_ctx);+ if !skip.is_empty() {+ // A processor chosen by `WGPU_POWER_PREF` can be the one that can't show the window.+ let hint = if chosen_gpu { " (without WGPU_POWER_PREF it uses the one that drives your display)" } else { "" };+ restarted = Some(format!(+ "The graphics processor tried first couldn't show the window, so DesignCraft started again on {} ({:?}, {:?}){hint}.",+ info.name.trim(),+ info.backend,+ info.device_type+ ));+ }}- }- let mut session = Session::new();- // Crash recovery: reopen what a previous run left unsaved, then keep it current.- session.recovery_dir = profile::recovery_dir();- let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok();- let mut app = DesignApp::new(session, services());- if let Some(line) = gpu.as_ref().and_then(gpu::Startup::status_line) {- app.status(line);- }- // Recovered documents matter more than the graphics note; both are in the log.- if let Some(n) = recovered.as_ref().and_then(|r| r["opened"].as_array()).map(Vec::len).filter(|n| *n > 0) {- app.status(format!("Recovered {n} unsaved document{} from the last session.", if n == 1 { "" } else { "s" }));- }- load_prefs(&mut app);- app.integrated_titlebar = cfg!(target_os = "macos");- if let Some(port) = control_port {- let rx = control_server::start(port, cc.egui_ctx.clone());- app = app.with_control(rx);- }- if sample {- let _ = app.run("file.newSample", serde_json::json!({}));- }- for f in files {- if let Err(e) = app.open_file("file.open", serde_json::json!({"path": f})) {- eprintln!("designcraft: {f}: {e}");+ let mut session = Session::new();+ // Crash recovery: reopen what a previous run left unsaved, then keep it current.- session.recovery_dir = designcraft_engine::recovery::default_dir();++ session.recovery_dir = profile::recovery_dir();+ let recovered = session.execute("file.recovery.open", &serde_json::json!({})).ok();+ let mut app = DesignApp::new(session, services());+ if let Some(line) = restarted.or_else(|| created.status_line()) {+ app.status(line);}- }- Ok(Box::new(App {- app,- #[cfg(target_os = "macos")]- menu: None,- startup: gpu,- frames: 0,- }))- }),- )+ // Recovered documents matter more than the graphics note; both are in the log.+ if let Some(n) = recovered.as_ref().and_then(|r| r["opened"].as_array()).map(Vec::len).filter(|n| *n > 0) {+ app.status(format!("Recovered {n} unsaved document{} from the last session.", if n == 1 { "" } else { "s" }));+ }+ load_prefs(&mut app);+ app.integrated_titlebar = cfg!(target_os = "macos");+ if let Some(port) = control_port {+ let rx = control_server::start(port, cc.egui_ctx.clone());+ app = app.with_control(rx);+ }+ if sample {+ let _ = app.run("file.newSample", serde_json::json!({}));+ }+ for f in files {+ if let Err(e) = app.open_file("file.open", serde_json::json!({"path": f})) {+ log::warn!("{f}: {e}");+ }+ }+ // The first frame is due from now (`gpu::watch_first_frame`).+ created.ready();+ Ok(Box::new(App {+ app,+ #[cfg(target_os = "macos")]+ menu: None,+ startup: created,+ #[cfg(target_os = "macos")]+ apple_events: events.connect(&cc.egui_ctx),+ frames: 0,+ }))+ }),+ )+ }))+ .map_err(|payload| designcraft_engine::guard::panic_message(payload.as_ref()));+ // The window's end, or a graphics failure that starts the app again. A failure is logged:+ // standard error and the log file, since a Windows start has no console to show it.+ // Documents that arrived after the last frame, for a start again to open too.+ #[cfg(target_os = "macos")]+ startup.opening(apple_events.queued());+ match gpu::finish(run, &startup) {+ Ok(()) => std::process::ExitCode::SUCCESS,+ Err(e) => {+ log::error!("DesignCraft stopped: {e}");+ std::process::ExitCode::FAILURE+ }+ }}#[cfg(test)]diff --cc crates/engine/src/cmd/file.rsindex c319538eb,e1e804015..f235a4258--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -13,43 -13,21 +13,43 @@@ use crate::{DocState, EngineError, Resupub 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}",+ "{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 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.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.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt", always, file_open_bytes),+ 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 bytes = to_bytes(&s.doc()?.doc);#[cfg(not(target_arch = "wasm32"))]- std::fs::write(&path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ crate::atomic::write_file(&path, &bytes)?;Ok(json!({"path": path, "bytes": bytes.len()}))}),cmd!(noundo "file.revert", "Revert", ["File"], None, "{} — back to the last saved version (not undoable)", can_revert, file_revert),diff --cc crates/ui-egui/src/dock.rsindex a9b723fa1,72810e151..0168e8abb--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@@ -48,15 -48,10 +48,18 @@@ pub const ICON_PANELS: &[(&str, &str, &("dataMerge", "Data Merge", "panel-datamerge"),];+/// Panels that only float (they open from a menu, not from the icon column).+pub const FLOATING_PANELS: &[(&str, &str)] = &[("tabs", "Tabs")];++/// The English name of panel `id`.+pub fn panel_label(id: &str) -> &'static str {+ ICON_PANELS.iter().map(|p| (p.0, p.1)).chain(FLOATING_PANELS.iter().copied()).find(|p| p.0 == id).map_or("Panel", |p| p.1)+}+pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {+ if crate::panel_docking::show(app, ui) {+ return;+ }let t = Tokens::get(ui.ctx());// Expanded panel stack (outermost, 253 pt) — declared first so it sits at the far right.if app.ui.dock_expanded {@@@ -131,9 -135,12 +143,12 @@@ fn dock_header(ui: &mut egui::Ui, t: &T/// A panel opened from the icon column, shown as a floating flyout next to the dock.pub fn flyout(app: &mut DesignApp, ctx: &egui::Context) {+ if app.ui.docking.is_some() {+ return;+ }let Some(id) = app.ui.open_panel.clone() else { return };let t = Tokens::get(ctx);- let label = crate::i18n::tr(&app.ui.language, ICON_PANELS.iter().find(|p| p.0 == id).map(|p| p.1).unwrap_or("Panel")).to_owned();+ let label = crate::i18n::tr(&app.ui.language, panel_label(&id)).to_owned();let screen = ctx.content_rect();let dock_w = if app.ui.dock_expanded { ctx.memory(|m| m.area_rect(egui::Id::new("dock")).map(|r| r.width())).unwrap_or(280.0) } else { 0.0 };let pos = egui::pos2(screen.max.x - 37.0 - dock_w - 262.0, 120.0);@@@ -232,13 -245,15 +254,16 @@@ pub fn dock_panel(app: &mut DesignApp,/// Floating panels: movable, resizable windows; "Dock" returns one to the icon column.pub fn floating(app: &mut DesignApp, ctx: &egui::Context) {+ if app.ui.docking.is_some() {+ return;+ }let t = Tokens::get(ctx);for (id, at) in app.ui.floating.clone() {- let label = crate::i18n::tr(&app.ui.language, ICON_PANELS.iter().find(|p| p.0 == id).map(|p| p.1).unwrap_or("Panel")).to_owned();+ let label = crate::i18n::tr(&app.ui.language, panel_label(&id)).to_owned();+ let docks = ICON_PANELS.iter().any(|p| p.0 == id);let mut open = true;let mut dock = false;- let r = egui::Window::new(label.clone())+ let mut w = egui::Window::new(label.clone()).id(egui::Id::new(("floating_panel", &id))).title_bar(false).default_pos(egui::pos2(at[0], at[1]))diff --cc crates/ui-egui/src/lib.rsindex e0e293f12,c003154ad..4694b1099--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -16,12 -16,11 +16,14 @@@ pub mod dockpub mod i18n;pub mod icons;pub mod menus;+mod new_document;+mod object_control;+ mod panel_docking;pub mod panels;+ mod prefs;pub mod render_worker;mod rtl;+mod section_options;pub mod story_editor;pub mod taskbar;pub mod theme;diff --cc crates/ui-egui/src/menus.rsindex 678a9e3ac,d123ec4eb..fff62d7d2--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -753,19 -721,11 +769,22 @@@ pub fn ui_label(id: &str) -> Option<(&'UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| (c.1, c.2))}+/// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it.+fn toggle_tabs_panel(app: &mut DesignApp) {+ if app.ui.floating.iter().any(|(p, _)| p == "tabs") {+ crate::dock::dock_panel(app, "tabs");+ } else {+ let at = app.canvas_rect.map_or(egui::pos2(300.0, 140.0), |r| r.min + egui::vec2(80.0, 60.0));+ crate::dock::float_panel(app, "tabs", at);+ app.ui.tabs_panel.snap_request = 2;+ }+}+/// Run a UI command; `None` if `id` isn't one.pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ if let Some(result) = crate::panel_docking::command(app, id, p) {+ return Some(result);+ }let rect = app.canvas_rect;let flag = |b: &mut bool| {*b = !*b;