Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Persist default workspace mode for newly opened PDFs (#172)

Blake Gower54df6b933e4f
diff --git a/ROADMAP.md b/ROADMAP.md
index 5f9e5ece1..ef2694750 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -128,6 +128,8 @@ M0 → M1 → M2 → M3 → M4 must happen in order. After M4, M5–M12 can run
Newest first. One line per session: the date, what moved, and the new overall percentage.
- **2026-10-07 (session 16):** PrintCraft is renamed PdfCraft: repo `storytold/pdfcraft`, crates and binaries `pdfcraft*`, bundle id `ai.storyteller.pdfcraft`. On first launch the app moves the old PrintCraft settings and crash-recovery folders to the new name, so upgrades keep recent files, preferences and unsaved work. No feature change. ≈ 30–35%.
+- **2026-10-07 (fork, default-workspace-mode):** Preferences ▸ Documents and view remembers the workspace used for newly opened PDFs. All Tools remains the default; explicit CLI/control mode overrides last for the session and PDF Initial View metadata stays independent. Overall estimate unchanged (≈ 30–35%).
+
- **2026-10-07 (session 15):** Five community issues, each with a regression test: in two-page view, Next page moves a whole spread (#77, #70); Export to Word opens in Word again, with control characters dropped and receipt-length pages kept within Word's 22 in, checked in Microsoft Word (#78, #72); macOS opens PDFs from Finder, Open With and the Dock (Apple events through the audited `fmv-macos-events`, PDF declared in the Info.plist), and the packaging no longer describes the image editor it was copied from (#82, #73); Add text keeps the box being typed when you click elsewhere, with Done and Discard beside it, reproduced and checked with real OS input (#86, #74); sharper, higher-contrast text, most visible on Windows, with every text colour at WCAG AA in both themes (#84, #76; the console window was already gone in 0.2.1). Still open: #79 (layered "not verified" signature appearances), #80 (native macOS menu bar), #81 (Homebrew and Scoop). P0 88%, P1 53%; 805 features 50.2% shipped (53.7% weighted). ≈ 30–35%.
- **2026-10-06 (community navigation):** Linux-only middle-button vertical scrolling in the document and Organize grid, toggled by clicking the wheel, with cancellation that protects page tools and selection. Scrolling stays on after releasing the wheel, even if the pointer moved before release. Manual feedback led to a Chromium-style distance^2.2 speed curve, a 15-screen-point dead zone, and continuous redraws that use elapsed frame time; the former linear speed cap is removed. Headless UI/control regressions cover fractional movement, consistent travel at 30/60/120/144 fps, pause/resume and cancellation. Other platforms retain their existing middle-button input behavior, with a regression that checks the custom scroller neither blocks input nor changes the cursor or consumes Escape. No new dependency. Automatic scrolling remains partial because keyboard-started timed scrolling is absent. Overall effort estimate remains ≈ 30–35%.
- **2026-10-06 (session 14):** Issues: move and resize existing text boxes in Edit text (#59, closes #40); Windows release builds open no console window and the Start Menu shortcut has its icon (#58, #57; rolled out to every Craft app); native Windows ARM64 installers, installed and run on an ARM64 runner in CI (#66, #71; the intermittent ARM64 test crash was a WARP shader-JIT race between parallel GPU-rendering tests, not our code); XFA forms are detected and explained instead of failing silently (#65, #60 stays open for real XFA). Also: squiggly underline tool, comment opacity, Preferences ▸ Identity, drag-and-drop/hover tests; community table export to Word/HTML/RTF (#62, with linear-time detection and a column cap). #63 (timestamps/LTV with outbound network) held for review fixes and an owner decision on network access. ≈ 30–35% (unchanged).
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index 71b347604..a0aa3cb20 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -119,14 +119,7 @@ pub fn mode_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
[(Mode::AllTools, "All tools"), (Mode::Read, "Read"), (Mode::Edit, "Edit"), (Mode::Convert, "Convert"), (Mode::Sign, "E-Sign")]
{
if widgets::mode_tab(ui, label, app.mode == mode).clicked() {
- app.mode = mode;
- app.left_open = true;
- app.left = match mode {
- Mode::Edit => crate::LeftPanel::Tool("edit"),
- Mode::Convert => crate::LeftPanel::Tool("export"),
- Mode::Sign => crate::LeftPanel::Tool("fill_sign"),
- _ => crate::LeftPanel::AllTools,
- };
+ app.select_mode(mode);
}
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 697560887..e9d8e4367 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -23,7 +23,9 @@
//! comments, selecting text, moving comments). `ui.state` reports `pages_on_screen` to aim at.
//! - `ui.type {text}`, `ui.key {key, modifiers?}`: keyboard input to the focused widget / app.
//! - `ui.command {id}`: run a registry command (as the menu would). `ui.commands` lists them.
-//! - `ui.set {key, value}`: the view options of the command line (`--page`, `--zoom`, …).
+//! - `ui.set {key, value}`: view options (`--page`, `--zoom`, …), plus persistent preferences.
+//! `default-mode=all|read|edit|convert|sign` applies to future PDF opens; `mode` overrides it
+//! for this session without changing the saved preference. `ui.state.default_mode` reports it.
//! - `ui.open {path}`: open a file.
//! - `ui.screenshot {region?}`: PNG of the window (base64), optionally cropped to a rect.
@@ -578,6 +580,7 @@ impl Host for crate::PdfCraftApp {
},
"home": self.active.is_none(),
"mode": format!("{:?}", self.mode),
+ "default_mode": self.default_mode,
"left_panel": if self.left_open { json!(format!("{:?}", self.left)) } else { Value::Null },
"right_panel": self.right.map(|r| format!("{r:?}")),
"dialog": self.dialog.map(|d| format!("{d:?}")),
diff --git a/crates/ui-egui/src/js_ui.rs b/crates/ui-egui/src/js_ui.rs
index 1c5893163..5209c4c42 100644
--- a/crates/ui-egui/src/js_ui.rs
+++ b/crates/ui-egui/src/js_ui.rs
@@ -231,6 +231,25 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
});
});
ui.add_space(8.0);
+ ui.label(egui::RichText::new(app.language.tr("Documents and view")).font(theme::semibold(13.0)));
+ ui.horizontal(|ui| {
+ ui.label(app.language.tr("Default workspace mode"));
+ for (mode, label) in [
+ (crate::Mode::AllTools, "All Tools"),
+ (crate::Mode::Read, "Read"),
+ (crate::Mode::Edit, "Edit"),
+ (crate::Mode::Convert, "Convert"),
+ (crate::Mode::Sign, "E-Sign"),
+ ] {
+ ui.radio_value(&mut app.default_mode, mode, app.language.tr(label));
+ }
+ });
+ ui.label(
+ egui::RichText::new(app.language.tr("Used when opening PDFs. An explicit launch or control mode takes precedence for the session."))
+ .small()
+ .color(t.text_muted),
+ );
+ ui.add_space(8.0);
// Identity: the author of new comments (Acrobat: Preferences ▸ Identity).
ui.label(egui::RichText::new(app.language.tr("Identity")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index c187c996b..d3877d624 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -77,8 +77,10 @@ pub use recovery::{AUTOSAVE_SECS, RecoveryMeta, RecoveryStore};
use theme::ThemeKind;
/// Top-level workspace modes (Acrobat's mode bar).
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "lowercase")]
pub enum Mode {
+ #[serde(rename = "all")]
AllTools,
Read,
Edit,
@@ -86,6 +88,19 @@ pub enum Mode {
Sign,
}
+impl Mode {
+ fn parse(value: &str) -> Option<Self> {
+ match value {
+ "all" => Some(Self::AllTools),
+ "read" => Some(Self::Read),
+ "edit" => Some(Self::Edit),
+ "convert" => Some(Self::Convert),
+ "sign" => Some(Self::Sign),
+ _ => None,
+ }
+ }
+}
+
/// What the left panel shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeftPanel {
@@ -289,6 +304,10 @@ pub struct PdfCraftApp {
/// `None` shows the Home tab.
pub active: Option<usize>,
pub mode: Mode,
+ /// Workspace used for newly opened PDFs; independent of PDF Initial View metadata.
+ pub default_mode: Mode,
+ /// Explicit CLI/control mode lasts for this session and is never persisted.
+ mode_override: Option<Mode>,
pub left: LeftPanel,
pub left_open: bool,
pub right: Option<RightPanel>,
@@ -496,6 +515,8 @@ impl PdfCraftApp {
views: Vec::new(),
active: None,
mode: Mode::AllTools,
+ default_mode: Mode::AllTools,
+ mode_override: None,
left: LeftPanel::AllTools,
left_open: true,
right: None,
@@ -678,6 +699,16 @@ impl PdfCraftApp {
self.views.push(DocView::new(id, &doc.info));
self.active = Some(self.views.len() - 1);
self.apply_initial_view(self.views.len() - 1, &initial);
+ if let Some(mode) = self.mode_override {
+ // Explicit mode options do not reset independent --tool / --left choices.
+ self.mode = mode;
+ } else if self.mode != self.default_mode {
+ // Switch workspace like the mode bar, but a left panel the user (or `--left closed`)
+ // closed stays closed, and an unchanged mode keeps the tool panel the user chose.
+ let left_open = self.left_open;
+ self.select_mode(self.default_mode);
+ self.left_open = left_open;
+ }
if let Some(p) = path {
self.recent.retain(|r| r.path != p);
self.recent.insert(0, RecentFile { name: name.to_string(), path: p, pages, size });
@@ -896,12 +927,25 @@ impl PdfCraftApp {
self.notify(format!("`{command}` {when}"));
}
+ /// Select the workspace and its matching tool panel, just like the mode bar.
+ pub(crate) fn select_mode(&mut self, mode: Mode) {
+ self.mode = mode;
+ self.left_open = true;
+ self.left = match mode {
+ Mode::Edit => LeftPanel::Tool("edit"),
+ Mode::Convert => LeftPanel::Tool("export"),
+ Mode::Sign => LeftPanel::Tool("fill_sign"),
+ _ => LeftPanel::AllTools,
+ };
+ }
+
/// Serialize the user's persistent state (recent files, theme). Local only.
pub fn persist(&self) -> String {
let trusted: Vec<String> = self.session.trusted_certificates().iter().map(pdfcraft_engine::sign::x509::to_pem).collect();
serde_json::json!({
"recent": self.recent,
"theme": self.theme,
+ "default_mode": self.default_mode,
"language": self.language,
"author": self.comment_prefs.author,
// Drawn signatures keep their original form (older settings read the same).
@@ -930,6 +974,9 @@ impl PdfCraftApp {
if let Ok(t) = serde_json::from_value::<ThemeKind>(v["theme"].clone()) {
self.theme = t;
}
+ if let Ok(mode) = serde_json::from_value::<Mode>(v["default_mode"].clone()) {
+ self.default_mode = mode;
+ }
if let Ok(language) = serde_json::from_value::<i18n::Language>(v["language"].clone()) {
self.language = language;
}
@@ -998,13 +1045,12 @@ impl PdfCraftApp {
}
}
("mode", _) => {
- self.mode = match value {
- "read" => Mode::Read,
- "edit" => Mode::Edit,
- "convert" => Mode::Convert,
- "sign" => Mode::Sign,
- _ => Mode::AllTools,
- }
+ let mode = Mode::parse(value).unwrap_or(Mode::AllTools);
+ self.mode_override = Some(mode);
+ self.mode = mode;
+ }
+ ("default-mode", _) => {
+ self.default_mode = Mode::parse(value).ok_or("default-mode must be all, read, edit, convert or sign")?;
}
("tool", _) => {
let g = pdfcraft_engine::catalog::group(value).ok_or_else(|| format!("unknown tool {value}"))?;
diff --git a/crates/ui-egui/tests/control.rs b/crates/ui-egui/tests/control.rs
index f510ed30f..fe38a6c8b 100644
--- a/crates/ui-egui/tests/control.rs
+++ b/crates/ui-egui/tests/control.rs
@@ -544,3 +544,16 @@ fn loopback_transport_requires_the_token() {
assert_eq!(good[1]["result"]["documents"][0]["name"], "doc.pdf");
assert!(good[2]["error"]["message"].as_str().unwrap().contains("disabled"));
}
+
+#[test]
+fn control_default_workspace_and_session_override() {
+ let (mut h, c) = harness();
+ ok(&mut h, &c, "ui.set", json!({"key": "default-mode", "value": "edit"}));
+ assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["default_mode"], "edit");
+ assert!(call(&mut h, &c, "ui.set", json!({"key": "default-mode", "value": "unknown"})).is_err());
+ h.state_mut().open_bytes("next.pdf", None, fixture(1)).unwrap();
+ assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["mode"], "Edit");
+ ok(&mut h, &c, "ui.set", json!({"key": "mode", "value": "read"}));
+ h.state_mut().open_bytes("another.pdf", None, fixture(1)).unwrap();
+ assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["mode"], "Read");
+}
diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs
index e5547f602..3ee9dc5fd 100644
--- a/crates/ui-egui/tests/ui.rs
+++ b/crates/ui-egui/tests/ui.rs
@@ -260,3 +260,119 @@ fn files_and_quit_from_the_operating_system() {
let closing = h.output().viewport_output.values().any(|v| v.commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close)));
assert!(closing);
}
+
+#[test]
+fn default_workspace_mode_persists_and_tolerates_invalid_settings() {
+ use pdfcraft_ui_egui::Mode;
+ for mode in [Mode::AllTools, Mode::Read, Mode::Edit, Mode::Convert, Mode::Sign] {
+ let mut app = PdfCraftApp::new();
+ app.default_mode = mode;
+ app.set_option("mode", "sign").unwrap();
+ let mut restored = PdfCraftApp::new();
+ restored.restore(&app.persist());
+ assert_eq!(restored.default_mode, mode);
+ restored.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(restored.mode, mode, "session override must not be persisted");
+ }
+ for json in ["{}", "{not json", r#"{"default_mode": null}"#, r#"{"default_mode": 5}"#, r#"{"default_mode": "unknown"}"#] {
+ let mut app = PdfCraftApp::new();
+ app.restore(json);
+ assert_eq!(app.default_mode, Mode::AllTools);
+ app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.mode, Mode::AllTools);
+ }
+}
+
+#[test]
+fn newly_opened_pdfs_use_the_default_workspace() {
+ use pdfcraft_ui_egui::{LeftPanel, Mode};
+ let mut app = PdfCraftApp::new();
+ app.restore(r#"{"default_mode": "edit"}"#);
+ app.open_bytes("first.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.mode, Mode::Edit);
+ assert_eq!(app.left, LeftPanel::Tool("edit"));
+ app.default_mode = Mode::Read;
+ assert_eq!(app.mode, Mode::Edit, "changing the preference affects future opens");
+ app.open_bytes("second.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.mode, Mode::Read);
+ // PDF Initial View is independent of the workspace preference.
+ let pdf =
+ String::from_utf8(FIXTURE.to_vec()).unwrap().replace("/Outlines 6 0 R", "/Outlines 6 0 R /PageLayout /TwoColumnLeft /PageMode /UseOutlines");
+ app.open_bytes("initial-view.pdf", None, pdf.into_bytes()).unwrap();
+ assert_eq!(app.mode, Mode::Read);
+ assert_eq!(app.views.last().unwrap().layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp);
+ assert_eq!(app.right, Some(pdfcraft_ui_egui::RightPanel::Bookmarks));
+}
+
+#[test]
+fn explicit_mode_overrides_default_before_and_after_open() {
+ use pdfcraft_ui_egui::Mode;
+ for before in [false, true] {
+ for (value, mode) in [("all", Mode::AllTools), ("read", Mode::Read), ("edit", Mode::Edit), ("convert", Mode::Convert), ("sign", Mode::Sign)] {
+ let mut app = PdfCraftApp::new();
+ app.default_mode = Mode::Read;
+ if before {
+ app.set_option("mode", value).unwrap();
+ }
+ app.open_bytes("first.pdf", None, FIXTURE.to_vec()).unwrap();
+ if !before {
+ // Desktop startup applies CLI options after the initial files open.
+ app.set_option("mode", value).unwrap();
+ }
+ assert_eq!(app.mode, mode);
+ app.set_option("default-mode", "edit").unwrap();
+ app.open_bytes("second.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.mode, mode);
+ assert_eq!(app.default_mode, Mode::Edit);
+ }
+ }
+}
+
+#[test]
+fn preferences_selects_default_workspace_for_next_open() {
+ use egui::accesskit::Role;
+ use pdfcraft_ui_egui::Mode;
+ let mut h = harness(|app| app.set_option("dialog", "preferences").unwrap());
+ h.get_by_label("Default workspace mode");
+ h.get_by_role_and_label(Role::RadioButton, "Read").click();
+ h.run_steps(2);
+ assert_eq!(h.state().default_mode, Mode::Read);
+ assert_eq!(h.state().mode, Mode::AllTools);
+ h.get_by_label("OK").click();
+ h.run_steps(2);
+ h.state_mut().open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(h.state().mode, Mode::Read);
+}
+
+#[test]
+fn explicit_mode_preserves_independent_tool_and_panel_options() {
+ use pdfcraft_ui_egui::LeftPanel;
+ let mut app = PdfCraftApp::new();
+ app.set_option("tool", "export").unwrap();
+ app.set_option("left", "closed").unwrap();
+ app.set_option("mode", "edit").unwrap();
+ assert_eq!(app.left, LeftPanel::Tool("export"));
+ assert!(!app.left_open);
+ app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.left, LeftPanel::Tool("export"));
+ assert!(!app.left_open);
+}
+
+#[test]
+fn opening_a_pdf_keeps_a_closed_left_panel_and_the_chosen_tool() {
+ use pdfcraft_ui_egui::{LeftPanel, Mode};
+ // `--left closed` without `--mode`, default workspace Edit: the panel stays closed.
+ let mut app = PdfCraftApp::new();
+ app.default_mode = Mode::Edit;
+ app.set_option("left", "closed").unwrap();
+ app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.mode, Mode::Edit);
+ assert!(!app.left_open);
+ // Default All Tools: opening another PDF leaves the tool panel the user picked.
+ let mut app = PdfCraftApp::new();
+ app.set_option("tool", "export").unwrap();
+ app.open_bytes("first.pdf", None, FIXTURE.to_vec()).unwrap();
+ app.open_bytes("second.pdf", None, FIXTURE.to_vec()).unwrap();
+ assert_eq!(app.mode, Mode::AllTools);
+ assert_eq!(app.left, LeftPanel::Tool("export"));
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index b445b5eca..9e33ad213 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -9662,8 +9662,8 @@ milestone = "M14"
status = "partial"
commands = ["app.preferences"]
tools = ["js_enabled"]
-evidence = ["crates/ui-egui/tests/javascript.rs::document_scripts_and_preferences"]
-notes = "Preferences dialog with Interface language, Identity and JavaScript; other categories still live in their tools, and it isn't generated from a schema yet."
+evidence = ["crates/ui-egui/tests/javascript.rs::document_scripts_and_preferences", "crates/ui-egui/tests/ui.rs::preferences_selects_default_workspace_for_next_open", "crates/ui-egui/tests/control.rs::control_default_workspace_and_session_override"]
+notes = "Preferences dialog with Interface language, Documents and view (persistent default workspace with session override), Identity and JavaScript; other categories still live in their tools, and it isn't generated from a schema yet."
[[feature]]
id = "misc.prefs-general"