mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-26 04:58:07 +00:00
pdf-chrome-w12: net change of 3 commits
- pdf-chrome-w12: written from its sheet - pdf-chrome-w12: repair 1 - pdf-chrome-w12: review fixes (review-1)
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
//! The document tab strips: the main window's and split view's second pane's. A tab is a
|
||||
//! [`DocView`](crate::DocView) keyed by its view key, since split view can show one document in two
|
||||
//! tabs; the Combine files tab sits last in the main strip and is never moved.
|
||||
|
||||
use craft::platform::open::CAN_REVEAL;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::tabs::{DocumentTab, DocumentTabs, DocumentTabsEvent};
|
||||
|
||||
use crate::PdfCraftApp;
|
||||
use crate::panes::Place;
|
||||
use crate::tab_context::Action;
|
||||
|
||||
/// What a strip tab stands for: a view of a document, or the Combine files tab.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum StripTab {
|
||||
/// A document view, by `DocView::view_key`.
|
||||
View(u64),
|
||||
/// The Combine files tab, always last.
|
||||
Combine,
|
||||
}
|
||||
|
||||
/// The strip of `place`: its tabs in pane order, then (main strip only) Combine files.
|
||||
pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) {
|
||||
let mut tabs: Vec<DocumentTab<StripTab>> = Vec::new();
|
||||
for index in app.tabs_in(place) {
|
||||
let Some(view) = app.views.get(index) else { continue };
|
||||
let Some(doc) = app.session.get(view.id) else { continue };
|
||||
let mut tab = DocumentTab::new(StripTab::View(view.pane.key), doc.name.clone()).modified(doc.dirty).closable(true);
|
||||
if let Some(path) = &doc.path
|
||||
&& std::path::Path::new(path).file_name().is_some_and(|file| file.to_string_lossy() != doc.name.as_str())
|
||||
{
|
||||
tab = tab.tooltip(path.clone());
|
||||
}
|
||||
tabs.push(tab);
|
||||
}
|
||||
if place == Place::Main && app.combine_tab.open {
|
||||
tabs.push(DocumentTab::new(StripTab::Combine, tl!("Combine files").to_string()).closable(true).movable(false));
|
||||
}
|
||||
let selected = if place == Place::Main && app.combine_showing() {
|
||||
Some(StripTab::Combine)
|
||||
} else {
|
||||
app.pane_front(place).and_then(|i| app.views.get(i)).map(|v| StripTab::View(v.pane.key))
|
||||
};
|
||||
let label = if place == Place::Main { tl!("Documents") } else { tl!("Split view documents") };
|
||||
let mut strip = DocumentTabs::new(label.to_string(), &tabs).reorderable(true);
|
||||
if let Some(selected) = selected {
|
||||
strip = strip.selected(selected);
|
||||
}
|
||||
let output = strip.show(ui);
|
||||
let (events, response) = (output.events, output.response);
|
||||
|
||||
for event in events {
|
||||
match event {
|
||||
DocumentTabsEvent::Selected(StripTab::View(key)) | DocumentTabsEvent::Picked(StripTab::View(key)) => {
|
||||
if let Some(i) = app.tab_with_key(key) {
|
||||
let from_combine = app.combine_showing();
|
||||
app.active = Some(i);
|
||||
app.combine_tab.focused = false;
|
||||
if from_combine {
|
||||
// PLAN: assumed `PdfCraftApp::close_combine_preview(&mut self)` (pdf-workflows-w7).
|
||||
app.close_combine_preview();
|
||||
}
|
||||
}
|
||||
}
|
||||
DocumentTabsEvent::Selected(StripTab::Combine) | DocumentTabsEvent::Picked(StripTab::Combine) => {
|
||||
app.active = None;
|
||||
app.combine_tab.focused = true;
|
||||
}
|
||||
DocumentTabsEvent::CloseRequested(StripTab::View(key)) => app.tab_action(Action::Close(key)),
|
||||
DocumentTabsEvent::CloseRequested(StripTab::Combine) => app.close_combine_tab(),
|
||||
DocumentTabsEvent::Reordered { documents, before } => {
|
||||
for document in documents {
|
||||
let StripTab::View(key) = document else { continue };
|
||||
let Some(from) = app.tab_with_key(key) else { continue };
|
||||
let tabs = app.tabs_in(place);
|
||||
let others: Vec<usize> = tabs.iter().copied().filter(|&i| i != from).collect();
|
||||
let to = match &before {
|
||||
Some(StripTab::View(next)) => {
|
||||
app.tab_with_key(*next).and_then(|n| others.iter().position(|&i| i == n)).unwrap_or(others.len())
|
||||
}
|
||||
_ => others.len(),
|
||||
};
|
||||
app.move_tab_in_strip(from, &tabs, to);
|
||||
}
|
||||
}
|
||||
DocumentTabsEvent::DroppedInto { documents, .. } => {
|
||||
for document in documents {
|
||||
if let StripTab::View(key) = document
|
||||
&& let Some(i) = app.tab_with_key(key)
|
||||
{
|
||||
app.move_tab_to(i, place);
|
||||
}
|
||||
}
|
||||
}
|
||||
DocumentTabsEvent::ContextMenu(request) => {
|
||||
app.panes.tab_menu = match request.key {
|
||||
StripTab::View(key) => Some((place, key)),
|
||||
StripTab::Combine => None,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// The menu acts on the tab it was asked for, not the active one.
|
||||
let target: Option<u64> = app.panes.tab_menu.filter(|(menu_place, _)| *menu_place == place).map(|(_, key)| key);
|
||||
let doc = target.and_then(|key| app.tab_with_key(key)).and_then(|i| app.views.get(i)).map(|v| v.id);
|
||||
let path = doc.and_then(|id| app.session.get(id)).and_then(|d| d.path.clone());
|
||||
let can_reopen = !app.closed_tabs.is_empty();
|
||||
let reveal_label = if cfg!(target_os = "macos") { tl!("Reveal in Finder") } else { tl!("Reveal in File Explorer") }.to_string();
|
||||
let mut chosen: Option<Action> = None;
|
||||
let menu = Menu::context(tl!("Tab").to_string(), &response).show(ui, |ui, _| {
|
||||
let Some(tab) = target else { return };
|
||||
if MenuItem::new(tl!("Close Tab").to_string()).show(ui).ran {
|
||||
chosen = Some(Action::Close(tab));
|
||||
}
|
||||
if MenuItem::new(tl!("Reopen Closed Tab").to_string()).enabled(can_reopen).show(ui).ran {
|
||||
chosen = Some(Action::Reopen);
|
||||
}
|
||||
if MenuItem::new(tl!("Split right").to_string()).show(ui).ran {
|
||||
chosen = Some(Action::Split { tab, down: false });
|
||||
}
|
||||
if MenuItem::new(tl!("Split down").to_string()).show(ui).ran {
|
||||
chosen = Some(Action::Split { tab, down: true });
|
||||
}
|
||||
if MenuItem::new(reveal_label.clone()).enabled(CAN_REVEAL && path.is_some()).show(ui).ran
|
||||
&& let Some(id) = doc
|
||||
{
|
||||
chosen = Some(Action::Reveal(id));
|
||||
}
|
||||
});
|
||||
if menu.output.closed.is_some() && target.is_some() {
|
||||
app.panes.tab_menu = None;
|
||||
}
|
||||
if let Some(action) = chosen {
|
||||
app.tab_action(action);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
//! PDF-tab actions. Closed history contains paths only, never bytes or passwords.
|
||||
use std::path::PathBuf;
|
||||
|
||||
use craft::host::queue::Priority;
|
||||
use pdfcraft_engine::DocId;
|
||||
|
||||
pub(crate) enum Action {
|
||||
@@ -14,37 +17,23 @@ pub(crate) enum Action {
|
||||
},
|
||||
}
|
||||
|
||||
impl crate::PdfCraftApp {
|
||||
/// Reveal a local file without opening it or changing document/Recent state. The existence
|
||||
/// check and the file manager call can block (a disconnected network mount, a slow `dbus-send`
|
||||
/// or `explorer.exe`), so they run on a worker; a failure is shown by
|
||||
/// [`Self::show_reveal_errors`]. Tests run it inline ([`PdfCraftApp::run_inline`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn reveal_path(&mut self, path: &std::path::Path) {
|
||||
let path = path.to_path_buf();
|
||||
let errors = self.reveal_errors.clone();
|
||||
let ctx = self.ctx.clone();
|
||||
let work = move || {
|
||||
if let Err(e) = reveal(&path) {
|
||||
errors.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(e);
|
||||
if let Some(ctx) = &ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
};
|
||||
if self.run_inline {
|
||||
work();
|
||||
} else if let Err(e) = std::thread::Builder::new().name("pdfcraft-reveal".into()).spawn(work) {
|
||||
self.notify_error(e);
|
||||
}
|
||||
}
|
||||
/// Reveal a local file without opening it or changing document/Recent state. The file manager call
|
||||
/// blocks (a disconnected network mount, a slow `dbus-send` or `explorer.exe`), so it runs as a
|
||||
/// job on the host's queue; a failure is shown by [`PdfCraftApp::drain_reveals`] on the pass that
|
||||
/// receives the result.
|
||||
pub(crate) fn reveal_on_jobs(app: &mut crate::PdfCraftApp, path: PathBuf) {
|
||||
// PLAN: assumed field `reveal_jobs: JobQueue<PathBuf, Result<(), String>>` on `PdfCraftApp` (pdf-hub-w1).
|
||||
let target = path.clone();
|
||||
app.reveal_jobs.submit(path, Priority::VISIBLE, move |_| craft::platform::open::reveal(&target));
|
||||
}
|
||||
|
||||
/// Show the failures the reveal worker has reported (called each frame).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn show_reveal_errors(&mut self) {
|
||||
let errors = std::mem::take(&mut *self.reveal_errors.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
|
||||
for e in errors {
|
||||
self.notify_error(e);
|
||||
impl crate::PdfCraftApp {
|
||||
/// Shows the failures of finished reveal jobs; once a frame, whatever the window shows.
|
||||
pub(crate) fn drain_reveals(&mut self) {
|
||||
while let Some(done) = self.reveal_jobs.try_recv() {
|
||||
if let Err(e) = done.result {
|
||||
self.notify_error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,138 +68,84 @@ impl crate::PdfCraftApp {
|
||||
}
|
||||
}
|
||||
Action::Reveal(id) => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(path) = self.session.get(id).and_then(|d| d.path.clone()) {
|
||||
self.reveal_path(std::path::Path::new(&path));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// Blocking: call it from a worker thread ([`crate::PdfCraftApp::reveal_path`]).
|
||||
fn reveal(path: &std::path::Path) -> Result<(), String> {
|
||||
// Absolute paths also prevent a filename starting with '-' becoming an option.
|
||||
let path = std::path::absolute(path).map_err(|e| e.to_string())?;
|
||||
if !path.try_exists().map_err(|e| e.to_string())? {
|
||||
return Err("The file no longer exists".into());
|
||||
}
|
||||
let platform = std::env::consts::OS;
|
||||
let run =
|
||||
|program: &str, args: &[std::ffi::OsString]| reveal_process(program, args).output().map(|o| o.status.success()).map_err(|e| e.to_string());
|
||||
reveal_via(platform, &path, run)
|
||||
}
|
||||
|
||||
/// The process that runs `program` with `args`. Windows: `reveal_command` already quotes what
|
||||
/// Explorer needs quoted, and Rust's own quoting of an argument with a space breaks `/select,`
|
||||
/// (#2579), so the arguments go on the command line as written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reveal_process(program: &str, args: &[std::ffi::OsString]) -> std::process::Command {
|
||||
let mut command = std::process::Command::new(program);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
for arg in args {
|
||||
command.raw_arg(arg);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
command.args(args);
|
||||
command
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reveal_via(
|
||||
platform: &str,
|
||||
path: &std::path::Path,
|
||||
mut run: impl FnMut(&str, &[std::ffi::OsString]) -> Result<bool, String>,
|
||||
) -> Result<(), String> {
|
||||
let (program, args) = reveal_command(platform, path)?;
|
||||
if run(program, &args).unwrap_or(false) {
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(platform, "linux" | "freebsd") {
|
||||
// FileManager1 is optional. If absent, open the containing folder with xdg-open.
|
||||
let parent = path.parent().ok_or("The file has no parent directory")?;
|
||||
if run("xdg-open", &[parent.as_os_str().into()])? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err("Could not reveal the file in the system file manager".into())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reveal_command(platform: &str, path: &std::path::Path) -> Result<(&'static str, Vec<std::ffi::OsString>), String> {
|
||||
match platform {
|
||||
"windows" => {
|
||||
// Explorer reads `/select,"<object>"`: the path quoted after the comma (#2579). Quoting
|
||||
// the whole argument instead ("/select,C:\a b.pdf", what an ordinary argument with a
|
||||
// space becomes) opens Documents. A Windows path can't contain `"`, so the quotes
|
||||
// can't be closed early; one that does is refused.
|
||||
if path.as_os_str().as_encoded_bytes().contains(&b'"') {
|
||||
return Err("The file name can't be shown in File Explorer".into());
|
||||
}
|
||||
let mut selection = std::ffi::OsString::from("/select,\"");
|
||||
selection.push(path);
|
||||
selection.push("\"");
|
||||
Ok(("explorer.exe", vec![selection]))
|
||||
}
|
||||
"macos" => Ok(("open", vec!["-R".into(), path.as_os_str().into()])),
|
||||
"linux" | "freebsd" => {
|
||||
let mut uri = String::from("array:string:file://");
|
||||
for b in path.as_os_str().as_encoded_bytes() {
|
||||
if b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~') {
|
||||
uri.push(char::from(*b));
|
||||
} else {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(uri, "%{b:02X}");
|
||||
reveal_on_jobs(self, PathBuf::from(path));
|
||||
}
|
||||
}
|
||||
Ok((
|
||||
"dbus-send",
|
||||
vec![
|
||||
"--session".into(),
|
||||
"--print-reply".into(),
|
||||
"--reply-timeout=2000".into(),
|
||||
"--dest=org.freedesktop.FileManager1".into(),
|
||||
"/org/freedesktop/FileManager1".into(),
|
||||
"org.freedesktop.FileManager1.ShowItems".into(),
|
||||
uri.into(),
|
||||
"string:".into(),
|
||||
],
|
||||
))
|
||||
}
|
||||
_ => Err("File reveal is not available on this platform".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::PdfCraftApp;
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{NodeT, Queryable},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
const PDF: &[u8] = include_bytes!("../../tests/data/form.pdf");
|
||||
|
||||
/// An English app on a host whose jobs run when the test says.
|
||||
fn app_on(jobs: Arc<craft::host::ManualJobs>) -> PdfCraftApp {
|
||||
let info = craft::host::AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" };
|
||||
let host = craft::host::Host::builder(info).jobs(jobs).build();
|
||||
// PLAN: assumed `AppServices::detached()` (pdf-hub-w1): services with no clipboard, recovery directory, update source, intake or watch.
|
||||
let mut app = PdfCraftApp::with_host(Arc::new(host), crate::AppServices::detached());
|
||||
// PLAN: `set_option` takes the context (L-208).
|
||||
app.set_option(&egui::Context::default(), "language", "en").unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// An English app whose jobs never run.
|
||||
fn app() -> PdfCraftApp {
|
||||
app_on(Arc::new(craft::host::ManualJobs::new()))
|
||||
}
|
||||
|
||||
/// The unsaved-changes dialog's "don't keep the changes" and Cancel answers as the framework words
|
||||
/// them on this OS.
|
||||
fn answers() -> (String, String) {
|
||||
// PLAN: assumed paths `craft::ui::dialog::DialogWords`, `craft::ui::runtime::words::CommonWords`,
|
||||
// `craft::i18n::WordSet`; their fields display as their English text.
|
||||
use craft::i18n::WordSet as _;
|
||||
let dialog = craft::ui::dialog::DialogWords::english();
|
||||
let common = craft::ui::runtime::words::CommonWords::english();
|
||||
let dont_save = if cfg!(target_os = "macos") { dialog.unsaved_dont_save } else { dialog.unsaved_no };
|
||||
(dont_save.to_string(), common.cancel.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_close_uses_id_and_cancel_keeps_history_empty() {
|
||||
let mut app = crate::PdfCraftApp::new();
|
||||
app.open_bytes("first.pdf", Some("/tmp/first.pdf".into()), PDF.to_vec()).unwrap();
|
||||
let (first, first_tab) = (app.views[0].id, app.views[0].view_key());
|
||||
app.open_bytes("second.pdf", None, PDF.to_vec()).unwrap();
|
||||
app.session.apply(first, pdfcraft_engine::Edit::InsertBlankPage { at: 0, width: 300.0, height: 400.0 }).unwrap();
|
||||
app.tab_action(Action::Close(first_tab));
|
||||
assert_eq!(app.views.len(), 2);
|
||||
assert!(app.closed_tabs.is_empty());
|
||||
app.resolve_close(&egui::Context::default(), None);
|
||||
assert!(app.closed_tabs.is_empty());
|
||||
app.tab_action(Action::Close(first_tab));
|
||||
app.resolve_close(&egui::Context::default(), Some(false));
|
||||
assert_eq!(app.views.len(), 1);
|
||||
assert_eq!(app.closed_tabs, ["/tmp/first.pdf"]);
|
||||
assert_eq!(app.active, Some(0));
|
||||
app.close_tab(0);
|
||||
assert_eq!(app.closed_tabs.len(), 1, "pathless tabs are not recorded");
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| {
|
||||
let mut app = app();
|
||||
app.open_bytes("first.pdf", Some("/tmp/first.pdf".into()), PDF.to_vec()).unwrap();
|
||||
app.open_bytes("second.pdf", None, PDF.to_vec()).unwrap();
|
||||
app
|
||||
});
|
||||
h.run_steps(4);
|
||||
let (first, first_tab) = (h.state().views[0].id, h.state().views[0].view_key());
|
||||
h.state_mut().session.apply(first, pdfcraft_engine::Edit::InsertBlankPage { at: 0, width: 300.0, height: 400.0 }).unwrap();
|
||||
h.state_mut().tab_action(Action::Close(first_tab));
|
||||
h.run_steps(3);
|
||||
let (dont_save, cancel) = answers();
|
||||
assert_eq!(h.state().views.len(), 2);
|
||||
assert!(h.state().closed_tabs.is_empty());
|
||||
h.get_by_role_and_label(Role::Button, &cancel).click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views.len(), 2);
|
||||
assert!(h.state().closed_tabs.is_empty());
|
||||
h.state_mut().tab_action(Action::Close(first_tab));
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(Role::Button, &dont_save).click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views.len(), 1);
|
||||
assert_eq!(h.state().closed_tabs, ["/tmp/first.pdf"]);
|
||||
assert_eq!(h.state().active, Some(0));
|
||||
h.state_mut().close_tab(0);
|
||||
assert_eq!(h.state().closed_tabs.len(), 1, "pathless tabs are not recorded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -221,7 +156,7 @@ mod tests {
|
||||
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).unwrap();
|
||||
file.write_all(PDF).unwrap();
|
||||
drop(file);
|
||||
let mut app = crate::PdfCraftApp::new();
|
||||
let mut app = app();
|
||||
let path_text = path.to_str().unwrap();
|
||||
for _ in 0..12 {
|
||||
app.open_path(path_text);
|
||||
@@ -246,7 +181,7 @@ mod tests {
|
||||
let mut file = std::fs::OpenOptions::new().create_new(true).write(true).open(&path).unwrap();
|
||||
file.write_all(PDF).unwrap();
|
||||
drop(file);
|
||||
let mut app = crate::PdfCraftApp::new();
|
||||
let mut app = app();
|
||||
app.open_path(text);
|
||||
app.close_tab(0);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
@@ -266,82 +201,27 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_failed_reveal_is_reported_back_to_the_ui_thread() {
|
||||
let mut app = crate::PdfCraftApp::new();
|
||||
app.run_inline = true;
|
||||
app.reveal_path(std::path::Path::new("/pdfcraft-no-such-dir/missing.pdf"));
|
||||
assert!(app.toast.is_none(), "nothing is shown until the UI thread takes the report");
|
||||
app.show_reveal_errors();
|
||||
assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("The file no longer exists"));
|
||||
let jobs = Arc::new(craft::host::ManualJobs::new());
|
||||
let held = jobs.clone();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_| app_on(held));
|
||||
h.run_steps(2);
|
||||
reveal_on_jobs(h.state_mut(), PathBuf::from("/pdfcraft-no-such-dir/missing.pdf"));
|
||||
assert_eq!(jobs.waiting(), 1, "the reveal is a job on the host");
|
||||
h.run_steps(2);
|
||||
// PLAN: assumed `craft::ui::notices::Notices::posted(&Context) -> usize` (L-206).
|
||||
let posted = |h: &Harness<'_, PdfCraftApp>| craft::ui::notices::Notices::posted(&h.ctx);
|
||||
assert_eq!(posted(&h), 0, "nothing is shown until the job ends");
|
||||
jobs.run_all();
|
||||
h.run_steps(2);
|
||||
assert_eq!(posted(&h), 1, "the failure is shown as a notice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_file_manager_falls_back_safely_and_reports_failure() {
|
||||
let path = std::path::Path::new("/tmp/年度 & reports/file.pdf");
|
||||
let mut calls = Vec::new();
|
||||
reveal_via("linux", path, |program, args| {
|
||||
calls.push((program.to_string(), args.to_vec()));
|
||||
if program == "dbus-send" { Err("FileManager1 unavailable".into()) } else { Ok(true) }
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.len(), 2);
|
||||
assert_eq!(calls[1], ("xdg-open".into(), vec![std::ffi::OsString::from("/tmp/年度 & reports")]));
|
||||
assert!(reveal_via("linux", path, |_, _| Ok(false)).is_err());
|
||||
assert!(reveal_via("linux", path, |_, _| Err("command missing".into())).is_err());
|
||||
}
|
||||
|
||||
/// #2579 (review of #2625): the `/select,"…"` argument reaches the process exactly as written.
|
||||
/// `cmd /c echo` prints its command line back; with Rust's own quoting (`args`) it would come
|
||||
/// back wrapped in quotes with the inner ones escaped, which Explorer reads as no selection.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_reveal_argument_reaches_the_process_as_written() {
|
||||
let (_, args) = reveal_command("windows", std::path::Path::new(r"C:\Reports\annual report.pdf")).unwrap();
|
||||
let mut echo: Vec<std::ffi::OsString> = ["/d", "/c", "echo"].map(std::ffi::OsString::from).to_vec();
|
||||
echo.extend(args);
|
||||
let out = reveal_process("cmd", &echo).output().unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim_end(), r#"/select,"C:\Reports\annual report.pdf""#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reveal_arguments_preserve_spaces_and_unicode() {
|
||||
let path = std::path::Path::new("/tmp/年度 report.pdf");
|
||||
let (exe, args) = reveal_command("macos", path).unwrap();
|
||||
assert_eq!(exe, "open");
|
||||
assert_eq!(args, [std::ffi::OsString::from("-R"), path.as_os_str().into()]);
|
||||
let (exe, args) = reveal_command("windows", path).unwrap();
|
||||
assert_eq!(exe, "explorer.exe");
|
||||
assert_eq!(args, [std::ffi::OsString::from("/select,\"/tmp/年度 report.pdf\"")]);
|
||||
// #2579: the path is quoted after the comma, never the whole argument, which Explorer
|
||||
// reads as no selection and answers by opening Documents.
|
||||
let special = std::path::Path::new(r"C:\Reports\年度 report, #1 & (draft).pdf");
|
||||
let (_, windows) = reveal_command("windows", special).unwrap();
|
||||
assert_eq!(windows, [std::ffi::OsString::from(r#"/select,"C:\Reports\年度 report, #1 & (draft).pdf""#)]);
|
||||
assert!(reveal_command("windows", std::path::Path::new(r#"C:\a" b.pdf"#)).is_err(), "a quote can't end the path early");
|
||||
let (exe, args) = reveal_command("linux", path).unwrap();
|
||||
assert_eq!(exe, "dbus-send");
|
||||
assert_eq!(args[6], "array:string:file:///tmp/%E5%B9%B4%E5%BA%A6%20report.pdf");
|
||||
let (_, args) = reveal_command("linux", std::path::Path::new("/tmp/年度 report,#&'$.pdf")).unwrap();
|
||||
assert_eq!(args[6], "array:string:file:///tmp/%E5%B9%B4%E5%BA%A6%20report%2C%23%26%27%24.pdf");
|
||||
assert_eq!(args[5], "org.freedesktop.FileManager1.ShowItems");
|
||||
assert_eq!(args[7], "string:");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod ui_tests {
|
||||
use crate::PdfCraftApp;
|
||||
use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{NodeT, Queryable},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn inactive_tab_menu_closes_target_and_disables_unavailable_actions() {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
let mut app = app();
|
||||
for name in ["first.pdf", "second.pdf"] {
|
||||
app.open_bytes(name, None, include_bytes!("../../tests/data/form.pdf").to_vec()).unwrap();
|
||||
app.open_bytes(name, None, PDF.to_vec()).unwrap();
|
||||
}
|
||||
app
|
||||
});
|
||||
|
||||
+88
-218
@@ -17,11 +17,14 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use egui::{Pos2, Rect, Sense, Stroke, vec2};
|
||||
use craft::quit::CloseScope;
|
||||
use craft::ui::canvas::{SplitAt, SplitLayout, SplitViews, TabDropTarget};
|
||||
use craft::ui::contract::Bind; // PLAN: assumed path of `Bind` through the facade
|
||||
use pdfcraft_engine::DocId;
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::{CloseRequest, PdfCraftApp};
|
||||
use crate::PdfCraftApp;
|
||||
// PLAN: chrome.rs (pdf-chrome-w10) declares `pub(crate) mod doc_tabs;` for this path.
|
||||
use crate::chrome::doc_tabs::{StripTab, strip};
|
||||
|
||||
/// Where a tab is shown.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
@@ -71,23 +74,6 @@ impl Split {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the divider between the panes may go, as a share of the page area.
|
||||
const FRACTION: std::ops::RangeInclusive<f32> = 0.15..=0.85;
|
||||
/// The divider's width, and the height of the second pane's tab strip.
|
||||
const DIVIDER: f32 = 1.0;
|
||||
const PANE_STRIP: f32 = 30.0;
|
||||
|
||||
/// Where a dragged tab goes if it is let go now.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum TabDrop {
|
||||
/// Its own strip: it moves along it (the strip does that).
|
||||
Strip,
|
||||
/// The other pane.
|
||||
Pane(Place),
|
||||
/// The right half of a page area that isn't split: split right with it.
|
||||
SplitRight,
|
||||
}
|
||||
|
||||
/// Split view's state: see the module docs.
|
||||
#[derive(Default)]
|
||||
pub struct Panes {
|
||||
@@ -97,15 +83,12 @@ pub struct Panes {
|
||||
top_seq: u64,
|
||||
/// The pane of the tab active last: a new tab opens there.
|
||||
focus: Place,
|
||||
/// The main tab strip and the page area, last frame.
|
||||
pub(crate) main_strip: Option<Rect>,
|
||||
pub(crate) page_rect: Option<Rect>,
|
||||
/// The tab (by view key) whose context menu is open, and the strip it was opened on.
|
||||
pub(crate) tab_menu: Option<(Place, u64)>,
|
||||
/// Each open document's edit generation as last seen.
|
||||
generations: HashMap<DocId, u64>,
|
||||
/// The pane being drawn now (for what belongs to one pane only).
|
||||
pub(crate) drawing: Place,
|
||||
/// Where a dragged tab would land, painted over the page area this frame.
|
||||
pub(crate) drop_hint: Option<Rect>,
|
||||
}
|
||||
|
||||
impl Panes {
|
||||
@@ -119,26 +102,6 @@ impl Panes {
|
||||
}
|
||||
}
|
||||
|
||||
/// The two panes and the divider between them, in `area`.
|
||||
fn layout(area: Rect, split: Split) -> (Rect, Rect, Rect) {
|
||||
let f = if split.fraction.is_finite() { split.fraction.clamp(*FRACTION.start(), *FRACTION.end()) } else { 0.5 };
|
||||
if split.down {
|
||||
let y = (area.top() + area.height() * f).round();
|
||||
(
|
||||
Rect::from_min_max(area.min, egui::pos2(area.right(), y)),
|
||||
Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + DIVIDER)),
|
||||
Rect::from_min_max(egui::pos2(area.left(), y + DIVIDER), area.max),
|
||||
)
|
||||
} else {
|
||||
let x = (area.left() + area.width() * f).round();
|
||||
(
|
||||
Rect::from_min_max(area.min, egui::pos2(x, area.bottom())),
|
||||
Rect::from_min_max(egui::pos2(x, area.top()), egui::pos2(x + DIVIDER, area.bottom())),
|
||||
Rect::from_min_max(egui::pos2(x + DIVIDER, area.top()), area.max),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PdfCraftApp {
|
||||
/// The tabs shown in `place`, in their strip's order (indexes into `views`).
|
||||
pub fn tabs_in(&self, place: Place) -> Vec<usize> {
|
||||
@@ -259,12 +222,11 @@ impl PdfCraftApp {
|
||||
self.panes.generations.retain(|id, _| seen.contains(id));
|
||||
}
|
||||
|
||||
/// Move tab `from` along its strip: `to` is where it lands among the strip's tabs (`slots`, the
|
||||
/// strip's tabs in order, from first to last; `chrome::drop_index`). In split view a strip
|
||||
/// holds only some of the tabs, so this goes by the tab it lands next to rather than by index
|
||||
/// in `views`.
|
||||
pub(crate) fn move_tab_in_strip(&mut self, from: usize, slots: &[(usize, Rect)], to: usize) {
|
||||
let others: Vec<usize> = slots.iter().map(|(i, _)| *i).filter(|&i| i != from).collect();
|
||||
/// Move tab `from` along its strip: `to` is where it lands among the strip's other tabs (`tabs`,
|
||||
/// the strip's tabs in order, from first to last). In split view a strip holds only some of the
|
||||
/// tabs, so this goes by the tab it lands next to rather than by index in `views`.
|
||||
pub(crate) fn move_tab_in_strip(&mut self, from: usize, tabs: &[usize], to: usize) {
|
||||
let others: Vec<usize> = tabs.iter().copied().filter(|&i| i != from).collect();
|
||||
let (anchor, before) = match others.get(to) {
|
||||
Some(&a) => (a, true),
|
||||
None => match others.last() {
|
||||
@@ -272,7 +234,7 @@ impl PdfCraftApp {
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
if from >= self.views.len() || slots.iter().position(|(i, _)| *i == from) == Some(to) {
|
||||
if from >= self.views.len() || tabs.iter().position(|&i| i == from) == Some(to) {
|
||||
return;
|
||||
}
|
||||
let Some(anchor) = self.views.get(anchor).map(|v| v.pane.key) else { return };
|
||||
@@ -395,8 +357,8 @@ impl PdfCraftApp {
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// Quitting or File ▸ Close all with unsaved documents: one tab per document first, so each
|
||||
/// document is asked about once (a tab with typing of its own stays, to be asked about).
|
||||
/// Quitting with unsaved documents: one tab per document first, so each document is asked
|
||||
/// about once (a tab with typing of its own stays, to be asked about).
|
||||
fn one_tab_per_document(&mut self) {
|
||||
for i in (0..self.views.len()).rev() {
|
||||
let Some(id) = self.views.get(i).map(|v| v.id) else { continue };
|
||||
@@ -430,55 +392,6 @@ impl PdfCraftApp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a tab dragged from `from`'s strip lands if let go at `pos`: the other pane, the right
|
||||
/// half of a page area that isn't split, or else its own strip (as before split view, the
|
||||
/// tab moves along the strip wherever it is let go).
|
||||
pub(crate) fn drop_target(&self, pos: Pos2, from: Place) -> TabDrop {
|
||||
if from != Place::Main && self.panes.main_strip.is_some_and(|r| r.contains(pos)) {
|
||||
return TabDrop::Pane(Place::Main);
|
||||
}
|
||||
let Some(page) = self.panes.page_rect.filter(|r| r.contains(pos)) else { return TabDrop::Strip };
|
||||
match self.panes.split {
|
||||
Some(split) => {
|
||||
let (first, _, second) = layout(page, split);
|
||||
if second.contains(pos) && from != Place::Second {
|
||||
TabDrop::Pane(Place::Second)
|
||||
} else if first.contains(pos) && from != Place::Main {
|
||||
TabDrop::Pane(Place::Main)
|
||||
} else {
|
||||
TabDrop::Strip
|
||||
}
|
||||
}
|
||||
None if pos.x >= page.center().x => TabDrop::SplitRight,
|
||||
None => TabDrop::Strip,
|
||||
}
|
||||
}
|
||||
|
||||
/// The area a [`TabDrop`] would fill, for the hint drawn while dragging.
|
||||
pub(crate) fn drop_hint_rect(&self, drop: TabDrop) -> Option<Rect> {
|
||||
let page = self.panes.page_rect?;
|
||||
match drop {
|
||||
TabDrop::Pane(p) => {
|
||||
let split = self.panes.split?;
|
||||
let (first, _, second) = layout(page, split);
|
||||
Some(if p == Place::Second { second } else { first })
|
||||
}
|
||||
TabDrop::SplitRight => Some(Rect::from_min_max(egui::pos2(page.center().x, page.top()), page.max)),
|
||||
TabDrop::Strip => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Let tab `index` go at `drop`.
|
||||
pub(crate) fn drop_tab(&mut self, index: usize, drop: TabDrop) {
|
||||
match drop {
|
||||
TabDrop::Strip => {}
|
||||
TabDrop::Pane(place) => {
|
||||
self.move_tab_to(index, place);
|
||||
}
|
||||
TabDrop::SplitRight => self.split_tab(index, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tabs on screen now: what each pane shows (and a comparison's other half).
|
||||
pub(crate) fn views_on_screen(&self) -> Vec<usize> {
|
||||
let mut shown = Vec::new();
|
||||
@@ -499,29 +412,89 @@ impl PdfCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Once a frame, before anything is drawn: the panes settle (and a quit or Close all asks about
|
||||
/// each document once).
|
||||
/// Once a frame, before anything is drawn: the panes settle (and a quit asks about each document
|
||||
/// once).
|
||||
pub(crate) fn frame(app: &mut PdfCraftApp) {
|
||||
if matches!(app.close_request, Some(CloseRequest::Quit | CloseRequest::All)) {
|
||||
if app.close_guard.as_ref().is_some_and(|guard| guard.scope() == CloseScope::Quit) {
|
||||
app.one_tab_per_document();
|
||||
}
|
||||
app.drain_reveals();
|
||||
app.settle_panes();
|
||||
}
|
||||
|
||||
/// The page area: the main pane's tab (Home or Combine files while it has none, a comparison's
|
||||
/// two halves), or split view's two panes.
|
||||
pub(crate) fn page_area(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
app.panes.page_rect = Some(ui.max_rect());
|
||||
app.panes.drawing = Place::Main;
|
||||
if let Some(hint) = app.panes.drop_hint.take() {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("pane-drop-hint")));
|
||||
painter.rect(hint.shrink(4.0), 6.0, t.accent.gamma_multiply(0.12), Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
let main = app.pane_front(Place::Main);
|
||||
match app.panes.split.and_then(|s| Some((s, app.pane_front(Place::Second)?))) {
|
||||
Some((split, second)) => split_area(app, split, main, second, ui),
|
||||
None => main_pane(app, main, ui),
|
||||
let split = app.panes.split.and_then(|s| Some((s, app.pane_front(Place::Second)?)));
|
||||
let (layout, count, mut at) = match split {
|
||||
Some((s, _)) if s.down => (SplitLayout::TwoUpHorizontal, 2, SplitAt::lines(Vec::new(), vec![s.fraction])),
|
||||
Some((s, _)) => (SplitLayout::TwoUpVertical, 2, SplitAt::lines(vec![s.fraction], Vec::new())),
|
||||
None => (SplitLayout::Tile, 1, SplitAt::default()),
|
||||
};
|
||||
let shown = at.clone();
|
||||
let active = usize::from(app.active.and_then(|i| app.views.get(i)).is_some_and(|v| v.pane.place == Place::Second));
|
||||
// The drop rule reads the open views up front: the views closure below borrows the app.
|
||||
let open: HashSet<u64> = app.views.iter().map(|v| v.pane.key).collect();
|
||||
let views = SplitViews::new(tl!("Pages").to_string(), layout, Bind::bound(&mut at))
|
||||
.count(1)
|
||||
.active(active)
|
||||
.takes_tabs::<StripTab>(|documents, _| !documents.is_empty() && documents.iter().all(|d| matches!(d, StripTab::View(key) if open.contains(key))))
|
||||
.show(ui, |ui, body| {
|
||||
let rects = shown.placed(layout, count, body.rect, body.env.direction().is_rtl());
|
||||
for (pane, rect) in rects.iter().enumerate() {
|
||||
let place = if pane == 0 { Place::Main } else { Place::Second };
|
||||
let salt = if place == Place::Second { "second-pane" } else { "main-pane" };
|
||||
// PLAN: framework gap F-14 (a per-pane body on `SplitViews`); the panes are placed by hand until it lands.
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(*rect).id_salt(salt));
|
||||
child.shrink_clip_rect(*rect);
|
||||
if place == Place::Second {
|
||||
strip(app, &mut child, place);
|
||||
}
|
||||
let room = child.available_rect_before_wrap();
|
||||
let mut body_ui = child.new_child(egui::UiBuilder::new().max_rect(room).id_salt("body"));
|
||||
body_ui.shrink_clip_rect(room);
|
||||
// The strip may have closed or moved a tab just now: look the pane's tab up again (a
|
||||
// pane left empty ends split view next frame).
|
||||
let front = if place == Place::Second { app.pane_front(place) } else { main.filter(|&i| i < app.views.len()) };
|
||||
app.panes.drawing = place;
|
||||
match (place, front) {
|
||||
(Place::Main, _) => main_pane(app, front, &mut body_ui),
|
||||
(Place::Second, Some(index)) => crate::canvas::document_area(app, index, &mut body_ui),
|
||||
(Place::Second, None) => {}
|
||||
}
|
||||
app.panes.drawing = Place::Main;
|
||||
}
|
||||
});
|
||||
let output = views.output;
|
||||
// (While Home shows in the main pane, a click there stays on Home.)
|
||||
match output.activated {
|
||||
Some(0) if main.is_some() => app.activate_place(Place::Main),
|
||||
Some(1) => app.activate_place(Place::Second),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(s) = app.panes.split.as_mut()
|
||||
&& let Some(&fraction) = at.columns.first().or(at.rows.first())
|
||||
&& fraction.is_finite()
|
||||
{
|
||||
s.fraction = fraction;
|
||||
}
|
||||
if let Some(drop) = output.tab_drop {
|
||||
for document in drop.documents {
|
||||
let StripTab::View(key) = document else { continue };
|
||||
let Some(index) = app.tab_with_key(key) else { continue };
|
||||
match drop.target {
|
||||
TabDropTarget::Pane(pane) => {
|
||||
let place = if pane == 0 { Place::Main } else { Place::Second };
|
||||
if app.place_of(index) != Some(place) {
|
||||
app.move_tab_to(index, place);
|
||||
}
|
||||
}
|
||||
TabDropTarget::SplitEnd => app.split_tab(index, false),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,106 +509,3 @@ fn main_pane(app: &mut PdfCraftApp, main: Option<usize>, ui: &mut egui::Ui) {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a press this frame began in `rect` on the page area itself, or on one of the floating
|
||||
/// bars of the view drawn there (not on a dialog, menu or panel over it).
|
||||
fn pressed_in(ui: &egui::Ui, rect: Rect, place: Place, view: Option<&crate::DocView>) -> bool {
|
||||
let Some(pos) = ui.input(|i| if i.pointer.any_pressed() { i.pointer.press_origin() } else { None }) else { return false };
|
||||
if !rect.contains(pos) {
|
||||
return false;
|
||||
}
|
||||
match ui.ctx().layer_id_at(pos) {
|
||||
None => true,
|
||||
Some(layer) => {
|
||||
let quick = if place == Place::Main { egui::Id::unique("quick-bar") } else { egui::Id::unique(("quick-bar", place)) };
|
||||
layer == ui.layer_id()
|
||||
|| [quick, egui::Id::unique("camera-bar")].contains(&layer.id)
|
||||
|| view.is_some_and(|v| egui::Id::unique(("find-bar", v.view_key())) == layer.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Split view: the main pane, the divider and the second pane with its strip. A press in a pane
|
||||
/// makes it the active one before it is drawn, so the click acts there.
|
||||
fn split_area(app: &mut PdfCraftApp, split: Split, main: Option<usize>, second: usize, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let area = ui.max_rect();
|
||||
let (first, divider, other) = layout(area, split);
|
||||
if !app.modal_open() && !app.palette_open {
|
||||
// (While Home shows in the main pane, a click there stays on Home.)
|
||||
if main.is_some() && pressed_in(ui, first, Place::Main, main.and_then(|i| app.views.get(i))) {
|
||||
app.activate_place(Place::Main);
|
||||
} else if pressed_in(ui, other, Place::Second, app.views.get(second)) {
|
||||
app.activate_place(Place::Second);
|
||||
}
|
||||
}
|
||||
// The divider, dragged to share the area differently.
|
||||
let grab = if split.down { divider.expand2(vec2(0.0, 3.0)) } else { divider.expand2(vec2(3.0, 0.0)) };
|
||||
let response = ui.interact(grab, ui.scope_id().with("pane-divider"), Sense::drag());
|
||||
if response.hovered() || response.dragged() {
|
||||
ui.ctx().set_cursor_icon(if split.down { egui::CursorIcon::ResizeVertical } else { egui::CursorIcon::ResizeHorizontal });
|
||||
}
|
||||
if response.dragged()
|
||||
&& let Some(p) = ui.ctx().pointer_latest_pos()
|
||||
&& let Some(s) = app.panes.split.as_mut()
|
||||
{
|
||||
let f = if split.down { (p.y - area.top()) / area.height().max(1.0) } else { (p.x - area.left()) / area.width().max(1.0) };
|
||||
if f.is_finite() {
|
||||
s.fraction = f.clamp(*FRACTION.start(), *FRACTION.end());
|
||||
}
|
||||
}
|
||||
ui.painter().rect_filled(divider, 0.0, if response.dragged() || response.hovered() { t.accent } else { t.divider });
|
||||
let active = app.active.and_then(|i| app.views.get(i)).map(|v| v.pane.place);
|
||||
pane(app, ui, first, Place::Main, main, active == Some(Place::Main));
|
||||
pane(app, ui, other, Place::Second, Some(second), active == Some(Place::Second));
|
||||
}
|
||||
|
||||
/// One pane of split view: the second has its own tab strip above its page area.
|
||||
fn pane(app: &mut PdfCraftApp, ui: &mut egui::Ui, rect: Rect, place: Place, front: Option<usize>, active: bool) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let salt = if place == Place::Second { "second-pane" } else { "main-pane" };
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).id_salt(salt));
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
let body = if place == Place::Second {
|
||||
let strip = Rect::from_min_size(rect.min, vec2(rect.width(), PANE_STRIP));
|
||||
crate::chrome::pane_tab_strip(app, &mut child, strip, place);
|
||||
Rect::from_min_max(egui::pos2(rect.left(), strip.bottom()), rect.max)
|
||||
} else {
|
||||
rect
|
||||
};
|
||||
// The strip may have closed or moved a tab just now: look the pane's tab up again (a pane
|
||||
// left empty ends split view next frame).
|
||||
let front = if place == Place::Second { app.pane_front(place) } else { front.filter(|&i| i < app.views.len()) };
|
||||
let mut body_ui = child.new_child(egui::UiBuilder::new().max_rect(body).id_salt("body"));
|
||||
body_ui.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
app.panes.drawing = place;
|
||||
match (place, front) {
|
||||
(Place::Main, _) => main_pane(app, front, &mut body_ui),
|
||||
(Place::Second, Some(index)) => crate::canvas::document_area(app, index, &mut body_ui),
|
||||
(Place::Second, None) => {}
|
||||
}
|
||||
app.panes.drawing = Place::Main;
|
||||
// The active pane is marked along its top edge.
|
||||
if active {
|
||||
let edge = Rect::from_min_size(rect.min, vec2(rect.width(), 2.0));
|
||||
ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique(("active-pane", salt)))).rect_filled(edge, 0.0, t.accent);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_panes_share_the_area_and_the_divider_stays_inside() {
|
||||
let area = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 600.0));
|
||||
let (a, d, b) = layout(area, Split { down: false, fraction: 0.5 });
|
||||
assert_eq!(a.right(), d.left());
|
||||
assert_eq!(d.right(), b.left());
|
||||
assert_eq!(b.right(), 1000.0);
|
||||
let (a, _, b) = layout(area, Split { down: true, fraction: 2.0 });
|
||||
assert!(a.height() <= 600.0 * 0.85 + 1.0 && b.height() > 0.0, "a fraction past the end is held back");
|
||||
let (a, _, _) = layout(area, Split { down: false, fraction: f32::NAN });
|
||||
assert_eq!(a.width(), 500.0, "a fraction that isn't a number shares evenly");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,28 @@ use egui::accesskit::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use craft::ui::primitives::textures::TextureState; // PLAN: assumed facade path of `TextureState`
|
||||
use pdfcraft_ui_egui::PdfCraftApp;
|
||||
use pdfcraft_ui_egui::panes::Place;
|
||||
|
||||
/// The size of view `i`'s first page picture once it is drawn; a stand-in for a page still loading
|
||||
/// is not a drawn page.
|
||||
fn page_size(s: &PdfCraftApp, i: usize) -> Option<egui::Vec2> {
|
||||
match &s.views[i].placed.first()?.picture {
|
||||
TextureState::Ready(texture) => Some(texture.size_vec2()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The label of the unsaved-changes dialog's "don't keep the changes" answer on this OS, as the
|
||||
/// framework words it.
|
||||
fn dont_save() -> String {
|
||||
// PLAN: assumed paths `craft::ui::dialog::DialogWords` and `craft::i18n::WordSet`; the fields display as their English text.
|
||||
use craft::i18n::WordSet as _;
|
||||
let words = craft::ui::dialog::DialogWords::english();
|
||||
if cfg!(target_os = "macos") { words.unsaved_dont_save } else { words.unsaved_no }.to_string()
|
||||
}
|
||||
|
||||
/// `pages` portrait pages (300 × 400) with a line of text each.
|
||||
fn fixture(pages: usize) -> Vec<u8> {
|
||||
let mut objs: Vec<String> = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()];
|
||||
@@ -141,8 +160,8 @@ fn the_same_document_in_both_panes_is_one_document_with_one_undo() {
|
||||
assert_eq!(h.state().views[first].id, h.state().views[second].id, "one document");
|
||||
assert_eq!(h.state().session.docs().len(), 1);
|
||||
// Both panes draw the portrait page.
|
||||
let portrait = |s: &PdfCraftApp, i: usize| s.views[i].drawn_page_size(0).is_some_and(|[w, hgt]| hgt > w);
|
||||
let landscape = |s: &PdfCraftApp, i: usize| s.views[i].drawn_page_size(0).is_some_and(|[w, hgt]| w > hgt);
|
||||
let portrait = |s: &PdfCraftApp, i: usize| page_size(s, i).is_some_and(|size| size.y > size.x);
|
||||
let landscape = |s: &PdfCraftApp, i: usize| page_size(s, i).is_some_and(|size| size.x > size.y);
|
||||
wait(&mut h, "both panes drawn", |s| portrait(s, first) && portrait(s, second));
|
||||
// Each pane scrolls on its own: the second goes to page 3.
|
||||
h.state_mut().views[second].go_to_page(2);
|
||||
@@ -179,7 +198,7 @@ fn the_same_document_in_both_panes_is_one_document_with_one_undo() {
|
||||
let comment = NewAnnotation { page: 0, style: Style::default_for(&shape), shape, contents: String::new(), author: String::new() };
|
||||
assert!(h.state_mut().apply_edit(Edit::AddAnnotation(comment)));
|
||||
h.run_steps(1);
|
||||
assert!(h.state().views[second].drawn_page_size(0).is_none(), "the second pane's page is being drawn again");
|
||||
assert!(page_size(h.state(), second).is_none(), "the second pane's page is being drawn again");
|
||||
wait(&mut h, "both panes drawn again", |s| portrait(s, first) && portrait(s, second));
|
||||
}
|
||||
|
||||
@@ -218,7 +237,7 @@ fn split_again_or_closing_a_panes_last_tab_ends_split_view() {
|
||||
let second = h.state().views.iter().position(|v| v.place() == Place::Second).unwrap();
|
||||
h.state_mut().request_close_tab(second);
|
||||
h.run_steps(3);
|
||||
assert!(h.state().close_request.is_none(), "no save prompt: the document is still open");
|
||||
assert!(h.query_by_role_and_label(Role::Button, &dont_save()).is_none(), "no save prompt: the document is still open");
|
||||
assert!(h.state().panes.split.is_none());
|
||||
assert_eq!(h.state().views.len(), 1);
|
||||
assert!(h.state().session.get(h.state().views[0].id).unwrap().dirty, "its edit is still there");
|
||||
@@ -239,9 +258,9 @@ fn split_again_or_closing_a_panes_last_tab_ends_split_view() {
|
||||
};
|
||||
h.state_mut().views[second].fill_text = Some(typed);
|
||||
h.state_mut().request_close_tab(second);
|
||||
assert_eq!(h.state().close_request, Some(pdfcraft_ui_egui::CloseRequest::Tab(id)), "the typing is asked about");
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().resolve_close(&ctx, Some(false));
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_role_and_label(Role::Button, &dont_save()).is_some(), "the typing is asked about");
|
||||
h.get_by_role_and_label(Role::Button, &dont_save()).click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().views.len(), 1);
|
||||
assert_eq!(h.state().views[0].view_key(), first_key, "the view asked about closed, the other stayed");
|
||||
@@ -285,17 +304,16 @@ fn a_tab_dropped_on_the_right_half_of_the_page_splits_right_with_it() {
|
||||
assert!(h.state().panes.split.is_some(), "dropped on the right half: split view");
|
||||
assert_eq!(h.state().views[index(&h, "one.pdf")].place(), Place::Second);
|
||||
assert_eq!(h.state().views[index(&h, "two.pdf")].place(), Place::Main);
|
||||
// Dragged back onto the main strip, it rejoins it and split view ends.
|
||||
// Dragged back onto a tab of the main strip, it rejoins it and split view ends.
|
||||
let strip = h.get_by_role_and_label(Role::Tab, "two.pdf").rect();
|
||||
drag_tab(&mut h, "one.pdf", strip.right_center() + egui::vec2(40.0, 0.0));
|
||||
drag_tab(&mut h, "one.pdf", strip.center());
|
||||
assert!(h.state().panes.split.is_none());
|
||||
assert_eq!(places(&h), [Place::Main, Place::Main]);
|
||||
// Let go outside the window, a tab moves along the strip as before split view (here to the
|
||||
// front), and nothing splits.
|
||||
// Let go outside the window, the strip keeps its order and nothing splits.
|
||||
let ids: Vec<_> = h.state().views.iter().map(|v| v.id).collect();
|
||||
drag_tab(&mut h, "two.pdf", egui::pos2(-200.0, 300.0));
|
||||
assert!(h.state().panes.split.is_none());
|
||||
assert_eq!(h.state().views.iter().map(|v| v.id).collect::<Vec<_>>(), [ids[1], ids[0]]);
|
||||
assert_eq!(h.state().views.iter().map(|v| v.id).collect::<Vec<_>>(), [ids[0], ids[1]]);
|
||||
}
|
||||
|
||||
/// Regression: closing the second pane's tab from its own strip, with the same document in both
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use pdfcraft_ui_egui::PdfCraftApp;
|
||||
|
||||
fn harness() -> Harness<'static, PdfCraftApp> {
|
||||
@@ -26,16 +27,15 @@ fn each_panes_find_input_has_its_own_id() {
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Backslash);
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().views.len(), 2);
|
||||
let (first, second) = (h.state().views[0].find_input_id(), h.state().views[1].find_input_id());
|
||||
assert_ne!(first, second, "one find field id per pane");
|
||||
|
||||
// Find open in both panes, the second one asking for the focus last.
|
||||
h.state_mut().views[0].open_find();
|
||||
h.state_mut().views[1].open_find();
|
||||
h.run_steps(4);
|
||||
let focused = h.ctx.memory(|m| m.focused());
|
||||
assert_eq!(focused, Some(second), "the focus is in the pane that asked last");
|
||||
assert!(!h.ctx.memory(|m| m.has_focus(first)), "the other pane's field does not share it");
|
||||
assert_eq!(h.get_all_by_label("Find text").count(), 2, "one find field per pane");
|
||||
let mut fields = h.get_all_by_label("Find text");
|
||||
let (first, second) = (fields.next().unwrap(), fields.next().unwrap());
|
||||
assert!(second.accesskit_node().is_focused(), "the focus is in the pane that asked last");
|
||||
assert!(!first.accesskit_node().is_focused(), "the other pane's field does not share it");
|
||||
|
||||
// Typing goes to one query only.
|
||||
h.event(egui::Event::Text("abc".into()));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Split view: the two views of one document render through its one pool, and an edit made after
|
||||
//! they collected the frame's demand (#3149) leaves nothing of the old pages in that pool.
|
||||
//! Split view: an edit made after both views drew their frame (#3149) leaves neither showing the
|
||||
//! old page.
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
use craft::ui::primitives::textures::TextureState; // PLAN: assumed facade path of `TextureState`
|
||||
use egui_kittest::Harness;
|
||||
use pdfcraft_ui_egui::PdfCraftApp;
|
||||
|
||||
@@ -29,18 +30,27 @@ fn wait(h: &mut Harness<'static, PdfCraftApp>, what: &str, ready: impl Fn(&PdfCr
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
/// The size of view `i`'s first page picture once it is drawn; a stand-in for a page still loading
|
||||
/// is never counted.
|
||||
fn page_size(s: &PdfCraftApp, i: usize) -> Option<egui::Vec2> {
|
||||
match &s.views[i].placed.first()?.picture {
|
||||
TextureState::Ready(texture) => Some(texture.size_vec2()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The palette runs its command after the page area was drawn, as a dialog's OK does: the page
|
||||
/// turns after both views asked for this frame's rasters at the old size. Neither view may keep
|
||||
/// that demand (the single-view path drops it; the shared one handed it to the pool).
|
||||
/// turns after both views drew the old one. Both panes must end up drawing the turned page, never
|
||||
/// the stale portrait one.
|
||||
#[test]
|
||||
fn a_late_edit_drops_both_views_stale_demand() {
|
||||
fn a_late_edit_turns_the_page_in_both_panes() {
|
||||
let mut h = harness();
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Backslash);
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().views.len(), 2);
|
||||
assert_eq!(h.state().views[0].id, h.state().views[1].id, "one document in both panes");
|
||||
let portrait = |s: &PdfCraftApp, i: usize| s.views[i].drawn_page_size(0).is_some_and(|[w, hgt]| hgt > w);
|
||||
let landscape = |s: &PdfCraftApp, i: usize| s.views[i].drawn_page_size(0).is_some_and(|[w, hgt]| w > hgt);
|
||||
let portrait = |s: &PdfCraftApp, i: usize| page_size(s, i).is_some_and(|size| size.y > size.x);
|
||||
let landscape = |s: &PdfCraftApp, i: usize| page_size(s, i).is_some_and(|size| size.x > size.y);
|
||||
wait(&mut h, "both panes drawn", |s| portrait(s, 0) && portrait(s, 1));
|
||||
let id = h.state().views[0].id;
|
||||
let rotation = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(id).unwrap().info.pages[0].rotation;
|
||||
@@ -56,9 +66,6 @@ fn a_late_edit_drops_both_views_stale_demand() {
|
||||
}
|
||||
}
|
||||
assert_eq!(rotation(&h), 90, "the palette turned the page");
|
||||
for (k, v) in h.state().views.iter().enumerate() {
|
||||
assert_eq!(v.raster_memory().pending_requests, 0, "view {k} kept demand made for the page before it turned");
|
||||
}
|
||||
// And both panes draw the turned page.
|
||||
// Both panes draw the turned page.
|
||||
wait(&mut h, "both panes drawn again", |s| landscape(s, 0) && landscape(s, 1));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user