Skip to content

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

Merge file-open-os: Save adds .designcraft, and the OS opens DesignCraft and IDML files

aiongg62df5e764a6d
diff --cc Cargo.lock
index c82ba9c4d,cbcca4195..72499f27a
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -877,10 -876,9 +877,11 @@@ dependencies =
"designcraft-ui-egui",
"eframe",
"egui",
+ "fmv-macos-events",
"log",
"muda",
+ "objc2 0.6.4",
+ "objc2-app-kit 0.3.2",
"rfd",
"serde",
"serde_json",
diff --cc apps/designcraft/Cargo.toml
index 6941afe9d,16cc4d4dd..02b6b5714
--- a/apps/designcraft/Cargo.toml
+++ b/apps/designcraft/Cargo.toml
@@@ -30,14 -29,10 +30,19 @@@ arboard = { workspace = true
# The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs.
winit = { version = "0.30", default-features = false, features = ["x11"] }
+[target.'cfg(windows)'.dependencies]
+# EnumDisplayDevices (src/gpu.rs): which GPU drives the display, so the window draws on the GPU
+# that shows it; drawing on a GPU without a monitor reset the display driver. Safe wrappers over
+# Win32 (MIT); the `user` feature is User32.dll only.
+winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
+
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.21", default-features = false }
+# The input context, to drop the IME's marked text when the Type tool ends a composition.
+objc2 = "0.6"
+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSTextInputContext"] }
+ # Finder double-clicks, Open With, Dock drops and `open -a DesignCraft brochure.idml` arrive as a
+ # kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This crate (also used by PhotoCraft,
+ # PdfCraft and WordCraft) registers the handler behind a safe API (Objective-C interop needs unsafe,
+ # which the workspace forbids). Pinned exactly: review the diff before bumping.
+ fmv-macos-events = "=0.1.0"
diff --cc apps/designcraft/src/apple_events.rs
index 000000000,79c19692d..71bb6a52f
mode 000000,100644..100644
--- a/apps/designcraft/src/apple_events.rs
+++ b/apps/designcraft/src/apple_events.rs
@@@ -1,0 -1,46 +1,59 @@@
+ //! macOS open-documents and quit Apple events.
+ //!
+ //! Finder double-clicks, Open With, drops on the Dock icon and `open -a DesignCraft brochure.idml`
+ //! don't pass paths on the command line: LaunchServices sends the running (or just-launched) app a
+ //! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the
+ //! `NSApplicationDelegate`, and handling it ourselves needs Objective-C class declarations, i.e.
+ //! `unsafe`, which this workspace forbids. The `fmv-macos-events` crate wraps exactly that (an
+ //! `NSAppleEventManager` handler registered before Finder's launch event, leaving winit's delegate
+ //! alone) behind a safe main-thread API.
+
+ use designcraft_ui_egui::DesignApp;
+ use fmv_macos_events::{Event, Inbox, Registration};
+
+ /// Keeps the Apple-event handlers registered; hold it until the event loop returns.
+ pub struct AppleEvents {
+ _registration: Registration,
+ inbox: Inbox,
+ }
+
+ impl AppleEvents {
+ /// Register the handlers. Call on the main thread before the event loop starts, so the event
+ /// that launched the app (a Finder double-click) is caught too.
+ pub fn install() -> Self {
+ let (registration, inbox) = Registration::install();
+ Self { _registration: registration, inbox }
+ }
+
+ /// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`.
+ pub fn connect(&self, ctx: &egui::Context) -> Inbox {
+ let ctx = ctx.clone();
+ self.inbox.set_wake(move || ctx.request_repaint());
+ self.inbox.clone()
+ }
++
++ /// The documents still queued: those that arrived after the window's last frame.
++ pub fn queued(&self) -> Vec<String> {
++ self.inbox
++ .drain()
++ .into_iter()
++ .flat_map(|e| if let Event::Open(paths) = e { paths } else { Vec::new() })
++ .map(|p| p.to_string_lossy().into_owned())
++ .collect()
++ }
+ }
+
+ /// Hand the documents that arrived since the last frame to the app, which opens them as File ›
-/// Open does once its window is ready; a quit request (Dock › Quit) closes the window, as its close
-/// button does.
-pub fn poll(inbox: &Inbox, app: &mut DesignApp, ctx: &egui::Context) {
++/// Open does once its window is ready, and return them; a quit request (Dock › Quit) closes the
++/// window, as its close button does.
++pub fn poll(inbox: &Inbox, app: &mut DesignApp, ctx: &egui::Context) -> Vec<String> {
++ let mut documents = Vec::new();
+ for e in inbox.drain() {
+ match e {
- Event::Open(paths) => app.open_documents_later(paths.into_iter().map(|p| p.to_string_lossy().into_owned())),
++ Event::Open(paths) => documents.extend(paths.into_iter().map(|p| p.to_string_lossy().into_owned())),
+ Event::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
+ }
+ }
++ app.open_documents_later(documents.iter().cloned());
++ documents
+ }
diff --cc apps/designcraft/src/gpu.rs
index 361ed25ba,e80f566b9..01b3ca6d4
--- a/apps/designcraft/src/gpu.rs
+++ b/apps/designcraft/src/gpu.rs
@@@ -186,564 -80,160 +186,575 @@@ pub fn display_gpus() -> Vec<DisplayGpu
}
}
-/// What `gpu.json` holds.
-#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct Record {
- /// The DesignCraft version that wrote the record; another version starts afresh.
- #[serde(default)]
- pub version: String,
- /// The backend of a start that has not presented a frame yet.
- #[serde(default)]
- pub trying: Option<Backend>,
- /// Backends whose start never presented a frame.
- #[serde(default)]
- pub failed: Vec<Backend>,
+/// Record that the GPU `pci` drives a display, merging it with its other displays.
+#[cfg(any(windows, target_os = "linux", test))]
+fn add_display_gpu(gpus: &mut Vec<DisplayGpu>, pci: (u32, u32), primary: bool) {
+ match gpus.iter_mut().find(|g| g.pci == pci) {
+ Some(gpu) => gpu.primary |= primary,
+ None => gpus.push(DisplayGpu { pci, primary }),
+ }
}
-/// The backend for a start, from [`choose`].
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct Choice {
- pub backend: Backend,
- /// The record to write before the window is created.
- pub record: Record,
- /// The backend the previous start never finished with, when this start moves away from it.
- pub switched_from: Option<Backend>,
-}
-
-/// Pick the backend for this start from the candidates (best first) and the previous start's
-/// record; `None` without candidates.
-pub fn choose(candidates: &[Backend], previous: &Record, version: &str) -> Option<Choice> {
- let first = *candidates.first()?;
- let same_version = previous.version == version;
- let mut failed: Vec<Backend> = if same_version { previous.failed.clone() } else { Vec::new() };
- failed.retain(|b| candidates.contains(b));
- let unfinished = previous.trying.filter(|_| same_version);
- if let Some(b) = unfinished
- && !failed.contains(&b)
- {
- failed.push(b);
- }
- let backend = match candidates.iter().copied().find(|b| !failed.contains(b)) {
- Some(b) => b,
- // Every candidate has failed: start over rather than never starting.
- None => {
- failed.clear();
- first
+/// Windows' display devices: one per GPU output; those `ATTACHED_TO_DESKTOP` show a monitor, one
+/// of them the `PRIMARY_DEVICE`. The registry doesn't tell a user which adapter drives a display,
+/// and WMI reports a resolution for a GPU without a monitor, so this is the way.
+#[cfg(windows)]
+fn windows_display_gpus() -> Vec<DisplayGpu> {
+ use winsafe::co::DISPLAY_DEVICE as Flags;
+ let mut gpus = Vec::new();
+ // A machine has a handful of display devices; the cap only bounds a runaway enumeration.
+ for device in winsafe::EnumDisplayDevices(None, None).take(256) {
+ let device = match device {
+ Ok(d) => d,
+ // The enumeration ends with "no more items" or, from a driver, with any other error.
+ Err(e) => {
+ log::debug!("display devices: {e}");
+ break;
+ }
+ };
+ if !device.StateFlags.has(Flags::ATTACHED_TO_DESKTOP) {
+ continue;
}
+ // Remote Desktop and other non-PCI devices (`ROOT\BasicDisplay\0000`) are left out.
+ let Some(pci) = pci_ids(&device.DeviceID()) else { continue };
+ add_display_gpu(&mut gpus, pci, device.StateFlags.has(Flags::PRIMARY_DEVICE));
+ }
+ gpus
+}
+
+/// The PCI `(vendor, device)` of a Windows device id such as
+/// `PCI\VEN_10DE&DEV_2204&SUBSYS_40421458&REV_A1`, any case; `None` for anything else.
+#[cfg(any(windows, test))]
+fn pci_ids(device_id: &str) -> Option<(u32, u32)> {
+ let field = |key: &str| {
+ device_id.split(['\\', '&']).find_map(|part| {
+ let (name, hex) = part.split_at_checked(key.len())?;
+ if name.eq_ignore_ascii_case(key) { u32::from_str_radix(hex, 16).ok() } else { None }
+ })
+ };
+ Some((field("VEN_")?, field("DEV_")?))
+}
+
+/// Linux: every connector `cardN-CONNECTOR` under `drm` whose `status` is `connected`, with the
+/// PCI ids of its card (`cardN/device/{vendor,device}`). A built-in panel is the primary display.
+#[cfg(any(target_os = "linux", test))]
+fn linux_display_gpus(drm: &std::path::Path) -> Vec<DisplayGpu> {
+ let read_hex = |p: std::path::PathBuf| -> Option<u32> {
+ let s = std::fs::read_to_string(p).ok()?;
+ u32::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok()
};
- let switched_from = unfinished.filter(|b| *b != backend);
- Some(Choice { backend, record: Record { version: version.to_owned(), trying: Some(backend), failed }, switched_from })
+ let mut gpus = Vec::new();
+ let Ok(entries) = std::fs::read_dir(drm) else { return gpus };
+ // A machine has a handful of connectors; the cap only bounds a pathological sysfs.
+ for entry in entries.flatten().take(256) {
+ let name = entry.file_name();
+ let Some((card, connector)) = name.to_str().and_then(|n| n.split_once('-')) else { continue };
+ let connected = std::fs::read_to_string(entry.path().join("status")).is_ok_and(|s| s.trim() == "connected");
+ if !connected {
+ continue;
+ }
+ let device = drm.join(card).join("device");
+ let (Some(v), Some(d)) = (read_hex(device.join("vendor")), read_hex(device.join("device"))) else { continue };
+ add_display_gpu(&mut gpus, (v, d), is_internal_panel(connector));
+ }
+ gpus
+}
+
+/// A laptop's built-in panel: an embedded DisplayPort, LVDS or DSI connector.
+#[cfg(any(target_os = "linux", test))]
+fn is_internal_panel(connector: &str) -> bool {
+ ["eDP", "LVDS", "DSI"].iter().any(|kind| connector.starts_with(kind))
}
-/// The record in `path`; a missing or unreadable file is an empty record.
-pub fn read(path: &Path) -> Record {
- std::fs::read(path).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default()
+/// `backend:vendor:device`, e.g. `Vulkan:1002:164e` (PCI ids, as `MESA_VK_DEVICE_SELECT` takes them).
+/// Metal reports no ids (`0000:0000` for every GPU), so an adapter without them is `backend:name`
+/// (`Metal:Intel Iris Pro Graphics`): otherwise leaving out the one that failed would leave out
+/// every GPU of a dual-GPU Mac. Commas, which separate [`SKIP_ARG`]'s keys, become spaces.
+fn key(backend: Backend, vendor: u32, device: u32, name: &str) -> String {
+ if vendor == 0 && device == 0 {
+ format!("{backend:?}:{}", name.replace(',', " ").trim())
+ } else {
+ format!("{backend:?}:{vendor:04x}:{device:04x}")
+ }
}
-/// Write `record` to `path` (creating the directory).
-pub fn write(path: &Path, record: &Record) -> std::io::Result<()> {
- if let Some(dir) = path.parent() {
- std::fs::create_dir_all(dir)?;
+/// The order to try `candidates` in (their indices): only those that present to the window and
+/// aren't in `skip`; the one whose name contains `named` (any case) first; hardware before
+/// software; native backends before OpenGL; the GPUs that drive one of `displays`, the primary
+/// display's first; then by `power`; then DX12 before Vulkan, keeping the system's order among
+/// equals (all of it for [`PowerPreference::None`]). Windows lists each GPU under both when both
+/// backends are in the instance (`WGPU_BACKEND=dx12,vulkan`), and Intel's Vulkan driver made the
+/// whole window flicker black where DX12 and OpenGL didn't; elsewhere there is no DX12 adapter, so
+/// the order is unchanged.
+///
+/// With no `displays`, or none a candidate's PCI ids match (OpenGL reports no device id, Metal no
+/// ids at all), the order is the power preference's alone.
+pub fn adapter_order(candidates: &[Candidate], power: PowerPreference, displays: &[DisplayGpu], named: Option<&str>, skip: &[String]) -> Vec<usize> {
+ let named = named.map(str::to_lowercase).filter(|n| !n.is_empty());
+ let mut order: Vec<(usize, &Candidate)> = candidates.iter().enumerate().filter(|(_, c)| c.presents && !skip.contains(&c.key)).collect();
+ // Stable, so equals keep the system's order.
+ order.sort_by_key(|(_, c)| {
+ let unnamed = named.as_ref().is_some_and(|n| !c.name.to_lowercase().contains(n));
+ let (drives_display, drives_primary) = c.drives(displays);
+ (
+ unnamed,
+ c.device_type == DeviceType::Cpu,
+ c.backend == Backend::Gl,
+ !drives_display,
+ !drives_primary,
+ power_rank(c.device_type, power),
+ c.backend == Backend::Vulkan,
+ )
+ });
+ order.into_iter().map(|(i, _)| i).collect()
+}
+
+/// wgpu's own ranking for a power preference: the preferred kind of GPU, the other kind, unknown,
+/// virtual, software.
+fn power_rank(t: DeviceType, power: PowerPreference) -> u8 {
+ match (power, t) {
+ (PowerPreference::None, _) => 0,
+ (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 0,
+ (_, DeviceType::IntegratedGpu | DeviceType::DiscreteGpu) => 1,
+ (_, DeviceType::Other) => 2,
+ (_, DeviceType::VirtualGpu) => 3,
+ (_, DeviceType::Cpu) => 4,
}
- let bytes = serde_json::to_vec_pretty(record).map_err(std::io::Error::other)?;
- std::fs::write(path, bytes)
}
-/// A start in progress: the backend chosen for it and the record that says so until a frame has
-/// been presented.
-#[derive(Debug)]
+/// The skip list of a [`SKIP_ARG`] argument; `None` for any other argument.
+pub fn skip_arg(arg: &str) -> Option<Vec<String>> {
+ arg.strip_prefix(SKIP_ARG).map(parse_skip)
+}
+
+fn parse_skip(v: &str) -> Vec<String> {
+ v.split(',').map(str::trim).filter(|k| !k.is_empty()).map(String::from).collect()
+}
+
+/// The window's start, shared by [`selector`], [`watch_first_frame`], the app and [`finish`].
+#[derive(Default)]
pub struct Startup {
- pub backend: Backend,
- pub switched_from: Option<Backend>,
- /// `gpu.json`, when the record is persisted.
- path: Option<PathBuf>,
- record: Record,
+ /// What the restart that began this start left out ([`SKIP_ARG`]).
+ skip: Vec<String>,
+ /// The key of the adapter [`selector`] picked.
+ adapter: OnceLock<String>,
+ /// [`selector`] passed over a software renderer.
+ software_left: AtomicBool,
+ /// The UI's context, which counts the frames run.
+ ui: OnceLock<egui::Context>,
+ /// When the app was created, the files named at the start opened: the first frame is due.
+ ready: OnceLock<Instant>,
+ /// The UI thread is in the app's own code ([`Startup::enter`]).
+ busy: AtomicBool,
+ /// How often the UI thread left the app's code: it moves while the thread is alive.
+ leaves: AtomicU64,
+ /// A note for the status bar from [`watch_first_frame`].
+ notice: Mutex<Option<String>>,
+ /// The backend fallback of this start (`gpu.json`); `None` when `WGPU_BACKEND` chooses.
+ fallback: Mutex<Option<backend::Fallback>>,
++ /// Documents the OS handed this run outside its arguments (macOS Apple events), for a start
++ /// again to open: the OS doesn't send them twice.
++ documents: Mutex<Vec<String>>,
}
impl Startup {
- /// Choose the backend for this start and record it in `path` (nothing is recorded without
- /// one). `None` when `WGPU_BACKEND` is set — wgpu follows it and the fallback is off — or the
- /// platform has no candidates.
- pub fn begin(path: Option<PathBuf>, version: &str) -> Option<Startup> {
- if wgpu::Backends::from_env().is_some_and(|b| !b.is_empty()) {
- log::info!("graphics: WGPU_BACKEND is set, wgpu picks the backend and the start-up fallback is off");
- return None;
+ pub fn new(fallback: Option<backend::Fallback>, skip: Vec<String>) -> Self {
+ Self { skip, fallback: Mutex::new(fallback), ..Self::default() }
+ }
+
+ /// The UI thread runs the app's code (`logic`, `ui`): a long wait now is the app being busy,
+ /// never a graphics hang.
+ pub fn enter(&self) {
+ self.busy.store(true, Ordering::Relaxed);
+ }
+
+ /// The UI thread leaves the app's code, to eframe and the graphics stack.
+ pub fn leave(&self) {
+ self.busy.store(false, Ordering::Relaxed);
+ self.leaves.fetch_add(1, Ordering::Relaxed);
+ }
+
++ /// Note documents the OS handed this run outside its arguments, for [`restart`] to pass on.
++ #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
++ pub fn opening(&self, paths: impl IntoIterator<Item = String>) {
++ self.documents.lock().unwrap_or_else(PoisonError::into_inner).extend(paths);
++ }
++
+ /// The note [`watch_first_frame`] left for the status bar, once.
+ pub fn take_notice(&self) -> Option<String> {
+ self.notice.lock().unwrap_or_else(PoisonError::into_inner).take()
+ }
+
+ /// While a backend is left to try, software renderers are passed over ([`SOFTWARE`]).
+ fn software_last(&self) -> bool {
+ !self.skip.iter().any(|k| k == SOFTWARE) && self.with_fallback(|_| ()).is_some()
+ }
+
+ /// The app was created on `ctx`.
+ pub fn created(&self, ctx: &egui::Context) {
+ // Set once; the window is created once.
+ let _ = self.ui.set(ctx.clone());
+ }
+
+ /// The app is ready to draw its first frame.
+ pub fn ready(&self) {
+ // Set once, like `created`.
+ let _ = self.ready.set(Instant::now());
+ }
+
+ /// The first frame was presented, or the app exits normally: no driver fault took this start
+ /// down ([`backend::Fallback::finished`]).
+ pub fn presented(&self) {
+ self.with_fallback(|f| f.finished());
+ }
+
+ /// Clear the record of the backend being tried before starting again (the failure was caught),
+ /// returning it for [`Startup::retry`].
+ fn caught(&self) -> Option<backend::Backend> {
+ self.with_fallback(|f| f.finished()).flatten()
+ }
+
+ /// Starting again failed: the record says this start is still trying `trying`.
+ fn retry(&self, trying: Option<backend::Backend>) {
+ self.with_fallback(|f| f.retry(trying));
+ }
+
+ /// wgpu picked an adapter of `backend` ([`backend::Fallback::started_with`]).
+ pub fn started_with(&self, backend: wgpu::Backend) {
+ if let Some(b) = backend::Backend::of(backend) {
+ self.with_fallback(|f| f.started_with(b));
}
- Self::begin_unforced(path, version)
}
- fn begin_unforced(path: Option<PathBuf>, version: &str) -> Option<Startup> {
- let previous = path.as_deref().map(read).unwrap_or_default();
- let choice = choose(candidates(), &previous, version)?;
- if let Some(p) = &path
- && let Err(e) = write(p, &choice.record)
- {
- log::warn!("graphics: {}: {e}", p.display());
+ /// The status-bar line for a start that moved away from a backend that crashed.
+ pub fn status_line(&self) -> Option<String> {
+ self.with_fallback(|f| f.status_line()).flatten()
+ }
+
+ fn with_fallback<T>(&self, f: impl FnOnce(&mut backend::Fallback) -> T) -> Option<T> {
+ self.fallback.lock().unwrap_or_else(PoisonError::into_inner).as_mut().map(f)
+ }
+}
+
+/// One look at the window's start, every [`WATCH_TICK`].
+#[derive(Clone, Copy, Debug)]
+struct Sample {
+ /// Passes the UI ran; from 2 on, the first frame was presented.
+ frames: u64,
+ /// The UI thread is in the app's own code.
+ busy: bool,
+ /// [`Startup::leaves`].
+ leaves: u64,
+ /// The window is known to be minimized, occluded or without focus: a compositor may hold its
+ /// frames back (a Wayland surface that isn't shown blocks the next frame).
+ hidden: bool,
+}
+
+/// What [`Watch::step`] makes of the window's start.
+#[derive(Debug, PartialEq, Eq)]
+enum Verdict {
+ Wait,
+ /// The first frame was presented: nothing more to watch.
+ Shown,
+ /// The first frame is late: log it and say so, once.
+ Late,
+ /// The UI thread has been stuck in the graphics stack for [`HANG_TIMEOUT`].
+ Hung,
+}
+
+/// The first-frame watch. VectorCraft gives up on an adapter once the first frame is
+/// [`FIRST_FRAME_TIMEOUT`] late. That also fired on healthy starts: a window on a locked screen or
+/// another workspace whose compositor holds its frames back, or a large document composing on a
+/// slow machine. So here a late frame is only reported; the adapter counts as hanging only when the
+/// UI thread is stuck outside the app's code (in eframe, wgpu or the driver), makes no progress at
+/// all for [`HANG_TIMEOUT`], and the window isn't known to be hidden. A busy UI thread, however
+/// long, never counts.
+#[derive(Debug, Default)]
+struct Watch {
+ /// Time waited for the first frame, the window not known to be hidden.
+ waited: Duration,
+ /// Time the UI thread has been stuck outside the app's code without progress.
+ stuck: Duration,
+ leaves: u64,
+ late: bool,
+}
+
+impl Watch {
+ fn step(&mut self, s: Sample, dt: Duration) -> Verdict {
+ if s.frames >= 2 {
+ return Verdict::Shown;
+ }
+ if s.hidden {
+ self.stuck = Duration::ZERO;
+ return Verdict::Wait;
}
- match choice.switched_from {
- Some(from) => log::warn!(
- "graphics: the last start with {} never showed a frame; trying {} (failed so far: {:?})",
- from.name(),
- choice.backend.name(),
- choice.record.failed
- ),
- None => log::info!("graphics: {} (WGPU_BACKEND overrides)", choice.backend.name()),
+ self.waited = self.waited.saturating_add(dt);
+ if s.busy || s.leaves != self.leaves {
+ self.leaves = s.leaves;
+ self.stuck = Duration::ZERO;
+ } else {
+ self.stuck = self.stuck.saturating_add(dt);
+ }
+ if self.stuck >= HANG_TIMEOUT {
+ Verdict::Hung
+ } else if self.waited >= FIRST_FRAME_TIMEOUT && !self.late {
+ self.late = true;
+ Verdict::Late
+ } else {
+ Verdict::Wait
}
- Some(Startup { backend: choice.backend, switched_from: choice.switched_from, path, record: choice.record })
}
+}
+
+/// How often [`watch_first_frame`] looks.
+const WATCH_TICK: Duration = Duration::from_millis(250);
- /// The backends wgpu may use: the chosen one, with OpenGL as the in-process fallback when it
- /// has no adapter (unless OpenGL itself has failed). Not on Windows: some OpenGL drivers
- /// (AMD's) crash while the instance is created (#167), before any fallback could help, so
- /// there OpenGL is only ever tried as its own candidate.
- pub fn backends(&self) -> wgpu::Backends {
- let mut backends = self.backend.bit();
- if !cfg!(windows) && !self.record.failed.contains(&Backend::Gl) {
- backends |= wgpu::Backends::GL;
+/// Watch the window's first frame from another thread, from the app's creation
+/// ([`Startup::ready`]); see [`Watch`]. Each look also asks for a repaint, so a UI thread that is
+/// only idle draws its second frame and ends the watch. When the adapter hangs, start the app again
+/// without it, as [`finish`] does for one that failed, and end this process, whose UI thread is
+/// stuck in the graphics driver.
+pub fn watch_first_frame(startup: Arc<Startup>) {
+ let watch = move || {
+ let mut watch = Watch::default();
+ loop {
+ std::thread::sleep(WATCH_TICK);
+ if startup.ready.get().is_none() {
+ continue;
+ }
+ let ui = startup.ui.get();
+ let hidden = ui.is_some_and(|c| {
+ c.input(|i| {
+ let v = i.viewport();
+ v.minimized == Some(true) || v.occluded == Some(true) || v.focused == Some(false)
+ })
+ });
+ let sample = Sample {
+ frames: ui.map_or(0, egui::Context::cumulative_frame_nr),
+ busy: startup.busy.load(Ordering::Relaxed),
+ leaves: startup.leaves.load(Ordering::Relaxed),
+ hidden,
+ };
+ if let Some(c) = ui {
+ c.request_repaint();
+ }
+ let adapter = startup.adapter.get().map_or("(none)", String::as_str);
+ match watch.step(sample, WATCH_TICK) {
+ Verdict::Wait => continue,
+ Verdict::Shown => return,
+ Verdict::Late => {
+ log::warn!(
+ "the window's first frame hasn't reached the screen in {}s on graphics adapter {adapter}",
+ FIRST_FRAME_TIMEOUT.as_secs()
+ );
+ *startup.notice.lock().unwrap_or_else(PoisonError::into_inner) = Some(format!(
+ "The window took over {} s to show on {adapter}. If it stays black, see the log; WGPU_ADAPTER_NAME or WGPU_POWER_PREF chooses another graphics processor.",
+ FIRST_FRAME_TIMEOUT.as_secs()
+ ));
+ continue;
+ }
+ Verdict::Hung => {}
+ }
+ let mut skip = startup.skip.clone();
+ let Some(failed) = restart_without(true, sample.frames, startup.adapter.get().map(String::as_str), &skip) else { return };
+ log::error!(
+ "the window's first frame didn't reach the screen and the UI thread was stuck in the graphics stack for {}s on graphics adapter {failed}: starting again without it",
+ HANG_TIMEOUT.as_secs()
+ );
+ skip.push(failed.to_string());
+ match restart(&skip, &startup) {
+ Ok(()) => end_hung_process(),
+ Err(e) => {
+ log::error!("starting again failed: {e}");
+ return;
+ }
+ }
}
- backends
+ };
+ if let Err(e) = std::thread::Builder::new().name("first frame".into()).spawn(watch) {
+ log::warn!("no watch on the window's first frame: {e}");
}
+}
- /// wgpu picked an adapter of `backend`: record that one, so a crash is blamed on the backend
- /// that is actually drawing.
- pub fn started_with(&mut self, backend: Backend) {
- if self.record.trying == Some(backend) {
- return;
- }
- self.backend = backend;
- self.record.trying = Some(backend);
- self.save();
+/// End this process from the watch thread while its UI thread is stuck in the graphics driver.
+/// On Windows `exit` runs the DLLs' detach code, which can wait on that thread forever and leave an
+/// invisible process holding the log and the control port, so the process is terminated.
+fn end_hung_process() {
+ log::logger().flush();
+ #[cfg(windows)]
+ if let Err(e) = winsafe::HPROCESS::GetCurrentProcess().TerminateProcess(0) {
+ log::error!("ending the process failed: {e}");
}
+ std::process::exit(0);
+}
- /// A frame has been presented (or the app exited normally): this start did not crash.
- pub fn presented(&mut self) {
- if self.record.trying.take().is_some() {
- self.save();
+/// eframe's adapter choice: the first of [`adapter_order`] for `power`, the GPUs that drive a
+/// `displays`, `WGPU_ADAPTER_NAME` and the adapters a restart left out. Every adapter, the displays
+/// and the choice are logged: which GPU draws is the first question in every black-window report.
+pub fn selector(power: PowerPreference, displays: Vec<DisplayGpu>, startup: Arc<Startup>) -> NativeAdapterSelectorMethod {
+ let named = std::env::var(NAME_ENV).ok();
+ let skip = startup.skip.clone();
+ Arc::new(move |adapters, surface| {
+ let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::new(a, surface)).collect();
+ let order = adapter_order(&candidates, power, &displays, named.as_deref(), &skip);
+ let (order, passed_over) = without_software(order, &candidates, startup.software_last());
+ if passed_over {
+ startup.software_left.store(true, Ordering::Relaxed);
+ log::info!("software renderers passed over while another backend is left to try");
}
+ let listed: Vec<String> = candidates
+ .iter()
+ .map(|c| {
+ let (drives_display, drives_primary) = c.drives(&displays);
+ let note = if !c.presents {
+ ", can't show the window"
+ } else if skip.contains(&c.key) {
+ ", failed before"
+ } else if drives_primary {
+ ", drives the primary display"
+ } else if drives_display {
+ ", drives a display"
+ } else {
+ ""
+ };
+ format!("{} ({:?}, {:?}, {}{note})", c.name.trim(), c.backend, c.device_type, c.key)
+ })
+ .collect();
+ log::info!("graphics adapters: {}", if listed.is_empty() { "none".to_string() } else { listed.join("; ") });
+ let first = order.first().and_then(|&i| adapters.get(i).zip(candidates.get(i)));
+ let Some((adapter, chosen)) = first else {
+ return Err(format!("no graphics adapter can show the window (power preference {power:?}, {} adapters)", adapters.len()));
+ };
+ let why = match chosen.drives(&displays) {
+ (_, true) => "it drives the primary display".to_string(),
+ (true, false) => "it drives a display".to_string(),
+ (false, false) if displays.is_empty() => format!("power preference {power:?}"),
+ (false, false) => format!("no adapter matches a display GPU, so power preference {power:?}"),
+ };
+ log::info!("drawing on {} ({:?}, {:?}): {why}", chosen.name.trim(), chosen.backend, chosen.device_type);
+ // Set once; eframe picks the adapter once.
+ let _ = startup.adapter.set(chosen.key.clone());
+ Ok(adapter.clone())
+ })
+}
+
+/// `order` without software renderers when `software_last`, and whether it dropped any.
+fn without_software(order: Vec<usize>, candidates: &[Candidate], software_last: bool) -> (Vec<usize>, bool) {
+ if !software_last {
+ return (order, false);
}
+ let before = order.len();
+ let order: Vec<usize> = order.into_iter().filter(|&i| candidates.get(i).is_some_and(|c| c.device_type != DeviceType::Cpu)).collect();
+ let dropped = order.len() != before;
+ (order, dropped)
+}
- /// The status-bar line for a start that moved away from a backend that crashed.
- pub fn status_line(&self) -> Option<String> {
- let from = self.switched_from?;
- Some(format!(
- "Graphics: switched from {} to {} — the last start with {} never showed a frame (set WGPU_BACKEND to choose).",
- from.name(),
- self.backend.name(),
- from.name()
- ))
- }
-
- fn save(&self) {
- if let Some(p) = &self.path
- && let Err(e) = write(p, &self.record)
- {
- log::warn!("graphics: {}: {e}", p.display());
+/// The last panic came from the graphics stack (see [`watch_panics`]).
+static GRAPHICS_PANIC: AtomicBool = AtomicBool::new(false);
+
+/// Note whether each panic comes from the graphics stack, so [`finish`] can tell a failing adapter
+/// from a bug. The previous hook still reports it.
+pub fn watch_panics() {
+ let previous = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ GRAPHICS_PANIC.store(info.location().is_some_and(|l| in_graphics_stack(l.file())), Ordering::Relaxed);
+ previous(info);
+ }));
+}
+
+/// A source file of wgpu (`wgpu-core-30.0.1/src/…`, `wgpu-hal-…`), egui-wgpu or naga.
+fn in_graphics_stack(file: &str) -> bool {
+ file.split(['/', '\\']).any(|dir| ["wgpu-", "egui-wgpu-", "naga-"].iter().any(|p| dir.starts_with(p)))
+}
+
+/// The adapter to start again without: the one picked, when the graphics failed while the window
+/// was starting up and it wasn't already left out.
+fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a str>, skip: &[String]) -> Option<&'a str> {
+ picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p))
+}
+
+/// After the window's run: `Ok` when it closed normally or the app started again (see the module
+/// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that
+/// ended it.
+pub fn finish(outcome: Result<eframe::Result, String>, startup: &Startup) -> Result<(), String> {
+ let (why, graphics_failed) = match outcome {
+ Ok(Ok(())) => return Ok(()),
+ Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true),
+ Ok(Err(e)) => (e.to_string(), false),
+ Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)),
+ };
+ let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr);
+ let starting = graphics_failed && frames < STARTUP_FRAMES;
+ let next = if starting {
+ let fallback = startup.with_fallback(|f| (f.backend, f.next_after(&backend::skipped_backends(&startup.skip))));
+ next_start(&startup.skip, startup.adapter.get().map(String::as_str), fallback, startup.software_left.load(Ordering::Relaxed))
+ } else {
+ None
+ };
+ let Some((skip, what)) = next else {
+ return Err(if graphics_failed { format!("{why} ({HELP})") } else { why });
+ };
+ log::error!("the window failed ({why}): starting again {what}");
+ restart(&skip, startup).map_err(|e| format!("{why}; starting again failed: {e}"))
+}
+
+/// The skip list to start again with after the graphics failed while the window was starting up,
+/// and what it changes (for the log); `None` when nothing is left to try. In this order: without the
+/// adapter `picked`; on the next backend (`fallback`: this start's backend and the next one, see
+/// [`backend::Fallback::next_after`]); with software renderers allowed, once, when a start passed
+/// one over (`software_left`, or [`SOFTWARE_LEFT`] in `skip`).
+fn next_start(
+ skip: &[String],
+ picked: Option<&str>,
+ fallback: Option<(backend::Backend, Option<backend::Backend>)>,
+ software_left: bool,
+) -> Option<(Vec<String>, String)> {
+ let mut next = skip.to_vec();
+ if let Some(failed) = restart_without(true, 0, picked, skip) {
+ next.push(failed.to_string());
+ return Some((next, format!("without graphics adapter {failed}")));
+ }
+ let software_left = software_left || skip.iter().any(|k| k == SOFTWARE_LEFT);
+ if let Some((from, Some(to))) = fallback {
+ next.push(from.key().to_string());
+ if software_left && !next.iter().any(|k| k == SOFTWARE_LEFT) {
+ next.push(SOFTWARE_LEFT.to_string());
}
+ return Some((next, format!("with {} (no {} graphics adapter could show the window)", to.name(), from.name())));
+ }
+ if software_left && !skip.iter().any(|k| k == SOFTWARE) {
+ // Every backend again, now with their software renderers; the adapters that failed stay out.
+ next.retain(|k| k != SOFTWARE_LEFT && backend::Backend::from_key(k).is_none());
+ next.push(SOFTWARE.to_string());
+ return Some((next, "on a software renderer (no graphics processor could show the window)".to_string()));
+ }
+ None
+}
+
- /// Start the app again with the same arguments and the skip list `skip` ([`SKIP_ARG`]). On Unix
++/// Start the app again with the same arguments, the documents the OS handed this run
++/// ([`Startup::opening`]) and the skip list `skip` ([`SKIP_ARG`]). On Unix
+/// the new app replaces this process (same process id, so an AppImage keeps its files mounted),
+/// and this returns only on failure; on Windows it starts beside this one, which then exits. The
+/// failure was caught, so `gpu.json` stops blaming the backend first, and blames it again when
+/// starting again fails.
+fn restart(skip: &[String], startup: &Startup) -> std::io::Result<()> {
+ log::logger().flush();
+ let mut c = std::process::Command::new(std::env::current_exe()?);
+ c.args(std::env::args_os().skip(1).filter(|a| a.to_str().is_none_or(|a| skip_arg(a).is_none())));
++ c.args(startup.documents.lock().unwrap_or_else(PoisonError::into_inner).iter());
+ c.arg(format!("{SKIP_ARG}{}", skip.join(",")));
+ let trying = startup.caught();
+ #[cfg(unix)]
+ let result = {
+ use std::os::unix::process::CommandExt as _;
+ Err(c.exec())
+ };
+ #[cfg(not(unix))]
+ let result = c.spawn().map(|_| ());
+ if result.is_err() {
+ startup.retry(trying);
}
+ result
}
#[cfg(test)]
diff --cc apps/designcraft/src/main.rs
index 0b527f095,465cd250f..2bfc959e6
--- a/apps/designcraft/src/main.rs
+++ b/apps/designcraft/src/main.rs
@@@ -26,8 -26,11 +28,11 @@@ struct App
app: DesignApp,
#[cfg(target_os = "macos")]
menu: Option<native_menu::NativeMenu>,
+ /// The window's start: the adapter and backend chosen for it; see `gpu`.
+ startup: std::sync::Arc<gpu::Startup>,
+ /// Documents and quit requests from Finder, the Dock and Open With.
+ #[cfg(target_os = "macos")]
+ apple_events: fmv_macos_events::Inbox,
- /// The graphics start in progress (`gpu.json`) until a frame has been presented; see `gpu`.
- startup: Option<gpu::Startup>,
/// Frames begun so far.
frames: u32,
}
@@@ -52,9 -54,9 +57,11 @@@ impl eframe::App for App
if let Some(m) = &mut self.menu {
m.poll(&mut self.app, ctx);
}
- apple_events::poll(&self.apple_events, &mut self.app, ctx);
++ // Noted for a start again after a graphics failure, which reopens them (`gpu::restart`).
++ self.startup.opening(apple_events::poll(&self.apple_events, &mut self.app, ctx));
}
self.app.logic(ctx);
+ self.startup.leave();
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(raw);
@@@ -200,10 -187,11 +207,12 @@@ fn open_filters(purpose: &str) -> &'sta
OpenFilter { name: "Video and sound", extensions: &["mp4", "m4v", "mov", "webm", "mp3", "m4a", "wav", "ogg"] },
],
_ => &[
- OpenFilter { name: "DesignCraft or IDML", extensions: &["designcraft", "idml"] },
+ OpenFilter { name: "DesignCraft, IDML or InDesign", extensions: &["designcraft", "idml", "indd", "indt"] },
OpenFilter { name: "DesignCraft", extensions: &["designcraft"] },
OpenFilter { name: "InDesign Markup (IDML)", extensions: &["idml"] },
+ OpenFilter { name: "InDesign document or template (INDD, INDT)", extensions: &["indd", "indt"] },
+ // Files saved without an extension; `file.open` tells the formats apart by content.
+ OpenFilter { name: "All files", extensions: &[ALL_FILES] },
],
}
}
@@@ -217,10 -259,9 +280,10 @@@ fn services() -> Services
}
dialog.pick_file().map(|p| p.to_string_lossy().to_string())
})),
- pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),
+ pick_save: Some(Box::new(pick_save)),
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
+ clipboard_text: Some(Box::new(|| arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok())),
..Default::default()
}
}
@@@ -338,86 -351,62 +401,97 @@@ fn main() -> std::process::ExitCode
b.with_x11();
}));
}
+ // 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 apple_events = &apple_events;
- 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);
++ 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 = designcraft_engine::recovery::default_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();
+ 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,
- #[cfg(target_os = "macos")]
- apple_events: apple_events.connect(&cc.egui_ctx),
- 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)]
@@@ -444,8 -433,19 +518,21 @@@ mod tests
assert!(place.len() > 1, "the place dialog keeps a filter for each kind of file");
assert!(place.iter().any(|filter| filter.extensions.contains(&"png")));
let documents = super::open_filters("");
- assert!(documents.first().is_some_and(|filter| filter.extensions == ["designcraft", "idml"]));
+ for ext in ["designcraft", "idml", "indd", "indt"] {
+ assert!(documents.first().is_some_and(|filter| filter.extensions.contains(&ext)), "{ext} is missing from the first Open filter");
+ }
+ assert!(documents.last().is_some_and(|filter| filter.extensions == [super::ALL_FILES]), "files without an extension can be picked");
+ }
+
+ #[test]
+ fn save_dialog_answers_get_the_suggested_extension() {
+ use std::path::PathBuf;
+ let save = |picked: &str, name: &str| super::picked_save_path(PathBuf::from(picked), super::suggested_extension(name));
+ assert_eq!(save("/d/Brochure", "Untitled.designcraft"), PathBuf::from("/d/Brochure.designcraft"));
+ assert_eq!(save("/d/Brochure.idml", "Untitled.designcraft"), PathBuf::from("/d/Brochure.idml.designcraft"));
+ assert_eq!(save("/d/Brochure.designcraft", "Untitled.designcraft"), PathBuf::from("/d/Brochure.designcraft"));
+ assert_eq!(save("/d/Brochure", "Untitled.pdf"), PathBuf::from("/d/Brochure.pdf"));
+ assert_eq!(save("/d/Brochure.txt", "Untitled.rtf"), PathBuf::from("/d/Brochure.txt"), "another export format is kept");
+ assert_eq!(save("/d/Package", "Untitled 1.2 Folder"), PathBuf::from("/d/Package"), "a folder has no extension");
}
}
diff --cc crates/engine/src/cmd/file.rs
index bd6d5f66c,1158809d7..8003d182c
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -13,39 -13,19 +13,40 @@@ 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, .idml, or an InDesign .indd/.indt (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 and, for IDML and InDesign files, package parts missing}",
- "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing); 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 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", 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.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}")))?;
@@@ -242,10 -176,17 +259,17 @@@ fn file_open(s: &mut Session, p: &Value
let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
#[cfg(not(target_arch = "wasm32"))]
{
- if path.to_ascii_lowercase().ends_with(".idml") || super::interchange::has_indd_extension(path) {
- if path.to_ascii_lowercase().ends_with(".idml") {
- return super::interchange::open_idml(s, p);
- }
+ let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- // The content decides: a file's extension may be missing or wrong.
- if designcraft_idml::is_idml(&bytes) {
++ // The content decides first: a file's extension may be missing or wrong. The extension
++ // then routes files whose content isn't recognised to the reader that explains why.
++ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase();
++ let native = designcraft_format::is_designcraft(&bytes) || bytes.trim_ascii_start().starts_with(b"{");
++ if designcraft_idml::is_idml(&bytes) || (!native && (super::interchange::is_indd(path, &bytes) || ext == "idml")) {
return super::interchange::open_idml(s, p);
}
- let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- if !bytes.starts_with(b"PK") && !bytes.trim_ascii_start().starts_with(b"{") {
++ if !native && ext != designcraft_format::EXTENSION {
+ return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file")));
+ }
let mut d = from_bytes(&bytes)?;
super::interchange::resolve_packaged_links(&mut d, std::path::Path::new(path).parent());
super::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path)));
@@@ -1168,24 -964,61 +1193,81 @@@ 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);
+ }
+ }
diff --cc crates/engine/src/cmd/mod.rs
index 35c90ef56,3b1d11a02..a5fd9a2fc
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@@ -305,6 -299,5 +305,6 @@@ 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, to_bytes};
+ pub use file::{base64_decode, base64_encode, from_bytes, is_document, to_bytes, with_document_extension};
+pub use layout::chapter_numbering;
pub(crate) use place_text::autoflow as place_text_autoflow;