Skip to content

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

Open: programmatic callers see focus vs open vs failure (#1620)

Eduardo Soares305a5676ce67
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index bba7108c0..5f43f6c7f 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -33,7 +33,8 @@
//! for this session without changing the saved preference. `ui.state.default_mode` reports it.
//! `theme=light|dark|system` changes the saved theme preference; `ui.state.theme_preference`
//! reports the choice and `ui.state.theme` reports the resolved light/dark colours.
-//! - `ui.open {path}`: open a file.
+//! - `ui.open {path}`: open a file. A file whose tab is already open focuses it
+//! (`"focused": true`) instead of adding a tab; only a failed open replies `Err`.
//! - `ui.screenshot {region?}`: PNG of the window (base64), optionally cropped to a rect.
use std::collections::{HashMap, VecDeque};
@@ -735,12 +736,10 @@ impl Host for crate::PdfCraftApp {
#[cfg(not(target_arch = "wasm32"))]
fn open(&mut self, path: &str) -> Reply {
- let before = self.views.len();
- self.open_path(path);
- if self.views.len() > before || self.password_prompt.is_some() {
- Ok(json!({ "opened": path, "password_prompt": self.password_prompt.is_some() }))
- } else {
- Err(self.toast.as_ref().map(|t| t.0.clone()).unwrap_or_else(|| format!("couldn't open {path}")))
+ match self.open_path(path) {
+ crate::OpenOutcome::Opened => Ok(json!({ "opened": path, "password_prompt": self.password_prompt.is_some() })),
+ crate::OpenOutcome::Focused => Ok(json!({ "opened": path, "focused": true })),
+ crate::OpenOutcome::Failed => Err(self.toast.as_ref().map(|t| t.0.clone()).unwrap_or_else(|| format!("couldn't open {path}"))),
}
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index d7f33abbc..afb19f5e5 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -734,6 +734,19 @@ fn rgb_triple(v: &serde_json::Value) -> Option<[f64; 3]> {
Some(out)
}
+/// What [`PdfCraftApp::open_path`] did: opened the file in a new tab, focused the tab already
+/// showing it, or failed. Failures tell the user through a toast; this is the programmatic
+/// contract for callers that must know (the control channel, tools that wait for a file) (#1620).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OpenOutcome {
+ /// The file opened in a new tab (or raised its password prompt).
+ Opened,
+ /// A tab already showed the file; it was focused and no tab was added.
+ Focused,
+ /// The file could not be read or opened; the user was told.
+ Failed,
+}
+
impl PdfCraftApp {
pub fn new() -> Self {
Self {
@@ -1208,6 +1221,8 @@ impl PdfCraftApp {
self.open_path(path);
}
}
+ #[cfg(target_arch = "wasm32")]
+ let _ = path;
}
/// The tab already showing the file at `path`, if any: its position in `views`. Paths are
@@ -1222,20 +1237,25 @@ impl PdfCraftApp {
}
#[cfg(not(target_arch = "wasm32"))]
- pub fn open_path(&mut self, path: &str) {
+ pub fn open_path(&mut self, path: &str) -> OpenOutcome {
if let Some(i) = self.view_showing(path) {
self.startup_superseded = true;
self.active = Some(i);
- return;
+ return OpenOutcome::Focused;
}
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string());
match std::fs::read(path) {
- Ok(bytes) => {
- if let Err(e) = self.open_bytes(&name, Some(path.to_string()), bytes) {
+ Ok(bytes) => match self.open_bytes(&name, Some(path.to_string()), bytes) {
+ Ok(()) => OpenOutcome::Opened,
+ Err(e) => {
self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e.to_string())]);
+ OpenOutcome::Failed
}
+ },
+ Err(e) => {
+ self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]);
+ OpenOutcome::Failed
}
- Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]),
}
}
@@ -1437,12 +1457,12 @@ impl PdfCraftApp {
let command = spec.id;
self.ask_one(pickers::Ask::File(dialog), None, move |app, path| {
let path = path.to_string_lossy().into_owned();
- let before = app.views.len();
- app.open_path(&path);
+ let outcome = app.open_path(&path);
if let Some(prompt) = app.password_prompt.as_mut().filter(|p| p.path.as_deref() == Some(path.as_str())) {
// Encrypted: the tool runs once the password is in.
prompt.then = Some(command);
- } else if app.views.len() > before && app.active.is_some() {
+ } else if outcome != OpenOutcome::Failed {
+ // A new tab or an already-open one the pick focused: either way, run on it.
app.execute(command);
}
});
@@ -2225,7 +2245,9 @@ impl eframe::App for PdfCraftApp {
for e in os_events {
match e {
#[cfg(not(target_arch = "wasm32"))]
- OsEvent::Open(paths) => paths.iter().for_each(|p| self.open_path(p)),
+ OsEvent::Open(paths) => paths.iter().for_each(|p| {
+ self.open_path(p);
+ }),
#[cfg(target_arch = "wasm32")]
OsEvent::Open(_) => {}
// Like closing the window: `guard_quit` asks about unsaved changes.
diff --git a/crates/ui-egui/src/pickers.rs b/crates/ui-egui/src/pickers.rs
index dcb012089..39b38d645 100644
--- a/crates/ui-egui/src/pickers.rs
+++ b/crates/ui-egui/src/pickers.rs
@@ -151,7 +151,9 @@ impl PdfCraftApp {
};
let ask = if multiple { Ask::Files(dialog) } else { Ask::File(dialog) };
self.ask(ask, target, move |app, paths| match pick_for {
- PickFor::Open => paths.iter().for_each(|p| app.open_path(&p.to_string_lossy())),
+ PickFor::Open => paths.iter().for_each(|p| {
+ app.open_path(&p.to_string_lossy());
+ }),
PickFor::Files(purpose) => app.use_paths(purpose, &paths),
});
}
diff --git a/crates/ui-egui/tests/commands.rs b/crates/ui-egui/tests/commands.rs
index 48a18eb42..8674c8810 100644
--- a/crates/ui-egui/tests/commands.rs
+++ b/crates/ui-egui/tests/commands.rs
@@ -187,6 +187,33 @@ fn a_tool_chosen_with_no_document_asks_for_one_and_runs_on_it() {
let _ = std::fs::remove_dir_all(&dir);
}
+#[test]
+fn a_tool_chosen_with_an_already_open_file_focuses_its_tab_and_still_runs() {
+ let dir = std::env::temp_dir().join(format!("pdfcraft-tool-focus-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("picked.pdf");
+ std::fs::write(&path, fixture(2)).unwrap();
+ let pick = path.to_string_lossy().into_owned();
+ let picked = pick.clone();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ // The file is already open, but the Home tab is showing (no active document).
+ app.open_path(&picked);
+ app.active = None;
+ app.pick_override = Some(vec![pick]);
+ app
+ });
+ h.run_steps(2);
+ h.state_mut().run_command("export.text");
+ h.run_steps(3);
+ let app = h.state();
+ assert_eq!(app.views.len(), 1, "the existing tab is reused, not duplicated");
+ assert_eq!(app.active, Some(0), "the pick focused the tab it already opened");
+ assert!(matches!(app.dialog, Some(Dialog::Export(_))), "the tool still runs on it: {:?}", app.dialog);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
#[test]
fn shortcuts_run_registered_commands() {
let mut h = harness();
diff --git a/crates/ui-egui/tests/control.rs b/crates/ui-egui/tests/control.rs
index 180dc85e6..7f1d27a76 100644
--- a/crates/ui-egui/tests/control.rs
+++ b/crates/ui-egui/tests/control.rs
@@ -1427,3 +1427,38 @@ fn read_mode_retains_existing_rail_click_to_close_policy() {
assert_eq!(h.state().right, None);
assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Read);
}
+
+#[test]
+fn control_open_of_an_already_open_file_replies_ok_and_focuses_its_tab() {
+ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let a = dir.join("a.pdf").to_string_lossy().into_owned();
+ let b = dir.join("b.pdf").to_string_lossy().into_owned();
+ std::fs::write(&a, fixture(2)).unwrap();
+ std::fs::write(&b, fixture(3)).unwrap();
+ let slot: Arc<Mutex<Option<ControlClient>>> = Arc::default();
+ let s = slot.clone();
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ *s.lock().unwrap() = Some(app.attach_control(&cc.egui_ctx));
+ app
+ });
+ h.run_steps(4);
+ let c = slot.lock().unwrap().take().unwrap();
+
+ let first = ok(&mut h, &c, "ui.open", json!({ "path": a }));
+ assert_eq!(first["opened"], json!(a), "{first}");
+ ok(&mut h, &c, "ui.open", json!({ "path": b }));
+ // The file is already open: the tab focuses, and the reply must be Ok — an agent driving the
+ // app headlessly would otherwise read a focus as a read failure (#1620).
+ let again = ok(&mut h, &c, "ui.open", json!({ "path": a }));
+ assert_eq!(again["focused"], true, "{again}");
+
+ let state = ok(&mut h, &c, "ui.state", json!({}));
+ let docs = state["documents"].as_array().cloned().unwrap_or_default();
+ assert_eq!(docs.len(), 2, "opening an open file adds no tab: {state}");
+ let a_tab = docs.iter().find(|d| d["path"] == json!(a)).unwrap();
+ assert_eq!(a_tab["active"], true, "the already-open tab is in front: {state}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rs
index 215eaedc5..9146ae65d 100644
--- a/crates/ui-egui/tests/editing.rs
+++ b/crates/ui-egui/tests/editing.rs
@@ -6,7 +6,7 @@ use egui::{Key, Modifiers};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind};
-use pdfcraft_ui_egui::{CloseRequest, Dialog, PdfCraftApp};
+use pdfcraft_ui_egui::{CloseRequest, Dialog, OpenOutcome, PdfCraftApp};
/// An `n`-page document with a proper xref table; page `i` shows "Page i+1".
fn fixture(n: usize) -> Vec<u8> {
@@ -585,7 +585,11 @@ fn the_last_session_reopens_its_files_pages_and_active_tab() {
let dir = TempPdfs::new("reopen");
let files = [dir.file("a.pdf", 1), dir.file("b.pdf", 5), dir.file("c.pdf", 2)];
let opened = files.clone();
- let mut h = session_harness(move |app| opened.iter().for_each(|f| app.open_path(f)));
+ let mut h = session_harness(move |app| {
+ opened.iter().for_each(|f| {
+ app.open_path(f);
+ })
+ });
h.state_mut().views[1].go_to_page(3);
h.state_mut().active = Some(1);
h.run_steps(4);
@@ -607,7 +611,11 @@ fn quitting_with_unsaved_changes_still_remembers_every_file() {
let dir = TempPdfs::new("quit");
let files = [dir.file("a.pdf", 1), dir.file("b.pdf", 1)];
let opened = files.clone();
- let mut h = session_harness(move |app| opened.iter().for_each(|f| app.open_path(f)));
+ let mut h = session_harness(move |app| {
+ opened.iter().for_each(|f| {
+ app.open_path(f);
+ })
+ });
for tab in 0..2 {
h.state_mut().active = Some(tab);
h.state_mut().views[tab].select_pages(&[0]);
@@ -659,17 +667,27 @@ fn opening_the_same_path_again_focuses_its_tab() {
let a = pdfs.file("a.pdf", 1);
let b = pdfs.file("b.pdf", 1);
let mut h = session_harness(|_| {});
- h.state_mut().open_path(&a);
- h.state_mut().open_path(&b);
+ assert_eq!(h.state_mut().open_path(&a), OpenOutcome::Opened);
+ assert_eq!(h.state_mut().open_path(&b), OpenOutcome::Opened);
h.run_steps(2);
assert_eq!(h.state().views.len(), 2, "two different files open two tabs");
- h.state_mut().open_path(&a);
+ assert_eq!(h.state_mut().open_path(&a), OpenOutcome::Focused, "opening an open file focuses, it doesn't reopen");
h.run_steps(2);
assert_eq!(h.state().views.len(), 2, "opening an open file again adds no tab");
assert_eq!(h.state().active, Some(0), "the existing tab comes to the front");
assert_eq!(open_paths(h.state()), vec![a, b], "the tab order is untouched");
}
+#[test]
+fn opening_a_missing_file_fails_and_tells_the_user() {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ let missing = std::env::temp_dir().join(format!("pdfcraft-no-such-file-{}.pdf", std::process::id()));
+ assert_eq!(app.open_path(&missing.to_string_lossy()), OpenOutcome::Failed);
+ assert!(app.views.is_empty());
+ assert!(app.toast.is_some(), "the failure is still reported to the user");
+}
+
#[test]
fn opening_the_same_file_with_a_dot_component_focuses_its_tab() {
let pdfs = TempPdfs::new("dedup-dot");