Skip to content

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

Merge remote-tracking branch 'upstream/main' into 1620-focus-open-tab

Eduardo Soares99fd06a8d719
diff --cc crates/ui-egui/src/control.rs
index 5f43f6c7f,a4ab35d96..56233ca27
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@@ -33,8 -36,8 +36,9 @@@
//! 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}`: accept a file open; native opens report `pending: true` until they
-//! complete and are listed in `ui.state.pending_opens`.
+//! - `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`.
++//! (`"focused": true`) instead of adding a tab; native opens report `pending: true` until
++//! they complete and are listed in `ui.state.pending_opens`; only a failed open replies `Err`.
//! - `ui.screenshot {region?}`: PNG of the window (base64), optionally cropped to a rect.
use std::collections::{HashMap, VecDeque};
@@@ -736,10 -766,14 +767,11 @@@ 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 if self.pending_opens.iter().any(|pending| pending.path.as_deref() == Some(path)) {
- Ok(json!({ "accepted": path, "pending": true }))
- } 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::Pending => Ok(json!({ "accepted": path, "pending": true })),
+ crate::OpenOutcome::Failed => Err(self.toast.as_ref().map(|t| t.0.clone()).unwrap_or_else(|| format!("couldn't open {path}"))),
}
}
diff --cc crates/ui-egui/src/lib.rs
index afb19f5e5,9db924759..73147909f
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -734,19 -887,6 +887,23 @@@ fn rgb_triple(v: &serde_json::Value) -
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).
++/// showing it, handed it to the background open worker, 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 was accepted for opening in the background; its tab appears when the open
++ /// completes (`ui.state.pending_opens` lists the files on the way).
++ Pending,
+ /// The file could not be read or opened; the user was told.
+ Failed,
+}
+
impl PdfCraftApp {
pub fn new() -> Self {
Self {
@@@ -1213,49 -1701,155 +1718,175 @@@
/// Open a file from a recent list: focus the tab already showing it, else open it (File ▸
/// Open Recent and the Home view's list share this).
pub fn open_recent(&mut self, path: &str) {
- #[cfg(not(target_arch = "wasm32"))]
- {
- if let Some(i) = self.view_showing(path) {
- self.active = Some(i);
- } else {
- self.open_path(path);
- }
+ if let Some(i) = self.tab_showing(path) {
+ self.active = Some(i);
+ } else {
+ #[cfg(not(target_arch = "wasm32"))]
+ 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
- /// compared after `absolute` normalization, so another spelling of the same file matches
- /// (#1620).
#[cfg(not(target_arch = "wasm32"))]
- fn view_showing(&self, path: &str) -> Option<usize> {
- let path = crate::last_session::absolute(path);
- self.views
- .iter()
- .position(|v| self.session.get(v.id).and_then(|d| d.path.as_deref()).map(crate::last_session::absolute).as_deref() == Some(path.as_str()))
+ pub(crate) fn open_remote_link(&mut self, source: DocId, file: String, destination: pdfcraft_render::RemoteDestination) {
+ if self.pending_remote_link.is_some() || self.pending_link.is_some() {
+ return;
+ }
+ let Some(source_doc) = self.session.get(source) else { return };
+ let source_path = source_doc.path.clone();
+ let path = match pdfcraft_engine::resolve_remote_document_path(source_path.as_deref().map(std::path::Path::new), &file) {
+ Ok(path) => path,
+ Err(e) => {
+ self.notify_fmt("Couldn't follow linked PDF: {reason}", &[("reason", &e.to_string())]);
+ return;
+ }
+ };
+ if pdfcraft_engine::remote_document_path_is_absolute(&file) {
+ self.pending_remote_link = Some(PendingRemoteLink { source, path, destination });
+ return;
+ }
+ self.open_resolved_remote_link(path, destination);
+ }
+
+ /// Take a pending request exactly once. Closing its source invalidates the request.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn resolve_pending_remote_link(&mut self, open: bool) {
+ if let Some(pending) = self.pending_remote_link.take()
+ && open
+ && self.session.get(pending.source).is_some()
+ {
+ self.open_resolved_remote_link(pending.path, pending.destination);
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ fn open_resolved_remote_link(&mut self, path: std::path::PathBuf, destination: pdfcraft_render::RemoteDestination) {
+ let path = path.to_string_lossy().into_owned();
+ let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.clone());
+ let stamp = file_watch::Stamp::at(&path);
+ self.startup_superseded = true;
+ let result = self.schedule_open(OpenRequest {
+ name: name.clone(),
+ path: Some(path.clone()),
+ stamp,
+ input: open_worker::Input::RemotePath(std::path::PathBuf::from(path)),
+ password: None,
+ activate: true,
+ after_open: Some(destination),
+ recovered: None,
+ then: None,
+ });
+ if let Err(error) = result {
+ self.notify_fmt("Couldn't follow linked PDF: {reason}", &[("reason", &error)]);
+ }
+ }
+
+ #[cfg(target_arch = "wasm32")]
+ pub(crate) fn open_remote_link(&mut self, _source: DocId, _file: String, _destination: pdfcraft_render::RemoteDestination) {
+ self.notify_tr("Local cross-PDF links require the desktop app");
+ }
+
+ #[cfg(target_arch = "wasm32")]
+ pub fn resolve_pending_remote_link(&mut self, _open: bool) {
+ self.pending_remote_link = None;
+ }
+
+ fn apply_remote_destination(&mut self, destination: pdfcraft_render::RemoteDestination) {
+ let Some(index) = self.views.len().checked_sub(1) else { return };
+ let Some(doc) = self.session.get(self.views[index].id) else { return };
+ let warning = match destination {
+ pdfcraft_render::RemoteDestination::Default => None,
+ pdfcraft_render::RemoteDestination::Named(_) => Some("The linked PDF opened, but its named destination was not applied."),
+ pdfcraft_render::RemoteDestination::Page { page, view } if page < doc.info.pages.len() => {
+ self.views[index].go_to_dest(page, view, &doc.info);
+ None
+ }
+ pdfcraft_render::RemoteDestination::Page { .. } => Some("The linked PDF opened, but its page destination was out of range."),
+ };
+ if let Some(warning) = warning {
+ self.notify_tr(warning);
+ }
}
#[cfg(not(target_arch = "wasm32"))]
- pub fn open_path(&mut self, path: &str) {
- self.open_path_then(path, None);
+ pub fn open_path(&mut self, path: &str) -> OpenOutcome {
- if let Some(i) = self.view_showing(path) {
++ self.open_path_then(path, None)
+ }
+
- /// Keep a chosen tool with its file until preparation and any password entry finish.
++ /// Keep a chosen tool with its file until preparation and any password entry finish. The
++ /// return value is the programmatic open contract (#1620): callers that must know whether
++ /// the file opened, focused its tab, was handed to the background worker, or failed.
+ #[cfg(not(target_arch = "wasm32"))]
- fn open_path_then(&mut self, path: &str, then: Option<&'static str>) {
++ fn open_path_then(&mut self, path: &str, then: Option<&'static str>) -> OpenOutcome {
+ // One file, one tab (#2166): a file that is open already comes to the front instead,
+ // and the tool it was opened for runs on it. One still being opened is left to that.
+ if let Some(i) = self.tab_showing(path) {
+ self.startup_superseded = true;
self.active = Some(i);
+ if let Some(command) = then {
+ self.execute(command);
+ }
- return;
+ return OpenOutcome::Focused;
}
+ if self.pending_opens.iter().any(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) {
- return;
++ return OpenOutcome::Pending;
+ }
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) => 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())]);
+ // Taken before reading: a build that rewrites the file meanwhile still counts as a change.
+ let stamp = file_watch::Stamp::at(path);
+ // Before the first frame there is no interaction to keep responsive; this also preserves
+ // deterministic inline startup and test flows. Once live, reading and preparation use
+ // the bounded worker and commit on the UI thread.
+ if self.ctx.is_none() || self.run_inline {
+ match std::fs::read(path) {
+ Ok(bytes) => {
+ let before = self.views.len();
+ if let Err(error) = self.open_bytes(&name, Some(path.to_string()), bytes) {
+ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]);
- } else if let Some(prompt) = self.password_prompt.as_mut().filter(|p| p.path.as_deref() == Some(path)) {
++ return OpenOutcome::Failed;
++ }
++ if let Some(prompt) = self.password_prompt.as_mut().filter(|p| p.path.as_deref() == Some(path)) {
++ // Encrypted: the tool runs once the password is in.
+ prompt.then = then;
+ } else if self.views.len() > before {
+ if let Some(doc) = self.views.last().map(|view| view.id) {
+ self.watch.known_as(doc, stamp);
+ }
+ if let Some(command) = then {
+ self.execute(command);
+ }
++ } else {
++ // Open reported success but added no tab and raised no prompt; the
++ // control channel answers this as a failure to open.
++ return OpenOutcome::Failed;
+ }
++ OpenOutcome::Opened
++ }
++ Err(error) => {
++ self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &error.to_string())]);
++ OpenOutcome::Failed
++ }
++ }
++ } else {
++ self.startup_superseded = true;
++ match self.schedule_open(OpenRequest {
++ name: name.clone(),
++ path: Some(path.to_string()),
++ stamp,
++ input: open_worker::Input::Path(std::path::PathBuf::from(path)),
++ password: None,
++ activate: true,
++ after_open: None,
++ recovered: None,
++ then,
++ }) {
++ Ok(_) => OpenOutcome::Pending,
++ Err(error) => {
++ self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]);
+ OpenOutcome::Failed
}
- },
- Err(e) => {
- self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]);
- OpenOutcome::Failed
- Err(error) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &error.to_string())]),
}
- return;
- }
- self.startup_superseded = true;
- if let Err(error) = self.schedule_open(OpenRequest {
- name: name.clone(),
- path: Some(path.to_string()),
- stamp,
- input: open_worker::Input::Path(std::path::PathBuf::from(path)),
- password: None,
- activate: true,
- after_open: None,
- recovered: None,
- then,
- }) {
- self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]);
}
}
diff --cc crates/ui-egui/tests/control.rs
index 7f1d27a76,e6af166d7..55328a2d6
--- a/crates/ui-egui/tests/control.rs
+++ b/crates/ui-egui/tests/control.rs
@@@ -1428,37 -1523,201 +1523,284 @@@ fn read_mode_retains_existing_rail_clic
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();
++ // Inline opens: this test pins the synchronous open contract (focus vs open vs
++ // failure). Live apps schedule the worker instead and reply `pending` (#1620).
++ app.run_inline = true;
+ *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);
+}
++
++/// The other half of the #1620 contract on a live UI: a fresh open is scheduled on the
++/// background worker and answered `pending` (upstream's reply shape), the tab appears once
++/// the open completes, and opening the file again then focuses that tab.
++#[test]
++fn control_open_replies_pending_while_the_worker_opens_and_focuses_once_it_has() {
++ let dir = std::env::temp_dir().join(format!("pdfcraft-ui-open-pending-{}", std::process::id()));
++ std::fs::create_dir_all(&dir).unwrap();
++ let a = dir.join("pending.pdf").to_string_lossy().into_owned();
++ std::fs::write(&a, fixture(2)).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["accepted"], json!(a), "{first}");
++ assert_eq!(first["pending"], true, "{first}");
++
++ // The worker completes the open on later frames; the tab shows, and only then does a
++ // repeated open focus it instead of reporting another pending open.
++ let mut documents = 0;
++ for _ in 0..30 {
++ h.run_steps(1);
++ let state = ok(&mut h, &c, "ui.state", json!({}));
++ documents = state["documents"].as_array().map(|d| d.len()).unwrap_or_default();
++ if documents == 1 {
++ break;
++ }
++ }
++ assert_eq!(documents, 1, "the pending open completed into a tab");
++
++ 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(), 1, "focusing the completed open adds no tab: {state}");
++ let _ = std::fs::remove_dir_all(&dir);
++}
++
+ fn navigation_frame(h: &mut Harness<'static, PdfCraftApp>, events: Vec<egui::Event>) {
+ h.input_mut().events.extend(events);
+ h.step();
+ }
+
+ fn navigation_wheel(h: &mut Harness<'static, PdfCraftApp>, pos: egui::Pos2, delta: f32, ctrl: bool) {
+ let modifiers = egui::Modifiers { ctrl, command: ctrl, ..egui::Modifiers::NONE };
+ navigation_frame(
+ h,
+ vec![
+ egui::Event::ModifiersChanged(modifiers),
+ egui::Event::PointerMoved(pos),
+ egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: egui::vec2(0.0, delta), modifiers, phase: egui::TouchPhase::Move },
+ ],
+ );
+ h.run_steps(20);
+ navigation_frame(h, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
+ }
+
+ #[test]
+ fn ctrl_wheel_anchors_visible_page_and_plain_wheel_only_scrolls() {
+ for percent in [100, 200, 400] {
+ for fraction in [0.1, 0.5, 0.9] {
+ let (mut h, c) = harness_pages(20);
+ ok(&mut h, &c, "ui.set", json!({"key":"zoom", "value":percent.to_string()}));
+ h.run_steps(4);
+ let viewport = h.state().views[0].viewport_rect();
+ let before = h.state().views[0].page_screen_rect(0).unwrap();
+ let visible = before.intersect(viewport).shrink(15.0);
+ let p = egui::pos2(visible.left() + fraction * visible.width(), visible.top() + fraction * visible.height());
+ let normalised = (p - before.min) / before.size();
+ let old_zoom = h.state().views[0].zoom;
+ navigation_wheel(&mut h, p, 20.0, true);
+ let enlarged = h.state().views[0].page_screen_rect(0).unwrap();
+ let anchored = enlarged.min + normalised * enlarged.size();
+ assert!(h.state().views[0].zoom > old_zoom);
+ assert!((anchored.y - p.y).abs() < 2.0, "percent={percent}, fraction={fraction}");
+ if before.width() > viewport.width() {
+ assert!((anchored.x - p.x).abs() < 2.0);
+ }
+ navigation_wheel(&mut h, p, -20.0, true);
+ assert!((h.state().views[0].zoom - old_zoom).abs() < 0.01);
+ let zoom = h.state().views[0].zoom;
+ let top = h.state().views[0].page_screen_rect(0).unwrap().top();
+ navigation_wheel(&mut h, p, -80.0, false);
+ assert_eq!(h.state().views[0].zoom, zoom);
+ assert!(h.state().views[0].page_screen_rect(0).unwrap().top() < top - 20.0);
+ }
+ }
+ }
+
+ #[test]
+ fn wheel_zoom_is_scoped_to_the_viewport_and_respects_existing_limits() {
+ let (mut h, c) = harness();
+ let outside = egui::pos2(5.0, 5.0);
+ let zoom = h.state().views[0].zoom;
+ navigation_wheel(&mut h, outside, 40.0, true);
+ assert_eq!(h.state().views[0].zoom, zoom);
+ for (percent, delta, expected) in [(6400, 80.0, 64.0), (8, -80.0, 0.08)] {
+ ok(&mut h, &c, "ui.set", json!({"key":"zoom", "value":percent.to_string()}));
+ h.run_steps(4);
+ let p = h.state().views[0].viewport_rect().center();
+ navigation_wheel(&mut h, p, delta, true);
+ assert_eq!(h.state().views[0].zoom, expected);
+ }
+ }
+
+ #[test]
+ fn initial_zoom_option_is_applied_before_the_first_viewport_layout() {
+ for percent in [50, 100, 200, 400] {
+ let h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.open_bytes("initial-zoom.pdf", None, fixture(3)).unwrap();
+ app.set_option("zoom", &percent.to_string()).unwrap();
+ assert_eq!(app.views[0].zoom, percent as f32 / 100.0, "initial options must work before the viewport exists");
+ app
+ });
+ assert_eq!(h.state().views[0].zoom, percent as f32 / 100.0);
+ }
+ }
+
+ /// #1306: a coordinate that only overflows once narrowed to a pointer position is refused by
+ /// click and drag, as move refuses it, before any pointer input is queued; the frames that follow
+ /// run, and the channel keeps working.
+ #[test]
+ fn click_and_drag_refuse_coordinates_that_overflow_like_move() {
+ let (mut h, c) = harness();
+ for (method, params) in [
+ ("ui.move", json!({ "x": 1e39, "y": -1e39 })),
+ ("ui.click", json!({ "x": 1e39, "y": -1e39 })),
+ ("ui.click", json!({ "x": 40.0, "y": 1e39 })),
+ ("ui.drag", json!({ "from": [1e39, -1e39], "to": [40.0, 40.0], "steps": 1 })),
+ ("ui.drag", json!({ "from": [40.0, 40.0], "to": [40.0, -1e39], "steps": 1 })),
+ // Each end fits, but not the way from one to the other.
+ ("ui.drag", json!({ "from": [-3e38, 40.0], "to": [3e38, 40.0], "steps": 1 })),
+ ] {
+ let e = call(&mut h, &c, method, params.clone()).expect_err(&format!("{method} {params} is refused"));
+ assert!(e.starts_with(&format!("{method}: ")) && e.contains("finite"), "{e}");
+ h.run_steps(4);
+ assert_eq!(ok(&mut h, &c, "ui.inspect", json!({ "query": "Read", "role": "Button" }))["count"], 1);
+ }
+ let read = ok(&mut h, &c, "ui.inspect", json!({ "query": "Read", "role": "Button" }))["widgets"][0]["rect"].clone();
+ let (x, y) = (read[0].as_f64().unwrap() + 4.0, read[1].as_f64().unwrap() + 4.0);
+ assert_eq!(ok(&mut h, &c, "ui.click", json!({ "x": x, "y": y }))["clicked"], json!([x, y]));
+ ok(&mut h, &c, "ui.drag", json!({ "from": [x, y], "to": [x + 10.0, y], "steps": 2 }));
+ }
+
+ #[test]
+ fn page_size_shows_while_the_pointer_is_in_the_bottom_left_quadrant() {
+ let (mut h, _c) = harness();
+ let area = h.state().views[0].viewport_rect();
+ let shown = |h: &Harness<'static, PdfCraftApp>| {
+ let layer = egui::LayerId::new(egui::Order::Foreground, egui::Id::new("page-size-hint"));
+ h.ctx.memory(|m| m.areas().visible_last_frame(&layer))
+ };
+ let away = area.center() + egui::vec2(300.0, -200.0);
+ h.event(egui::Event::PointerMoved(away));
+ h.run_steps(3);
+ assert!(!shown(&h), "top-right: hidden");
+ h.event(egui::Event::PointerMoved(area.left_bottom() + egui::vec2(80.0, -80.0)));
+ h.run_steps(3);
+ assert!(shown(&h), "bottom-left: shown");
+ if let Ok(dir) = std::env::var("PDFCRAFT_SHOT_DIR") {
+ h.render().unwrap().save(format!("{dir}/page-size-hint.png")).unwrap();
+ }
+ h.event(egui::Event::PointerMoved(away));
+ h.run_steps(3);
+ assert!(!shown(&h), "pointer left: hidden again");
+ }
+
+ #[test]
+ fn navigation_history_commands_and_rail_are_per_tab_and_non_editing() {
+ for os in [egui::os::OperatingSystem::Nix, egui::os::OperatingSystem::Mac, egui::os::OperatingSystem::Windows] {
+ navigation_history_for_os(os);
+ }
+ }
+
+ fn navigation_history_for_os(os: egui::os::OperatingSystem) {
+ let (mut h, c) = harness();
+ h.ctx.set_os(os);
+ h.run_steps(2);
+ let enabled =
+ |list: Value, id: &str| list["commands"].as_array().unwrap().iter().find(|cmd| cmd["id"] == id).unwrap()["enabled"].as_bool().unwrap();
+ assert!(!enabled(ok(&mut h, &c, "ui.commands", json!({})), "view.previous_view"));
+ assert!(call(&mut h, &c, "ui.command", json!({"id": "view.previous_view"})).is_err());
+ // Empty-history shortcuts were silent before registry integration and must stay silent.
+ for key in ["[", "]"] {
+ ok(&mut h, &c, "ui.key", json!({"key": key, "modifiers": ["command"]}));
+ assert!(h.state().toast.is_none(), "an unavailable history action must not ask to open the already-open document");
+ }
+ let before = h.state().session.get(h.state().views[0].id).unwrap().bytes.clone();
+ ok(&mut h, &c, "ui.set", json!({"key": "page", "value": "4"}));
+ assert!(enabled(ok(&mut h, &c, "ui.commands", json!({})), "view.previous_view"));
+ // The real rail button is accessible and invokes the same history, not the adjacent page.
+ let shortcut = if h.ctx.os() == egui::os::OperatingSystem::Mac { "⌘[" } else { "Ctrl+[" };
+ ok(&mut h, &c, "ui.click", json!({"label": &format!("Previous view ({shortcut})")}));
+ assert_eq!(h.state().views[0].current, 0);
+ assert!(enabled(ok(&mut h, &c, "ui.commands", json!({})), "view.next_view"));
+ ok(&mut h, &c, "ui.command", json!({"id": "view.next_view"}));
+ assert_eq!(h.state().views[0].current, 3);
+ ok(&mut h, &c, "ui.set", json!({"key": "page", "value": "5"}));
+ ok(&mut h, &c, "ui.key", json!({"key": "[", "modifiers": ["command"]}));
+ assert_eq!(h.state().views[0].current, 3, "shortcut traverses exactly one history entry");
+ ok(&mut h, &c, "ui.key", json!({"key": "]", "modifiers": ["command"]}));
+ assert_eq!(h.state().views[0].current, 4);
+ ok(&mut h, &c, "ui.command", json!({"id": "view.previous_view"}));
+ h.state_mut().open_bytes("other.pdf", None, fixture(5)).unwrap();
+ assert!(!enabled(ok(&mut h, &c, "ui.commands", json!({})), "view.previous_view"));
+ ok(&mut h, &c, "ui.set", json!({"key": "page", "value": "2"}));
+ ok(&mut h, &c, "ui.command", json!({"id": "view.previous_view"}));
+ assert_eq!(h.state().views[1].current, 0);
+ assert_eq!(h.state().views[0].current, 3, "other tab's history does not move this document");
+ h.state_mut().active = Some(0);
+ ok(&mut h, &c, "ui.command", json!({"id": "view.previous_view"}));
+ assert_eq!(h.state().views[0].current, 0);
+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().bytes, before);
+ assert!(!h.state().session.get(h.state().views[0].id).unwrap().dirty);
+ h.state_mut().open_bytes("reopened.pdf", None, before.as_ref().clone()).unwrap();
+ assert!(h.state().views.last().unwrap().back.is_empty());
+ assert!(h.state().views.last().unwrap().forward.is_empty());
+ }
+
+ #[test]
+ fn routine_continuous_scrolling_does_not_add_navigation_history() {
+ let (mut h, c) = harness_pages(20);
+ ok(&mut h, &c, "ui.set", json!({"key": "animation_effects", "value": "off"}));
+ h.hover_at(egui::pos2(700.0, 450.0));
+ h.event(egui::Event::MouseWheel {
+ unit: egui::MouseWheelUnit::Point,
+ delta: egui::vec2(0.0, -1200.0),
+ modifiers: egui::Modifiers::NONE,
+ phase: egui::TouchPhase::Move,
+ });
+ h.run_steps(8);
+ assert!(h.state().views[0].current > 0, "the wheel really moved to a later page");
+ assert!(h.state().views[0].back.is_empty());
+ assert!(h.state().views[0].forward.is_empty());
+ }
diff --cc crates/ui-egui/tests/editing.rs
index 9146ae65d,d41041e52..35e7e671e
--- a/crates/ui-egui/tests/editing.rs
+++ b/crates/ui-egui/tests/editing.rs
@@@ -661,91 -818,6 +826,93 @@@ fn the_last_session_is_off_by_default_a
assert!(later.views.is_empty(), "neither opens from the session");
}
+#[test]
+fn opening_the_same_path_again_focuses_its_tab() {
+ let pdfs = TempPdfs::new("dedup-open");
+ let a = pdfs.file("a.pdf", 1);
+ let b = pdfs.file("b.pdf", 1);
- let mut h = session_harness(|_| {});
++ // Inline opens: this pins the synchronous open contract (open vs focus). A live app
++ // schedules the background worker instead and answers `Pending` until it completes.
++ let mut h = session_harness(|app| app.run_inline = true);
+ 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");
+ 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");
+ let a = pdfs.file("a.pdf", 1);
+ let dotted = format!("{}/./a.pdf", pdfs.0.display());
- let mut h = session_harness(|_| {});
++ let mut h = session_harness(|app| app.run_inline = true);
+ h.state_mut().open_path(&a);
+ h.state_mut().open_path(&dotted);
+ h.run_steps(2);
+ assert_eq!(h.state().views.len(), 1, "another spelling of the same file matches");
+ assert_eq!(h.state().active, Some(0));
+}
+
+#[test]
+fn opening_a_file_whose_copy_vanished_from_disk_focuses_its_tab() {
+ let pdfs = TempPdfs::new("dedup-vanished");
+ let a = pdfs.file("a.pdf", 1);
+ let mut h = session_harness(|_| {});
+ h.state_mut().open_path(&a);
+ h.run_steps(2);
+ std::fs::remove_file(&a).unwrap();
+ h.state_mut().open_path(&a);
+ h.run_steps(2);
+ assert_eq!(h.state().views.len(), 1, "no second tab");
+ assert_eq!(h.state().active, Some(0), "the open tab is focused");
+ assert!(h.state().toast.is_none(), "no read error: the file is never read again");
+}
+
+#[test]
+fn opening_an_encrypted_document_twice_keeps_one_prompt_and_one_tab() {
+ let pdfs = TempPdfs::new("dedup-encrypted");
+ let secret = pdfs.0.join("secret.pdf");
+ std::fs::write(&secret, protected("pw", "owner", -1)).unwrap();
+ let s = secret.to_string_lossy().into_owned();
- let mut h = session_harness(|_| {});
++ let mut h = session_harness(|app| app.run_inline = true);
+ h.state_mut().open_path(&s);
+ h.state_mut().open_path(&s);
+ h.run_steps(2);
+ assert!(h.state().views.is_empty(), "still locked");
+ let field = h.get_by_role(Role::PasswordInput);
+ field.focus();
+ field.type_text("pw");
+ h.run_steps(2);
+ h.key_press(Key::Enter);
+ h.run_steps(4);
+ assert_eq!(h.state().views.len(), 1, "unlocking opens one tab, not two");
+}
+
+#[test]
+fn opening_documents_without_a_path_still_open_twice() {
+ let bytes = fixture(1);
+ let mut h = session_harness(|_| {});
+ h.state_mut().open_bytes("copy.pdf", None, bytes.clone()).unwrap();
+ h.state_mut().open_bytes("copy.pdf", None, bytes).unwrap();
+ h.run_steps(2);
+ assert_eq!(h.state().views.len(), 2, "bytes have no path to compare (attachments, conversions)");
+}
+
#[test]
fn save_prompt_stays_inside_the_screen_for_a_long_filename() {
// Issue #161: an unwrapped title carrying a long filename widened the centered modal past
diff --cc crates/ui-egui/tests/ui.rs
index 1e2df54bc,d30ab1b8d..9ffa46d7e
--- a/crates/ui-egui/tests/ui.rs
+++ b/crates/ui-egui/tests/ui.rs
@@@ -611,34 -788,15 +788,39 @@@ fn dropping_a_pdf_on_the_window_opens_i
assert!(h.state().views.is_empty());
let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: "dropped.pdf".into(), bytes: FIXTURE.to_vec() });
h.input_mut().dropped_files.push(file);
- h.run_steps(3);
+ support::wait_until(&mut h, "dropped document", |app| app.views.len() == 1 && app.password_prompt.is_none());
assert_eq!(h.state().views.len(), 1, "the dropped PDF opens in a tab");
h.get_by_label_contains("dropped.pdf");
+ let (_, id) = h.state().active_ids().unwrap();
+ let doc = h.state().session.get(id).unwrap();
+ assert_eq!(doc.name, "dropped.pdf");
+ assert_eq!(doc.bytes.as_slice(), FIXTURE);
}
+#[test]
+fn dropping_an_open_pdf_again_focuses_its_tab() {
+ let dir = std::env::temp_dir().join(format!("pdfcraft-drop-dedup-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("dropped.pdf");
+ std::fs::write(&path, FIXTURE).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app
+ });
+ h.run_steps(3);
+ let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: path.clone(), bytes: FIXTURE.to_vec() });
+ h.input_mut().dropped_files.push(file.clone());
- h.run_steps(3);
++ // The drop opens through the background worker on a live window; wait for the tab.
++ support::wait_until(&mut h, "dropped document", |app| app.views.len() == 1);
+ assert_eq!(h.state().views.len(), 1, "the dropped PDF opens in a tab");
+ h.input_mut().dropped_files.push(file);
+ h.run_steps(3);
+ assert_eq!(h.state().views.len(), 1, "dropping it again adds no tab");
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
#[test]
fn a_file_dropped_on_the_page_grid_is_read_from_disk_and_inserted() {
// The grid's drop reads a file from its path when its turn to be inserted comes, and inserts it
diff --cc parity/acrobat-features.toml
index 56a116286,7aca7d5c8..6324720bd
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@@ -22,8 -34,8 +34,8 @@@ milestone = "M1
status = "shipped"
commands = ["file.open"]
tools = ["doc_open"]
- evidence = ["crates/automation/tests/automation.rs::open_inspect_render_and_find", "crates/ui-egui/tests/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/ui.rs::files_and_quit_from_the_operating_system", "crates/ui-egui/tests/editing.rs::opening_the_same_path_again_focuses_its_tab", "crates/ui-egui/tests/editing.rs::opening_a_file_whose_copy_vanished_from_disk_focuses_its_tab"]
- notes = "File ▸ Open, the command line (Linux and Windows file associations), and on macOS Finder, Open With and the Dock (Apple events; the bundle declares PDF as a document type); an already-open file focuses its tab instead of opening a second copy (#1620)"
-evidence = ["crates/automation/tests/automation.rs::open_inspect_render_and_find", "crates/ui-egui/tests/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/ui.rs::files_and_quit_from_the_operating_system", "crates/ui-egui/src/open_worker_tests.rs::a_chosen_tool_runs_on_its_file_only_after_native_preparation_commits"]
-notes = "File ▸ Open, the command line (Linux and Windows file associations), the Windows MSI's \"Edit with PdfCraft\" entry on PDF files' File Explorer right-click menu (#682; several selected PDFs open as tabs of one window), and on macOS Finder, Open With and the Dock (Apple events; the bundle declares PDF as a document type). Not yet: a first-level Windows 11 menu entry (needs package identity) or Combine from the file manager (#585)"
++evidence = ["crates/automation/tests/automation.rs::open_inspect_render_and_find", "crates/ui-egui/tests/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/ui.rs::files_and_quit_from_the_operating_system", "crates/ui-egui/src/open_worker_tests.rs::a_chosen_tool_runs_on_its_file_only_after_native_preparation_commits", "crates/ui-egui/tests/editing.rs::opening_the_same_path_again_focuses_its_tab", "crates/ui-egui/tests/editing.rs::opening_a_file_whose_copy_vanished_from_disk_focuses_its_tab"]
++notes = "File ▸ Open, the command line (Linux and Windows file associations), the Windows MSI's \"Edit with PdfCraft\" entry on PDF files' File Explorer right-click menu (#682; several selected PDFs open as tabs of one window), and on macOS Finder, Open With and the Dock (Apple events; the bundle declares PDF as a document type); an already-open file focuses its tab instead of opening a second copy (#1620). Not yet: a first-level Windows 11 menu entry (needs package identity) or Combine from the file manager (#585)"
[[feature]]
id = "core.repair-broken-files"