From 01daa58e2d467371497507da47470f334de4a9c2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:28 -0500 Subject: [PATCH] pdf-hub-w1: net change of 2 commits - pdf-hub-w1: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot) - pdf-hub-w1: review fixes (review-1) --- Cargo.toml | 2 + apps/pdfcraft-web/src/main.rs | 92 ++-- apps/pdfcraft/src/main.rs | 363 +++++--------- crates/ui-egui/Cargo.toml | 14 +- crates/ui-egui/src/app.rs | 809 +++++++++++++------------------- crates/ui-egui/src/app/frame.rs | 215 +-------- crates/ui-egui/src/lib.rs | 571 ++++++++-------------- crates/ui-egui/src/state.rs | 193 +------- 8 files changed, 725 insertions(+), 1534 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index be7ca0fefc..43da421551 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,8 @@ craft-cms = { git = "https://github.com/storytold/craft-libs", version = "0.1.0" craft-zip = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "527c2750e37fb8bf576dc9a9e07ffc60b9d63717" } # Whether a path stored in a document may be opened (GoToR link targets). craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "527c2750e37fb8bf576dc9a9e07ffc60b9d63717" } +# The installed-font catalog the engine reads faces from (Edit ▸ Add text, font embedding). +craft-font-catalog = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "527c2750e37fb8bf576dc9a9e07ffc60b9d63717", default-features = false } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "527c2750e37fb8bf576dc9a9e07ffc60b9d63717", features = ["ui"] } craft-pdf = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "527c2750e37fb8bf576dc9a9e07ffc60b9d63717", features = ["cos", "crypt", "filters"] } diff --git a/apps/pdfcraft-web/src/main.rs b/apps/pdfcraft-web/src/main.rs index a168b27101..26a80e1282 100644 --- a/apps/pdfcraft-web/src/main.rs +++ b/apps/pdfcraft-web/src/main.rs @@ -3,12 +3,16 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +// PLAN: apps/pdfcraft-web/Cargo.toml needs `craft = { workspace = true, features = ["host", "platform", "ui", "web-host"] }`; the manifest is not in this set's Files table. + #[cfg(any(target_arch = "wasm32", test))] mod api; #[cfg(target_arch = "wasm32")] fn main() { - use pdfcraft_ui_egui::PdfCraftApp; + use std::sync::Arc; + + use pdfcraft_ui_egui::{AppServices, PdfCraftApp}; let options = eframe::WebOptions { renderer: eframe::Renderer::Glow, ..Default::default() }; wasm_bindgen_futures::spawn_local(async move { @@ -18,38 +22,35 @@ fn main() { canvas, options, Box::new(|cc| { - let mut app = PdfCraftApp::new(); - // "printcraft": settings saved under the app's former name, PrintCraft. - if let Some(json) = cc.storage.and_then(|s| s.get_string("pdfcraft").or_else(|| s.get_string("printcraft"))) { - app.restore(&json); - } + let ctx = cc.egui_ctx.clone(); + let wake = craft::host::Wake::new(move || ctx.request_repaint()); + // Files to open: a `?file=` download, the embedding page's `pdfcraft:open`, a drop. + let (intake, opens) = craft::platform::open::FileIntake::new(wake.clone()); + // Picks read the browser's files; saves download, or go to the embedding page. + let files = craft::web_host::files::BrowserFiles::new(wake, host::MAX_OPEN_BYTES); + let app_host = craft::host::Host::builder(pdfcraft_ui_egui::APP_INFO).files(Arc::new(files)).build(); + let mut app = PdfCraftApp::with_host(Arc::new(app_host), AppServices::system(&cc.egui_ctx, intake)); + // PLAN: assumed pdfcraft_ui_egui::settings::open() -> Store over craft::settings::BrowserFiles on wasm32, with the former PrintCraft key migrated (pdf-shell-w9, SH-C29, L-117). + let settings = pdfcraft_ui_egui::settings::open(); + app.apply_settings(&settings.get()); + app.attach_settings(settings); // `?file=` opens a PDF from a URL (same-origin or CORS-enabled). if let Some(url) = query_param("file") { - let inbox = app.startup_inbox.clone(); - let failed = app.failed_inbox.clone(); + let opens = opens.clone(); let ctx = cc.egui_ctx.clone(); wasm_bindgen_futures::spawn_local(async move { let name = url.rsplit('/').next().unwrap_or("document.pdf").split('?').next().unwrap_or("document.pdf").to_string(); match fetch_bytes(&url).await { - Ok(bytes) => { - if let Ok(mut q) = inbox.lock() { - q.push((name, bytes)); - } - } + Ok(bytes) => opens.open_bytes(name, Arc::from(bytes)), Err(e) => { eframe::web_sys::console::error_1(&format!("PdfCraft: could not fetch {url}: {e}").into()); // Shown in the app too, not only in the console (#173). - if let Ok(mut q) = failed.lock() { - q.push((name, e)); - } + let text = pdfcraft_ui_egui::i18n::fmt(pdfcraft_ui_egui::i18n::t("Couldn't open {name}: {e}"), &[("name", &name), ("e", &e)]); + let _ = craft::ui::notices::NoticeCenter::new().post(&ctx, &craft::ui::notices::PostedNotice::new(text), &[]); } } - ctx.request_repaint(); }); } - // eframe never raises a close request on a browser reload or tab close, so `guard_quit` never - // prompts; ask the browser to confirm instead while a document has unsaved work or an OCR review is open (#812). - warn_before_unload(app.unsaved_flag.clone()); // Host modes (`host` below, over `craft-web-host`): `?host=parent`, a // same-origin page embedding PdfCraft in an iframe (such as the Nextcloud // app), or `data-host="page"` on the canvas, a host that runs the module in @@ -62,8 +63,7 @@ fn main() { { app.comment_prefs.author = author.chars().take(200).collect(); } - bridge.listen(app.startup_inbox.clone(), cc.egui_ctx.clone()); - app.host_save = Some(bridge.save_fn()); + bridge.listen(opens.clone()); app.host_dirty = Some(bridge.dirty_fn()); bridge.post_ready(); } else if query_param("host").as_deref() == Some("parent") { @@ -74,7 +74,9 @@ fn main() { // `?control`: `window.pdfcraft`, the page's command API (`api`). Opt-in: the control // channel keeps the accessibility tree of every frame. if query_param("control").is_some() { - api::install(app.attach_control(&cc.egui_ctx)); + let (requests, receiver) = std::sync::mpsc::channel(); + app.attach_control(receiver, None); + api::install(requests); } Ok(Box::new(app)) }), @@ -89,20 +91,6 @@ fn main() { }); } -#[cfg(target_arch = "wasm32")] -fn warn_before_unload(unsaved: std::sync::Arc) { - use eframe::wasm_bindgen::{JsCast, closure::Closure}; - let Some(window) = web_sys::window() else { return }; - let handler = Closure::::new(move |event: web_sys::Event| { - if unsaved.load(std::sync::atomic::Ordering::Relaxed) { - event.prevent_default(); - } - }); - if window.add_event_listener_with_callback("beforeunload", handler.as_ref().unchecked_ref()).is_ok() { - handler.forget(); - } -} - #[cfg(target_arch = "wasm32")] fn query_param(key: &str) -> Option { let search = web_sys::window()?.location().search().ok()?; @@ -143,14 +131,16 @@ fn app_canvas() -> Option { /// says `file: false` and a host sends `bytes`. /// - `pdfcraft:open` (from the host): `{ name, bytes }` holding a PDF. It opens in a tab, like a /// `?file=` URL; a file over [`host::MAX_OPEN_BYTES`] is refused before it is copied. -/// - `pdfcraft:save` (to the host): `{ name, saveAs, bytes }` when the user saves. The host stores -/// the file (and reports its own errors). +/// - `pdfcraft:save` (to the host): `{ name, saveAs, bytes }` when the user saves, posted by the +/// browser file service. The host stores the file (and reports its own errors). /// - `pdfcraft:dirty` whenever unsaved work appears or goes away, `pdfcraft:failed` when the app /// couldn't start. #[cfg(target_arch = "wasm32")] mod host { use std::rc::Rc; + use std::sync::Arc; + use craft::platform::open::IntakeSender; use craft_web_host::web::{FileData, Host, Message}; /// The app id in the host messages (`pdfcraft:ready`). @@ -160,7 +150,7 @@ mod host { const DEFAULT_NAME: &str = "document.pdf"; /// The largest file the host may hand over to open, checked before it is copied (the app's own readers have their own limits). - const MAX_OPEN_BYTES: u64 = 512 << 20; + pub(super) const MAX_OPEN_BYTES: u64 = 512 << 20; #[derive(Clone)] pub struct Bridge { @@ -185,20 +175,15 @@ mod host { let _ = self.host.post_failed(error, None); } - /// Hear `pdfcraft:open` and queue the file like a `?file=` download. - pub fn listen(&self, inbox: pdfcraft_ui_egui::Inbox, ctx: egui::Context) { + /// Hear `pdfcraft:open` and hand the file to the app's intake, like a `?file=` download. + pub fn listen(&self, opens: IntakeSender) { self.host.listen(move |message| { if let Message::Open { name, data } = message { - queue_open(&name, &data, &inbox, &ctx); + queue_open(&name, &data, &opens); } }); } - pub fn save_fn(&self) -> pdfcraft_ui_egui::HostSaveFn { - let host = self.host.clone(); - Box::new(move |name: &str, bytes: &[u8], save_as: bool| host.post_save(name, bytes, None, save_as)) - } - pub fn dirty_fn(&self) -> pdfcraft_ui_egui::HostDirtyFn { let host = self.host.clone(); // A host starts out clean: the first report is a change only when it is dirty. @@ -212,10 +197,10 @@ mod host { } } - /// The `pdfcraft:open` payload, `{ name, bytes }` where `bytes` holds a PDF: queue it like a - /// `?file=` download and wake the app. The crate has cleaned the name (and cut it to 255 + /// The `pdfcraft:open` payload, `{ name, bytes }` where `bytes` holds a PDF: hand it to the + /// intake, which wakes the app. The crate has cleaned the name (and cut it to 255 /// characters); a blank one comes as `document` and becomes `document.pdf`. - fn queue_open(name: &str, data: &FileData, inbox: &pdfcraft_ui_egui::Inbox, ctx: &egui::Context) { + fn queue_open(name: &str, data: &FileData, opens: &IntakeSender) { let name = if name == "document" { DEFAULT_NAME } else { name }.to_string(); let FileData::Bytes(view) = data else { eframe::web_sys::console::warn_1(&format!("PdfCraft: host file {name} came as a File; PdfCraft reads bytes only; not opened").into()); @@ -228,10 +213,7 @@ mod host { ); return; } - if let Ok(mut q) = inbox.lock() { - q.push((name, view.to_vec())); - } - ctx.request_repaint(); + opens.open_bytes(name, Arc::from(view.to_vec())); } } diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index a2a4e4410a..4940fc87c7 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -18,10 +18,14 @@ //! `--new-window` opens a window of its own. Without it, on Windows, a launch that only names files //! hands them to the PdfCraft already running, where they open as tabs (`single_instance`). //! -//! `--control ` enables the UI control channel (off by default): the app listens on a random -//! loopback port and writes `{"port", "token", "pid"}` to `` (owner-only permissions). The -//! app doesn't start if it can't. -//! Agents then drive it with `pdfcraft-cli ui --control …`. +//! `--control ` enables the UI control channel (off by default): the app listens on +//! 127.0.0.1: (`0` picks a free one) and asks for the token `--control-token ` or +//! `--control-token-file ` gives (or `PDFCRAFT_CONTROL_PORT`, `PDFCRAFT_CONTROL_TOKEN`, +//! `PDFCRAFT_CONTROL_TOKEN_FILE`). The app doesn't start if it can't listen. +//! Agents then drive it with `pdfcraft-cli ui …`. +//! +// PLAN: apps/pdfcraft/Cargo.toml needs `craft = { workspace = true, features = ["automation", "window", "platform", "settings", "host", "ui"] }`; the manifest is not in this set's Files table. +// PLAN: forms-02's `reorder_keys` wiring names no signature this set can call; its owner wires it here. // Release builds on Windows are GUI-subsystem programs, so launching the app doesn't open a console // window next to it (#57). `--version` and diagnostics then go nowhere when started from a terminal @@ -37,15 +41,9 @@ use pdfcraft_ui_egui::PdfCraftApp; #[cfg(target_os = "macos")] mod apple_events; mod compositor_gpu; -mod decorations; -mod logging; -#[cfg(target_os = "windows")] -mod motion; mod reopen; -mod settings; mod single_instance; mod startup; -mod text_scale; #[cfg(test)] #[path = "windows_manifest.rs"] mod windows_manifest; @@ -72,7 +70,8 @@ Options: --new-window open a window of its own instead of passing the files to a running PdfCraft --create-images [images…] put the images in one PDF and ask for the page DPI --combine files… add the files to the Combine files tab, of a running PdfCraft if there is one - --control enable the UI control channel (pdfcraft-cli ui --control …) + --control enable the UI control channel on 127.0.0.1: (0: a free port) + --control-token-file the control channel's token, from FILE (or --control-token ) --page N, --zoom 150, --layout continuous, --theme dark, … view settings applied once the files are open -h, --help print this and exit @@ -88,27 +87,16 @@ fn print_and_exit(text: &str) -> eframe::Result { Ok(()) } -/// The app was called PrintCraft before; settings saved then are under this key. -const LEGACY_STORAGE_KEY: &str = "printcraft"; - -/// The preferences folder (`app.ron`, docs/development.md). In portable mode -/// it is `PdfCraftData` beside the executable (#157). XDG desktops use the configuration base; -/// other platforms retain eframe's PdfCraft folder. Logs and recovery stay in the data folder. +// PLAN: assumed pdfcraft_ui_egui::settings::{resolution() -> &'static craft::settings::Resolved (the portable_dir() resolution), open() -> Store, dictionary_dir() -> Option} (pdf-shell-w9). +/// The preferences folder (`app.ron`, docs/development.md), as the settings resolution chose it: +/// `PdfCraftData` beside the executable in portable mode (#157), else the platform's folder. fn settings_dir() -> Option { - let legacy = eframe::storage_dir("PdfCraft"); - match settings::directory( - cfg!(all(unix, not(target_os = "macos"))), - pdfcraft_ui_egui::portable::data_dir(), - legacy.clone(), - std::env::var_os("XDG_CONFIG_HOME").map(std::path::PathBuf::from), - std::env::home_dir(), - ) { - Ok(dir) => dir, - Err(e) => { - log::warn!("could not migrate preferences to the XDG configuration folder; using the original location: {e}"); - legacy - } - } + pdfcraft_ui_egui::settings::resolution().dir.clone() +} + +/// Whether settings, logs and recovery live beside the executable (#157). +fn portable() -> bool { + pdfcraft_ui_egui::settings::resolution().rule == craft::settings::Rule::Portable } /// Move the settings and crash-recovery folders of the app's former name, PrintCraft, to the new @@ -116,7 +104,7 @@ fn settings_dir() -> Option { /// folder is left alone when the new one already exists or the move fails. A portable copy leaves /// the per-user folders alone. fn migrate_legacy_folders() { - if pdfcraft_ui_egui::portable::data_dir().is_some() { + if portable() { return; } let mut moves = vec![(eframe::storage_dir("PrintCraft"), eframe::storage_dir("PdfCraft"))]; @@ -213,8 +201,8 @@ fn main() -> eframe::Result { if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } - // First, so the panic hook and every start-up warning are recorded (`logging`). - let logger = logging::install(); + // First, so the panic hook and every start-up warning are recorded. + let logger = craft::platform::logs::install(craft::platform::logs::LogNames::new("pdfcraft")); if let Some(value) = pdfcraft_platform::crypto_env::dropped() { let name = pdfcraft_platform::crypto_env::IA32CAP; log::warn!("{name} was set to {value}; PdfCraft started again without it (aws-lc stops on a CPU feature the processor lacks)"); @@ -245,17 +233,18 @@ fn main() -> eframe::Result { } startup.files = rejoin_split_paths(startup.files, |p| std::path::Path::new(p).is_file()); let may_hand_off = startup.may_hand_off(); - let startup::Arguments { files, options, control_file, create_images, combine, two_paged, .. } = startup; - let integrated = cfg!(target_os = "macos"); - // GNOME on Wayland leaves the window frame to the app (src/decorations.rs). - let window_controls = if cfg!(any(target_os = "macos", target_os = "windows")) { None } else { decorations::app_drawn() }; + let startup::Arguments { files, options, control_port, control_token, control_token_file, create_images, combine, two_paged, .. } = startup; + // A bad control configuration stops the launch before any window opens. + let control = match control_options(control_port, control_token, control_token_file) { + Ok(control) => control, + Err(message) => usage_error(&message), + }; migrate_legacy_folders(); // The log file stays in the data folder; opened after the arguments (so `--version` leaves // no file behind) and after the PrintCraft migration (which a fresh folder would block). // Records logged until now are written to it first. - if let (Some(logger), Some(dir)) = - (logger, pdfcraft_ui_egui::portable::data_dir().map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir("PdfCraft"))) - { + let data_dir = if portable() { settings_dir() } else { eframe::storage_dir("PdfCraft") }; + if let (Some(logger), Some(dir)) = (logger, data_dir) { match logger.attach_dir(&dir.join("logs")) { Ok(path) => log::info!("PdfCraft {}, log file {}", pdfcraft_engine::build_info::version(), path.display()), // Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics. @@ -269,13 +258,23 @@ fn main() -> eframe::Result { // Absolute for this instance too: links relative to a document resolve against its folder, // never the working directory. let files = single_instance::absolute(&files); - let instance = match single_instance::claim(&files, may_hand_off, combine) { + // PLAN: assumed single_instance::claim(&[String], bool, bool, portable: bool) (pdf-shell-w6): a portable copy claims its own instance. + let instance = match single_instance::claim(&files, may_hand_off, combine, portable()) { single_instance::Claim::HandedOff => return Ok(()), single_instance::Claim::Primary(server) => Some(server), single_instance::Claim::Alone => None, }; + let settings = pdfcraft_ui_egui::settings::open(); + // Who draws the window frame: the platform and Preferences ▸ Use system title bar decide, + // unless `PDFCRAFT_TITLEBAR` overrides them. + let frame = craft::window::policy::decide_for( + craft::window::Prefix::new("PDFCRAFT"), + craft::window::policy::Backend::from_env(), + settings.get().title_bar_choice, + ); + let integrated = !matches!(frame.frame, craft::window::policy::Frame::Native); let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref()); - let launch = Launch { files, options, control_file, create_images, combine, integrated, window_controls, two_paged }; + let launch = Launch { files, options, control, create_images, combine, integrated, two_paged, settings }; // Finder, Open With and the Dock deliver files as Apple events, not arguments; catch the one // that launched us as well as later ones. Lives until the event loop returns. #[cfg(target_os = "macos")] @@ -285,7 +284,7 @@ fn main() -> eframe::Result { let first = if choice == RendererChoice::Gl { eframe::Renderer::Glow } else { eframe::Renderer::Wgpu }; let result = eframe::run_native( "PdfCraft", - native_options(launch.integrated, launch.window_controls.is_some(), first), + native_options(launch.integrated, first), app_creator( launch.clone(), Rc::clone(&started), @@ -303,7 +302,7 @@ fn main() -> eframe::Result { log::error!("the GPU renderer (wgpu) didn't start: {e}. Starting with OpenGL instead; set PDFCRAFT_RENDERER=gl to skip wgpu."); eframe::run_native( "PdfCraft", - native_options(launch.integrated, launch.window_controls.is_some(), eframe::Renderer::Glow), + native_options(launch.integrated, eframe::Renderer::Glow), app_creator( launch, started, @@ -336,6 +335,47 @@ fn renderer_choice(value: Option<&str>) -> RendererChoice { } } +/// The control server's port and token from `--control `, `--control-token`, +/// `--control-token-file` and their `PDFCRAFT_CONTROL_*` variables; `None` leaves the server off. +/// A port needs a token or a token file, so the token is never printed (AGENTS.md §3). +fn control_options(port: Option, token: Option, token_file: Option) -> Result, String> { + use craft::automation::args::{ControlOptions, EnvNames, FlagNames, OptionsError, Source, Sources, control_port}; + let names = EnvNames::for_app("PDFCRAFT"); + let flags = FlagNames::default(); + let port = match port { + Some(value) => Some(control_port(&value).map_err(|_| OptionsError::NotAPort { value, shown: format!("{} ", flags.port) }.to_string())?), + None => None, + }; + let given = ControlOptions { + sources: Sources { + port: port.map(|_| Source::Flag), + token: token.as_ref().map(|_| Source::Flag), + token_file: token_file.as_ref().map(|_| Source::Flag), + }, + port, + token, + token_file: token_file.map(std::path::PathBuf::from), + }; + let options = ControlOptions::resolve(given, &names).map_err(|e| e.to_string())?; + options.check(&flags, &names).map_err(|e| e.to_string())?; + let Some(port) = options.port else { return Ok(None) }; + if options.token.is_none() && options.token_file.is_none() { + return Err(format!( + "the argument '{} ' needs '{} ' or '{} ' (or {} or {})", + flags.port, flags.token, flags.token_file, names.token, names.token_file + )); + } + let token = options.server_token().map_err(|e| e.to_string())?; + let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("pdfcraft: {}\n", options.token_notice(&token))); + Ok(Some((port, token))) +} + +/// A bad command line: say why as clap would, and exit with the usage status. +fn usage_error(message: &str) -> ! { + let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("error: {message}\n\nFor more information, try '--help'.\n")); + std::process::exit(craft::automation::args::USAGE_EXIT_CODE) +} + /// Whether a failed run should be retried with OpenGL: only when wgpu was tried first by choice of /// nobody, and it failed before the app was created (so while starting the renderer, not later). fn retry_with_gl(choice: RendererChoice, app_started: bool) -> bool { @@ -343,7 +383,7 @@ fn retry_with_gl(choice: RendererChoice, app_started: bool) -> bool { } /// The window and renderer settings for one run. -fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer) -> eframe::NativeOptions { +fn native_options(integrated: bool, renderer: eframe::Renderer) -> eframe::NativeOptions { let mut viewport = egui::ViewportBuilder::default() .with_title("PdfCraft") .with_inner_size([1440.0, 920.0]) @@ -365,11 +405,13 @@ fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer) Err(e) => log::warn!("app icon: {e}"), } if integrated { - viewport = viewport.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false); - } - if app_frame { - // The tab strip is the title bar (pdfcraft_ui_egui::window_controls). - viewport = viewport.with_decorations(false); + // macOS keeps its traffic lights over the app's bar; elsewhere the app's bar is the whole + // title bar, with its own caption buttons. + viewport = if cfg!(target_os = "macos") { + viewport.with_fullsize_content_view(true).with_titlebar_shown(false).with_title_shown(false) + } else { + viewport.with_decorations(false) + }; } let persistence_path = settings_dir().map(|d| d.join("app.ron")); // Set explicitly, so the renderer never depends on which one eframe defaults to. @@ -388,26 +430,16 @@ fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer) struct Launch { files: Vec, options: Vec<(String, String)>, - control_file: Option, + /// The control server's port and token, when `--control` asked for one. + control: Option<(u16, String)>, create_images: bool, /// `--combine`: the files go to the Combine files tab. combine: bool, + /// The app's bar is the title bar. integrated: bool, - /// The window buttons the app draws, when the desktop leaves the frame to it. - window_controls: Option, two_paged: bool, -} - -/// Whether the window is a native Wayland one (not X11 or XWayland). -#[cfg(all(unix, not(target_os = "macos")))] -fn native_wayland(cc: &eframe::CreationContext<'_>) -> bool { - use raw_window_handle::{HasDisplayHandle, RawDisplayHandle}; - cc.display_handle().is_ok_and(|handle| matches!(handle.as_raw(), RawDisplayHandle::Wayland(_))) -} - -#[cfg(not(all(unix, not(target_os = "macos"))))] -fn native_wayland(_: &eframe::CreationContext<'_>) -> bool { - false + /// The settings store the preferences come from. + settings: pdfcraft_ui_egui::settings::Store, } /// Decode `png` as a [`winit::window::Icon`] for the Windows taskbar and Alt+Tab (`ICON_BIG`). @@ -458,59 +490,51 @@ fn app_creator<'a>( instance: Option<&'a single_instance::Server>, #[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents, ) -> eframe::AppCreator<'a> { - let Launch { files, options, control_file, create_images, combine, integrated, window_controls, two_paged } = launch; + let Launch { files, options, control, create_images, combine, two_paged, settings, .. } = launch; Box::new(move |cc| { started.set(true); - let mut app = PdfCraftApp::new(); + let ctx = cc.egui_ctx.clone(); + let wake = craft::host::Wake::new(move || ctx.request_repaint()); + // Files a second launch hands over arrive through the single-instance server. + // PLAN: assumed single_instance::Server::connect(&self, &egui::Context) -> FileIntake and apple_events::AppleEvents::connect(&self, IntakeSender, &egui::Context) (pdf-shell-w6). + let intake = match instance { + Some(server) => server.connect(&cc.egui_ctx), + None => craft::platform::open::FileIntake::new(wake).0, + }; + // Finder, Open With and the Dock deliver files as Apple events, not arguments. + #[cfg(target_os = "macos")] + apple_events.connect(intake.sender(), &cc.egui_ctx); + let mut app = PdfCraftApp::with_intake(&cc.egui_ctx, intake); // First start (or settings from before Units existed): the region's unit. app.units = pdfcraft_ui_egui::units::Unit::system(); - #[cfg(target_os = "linux")] - app.enable_desktop_theme(); // The system's reopen-windows choice (macOS) starts the preference; a saved choice replaces it. app.reopen_last_session = reopen::system_default(); - if let Some(json) = cc.storage.and_then(|s| s.get_string("pdfcraft").or_else(|| s.get_string(LEGACY_STORAGE_KEY))) { - app.restore(&json); - } - app.window_state = pdfcraft_ui_egui::window_state::WindowState::started_with(cc.storage); - app.integrated_titlebar = integrated; - app.window_controls = window_controls; - app.system_text_scale = text_scale::system(); - // Windows' Animation effects setting, which Preferences ▸ Animation effects follows unless - // it is set to On or Off. + app.apply_settings(&settings.get()); + app.attach_settings(settings); #[cfg(target_os = "windows")] - { - if let Some(window) = cc.winit_window() { - set_taskbar_icon(window); - } - app.motion.source = Some(motion::source()); + if let Some(window) = cc.winit_window() { + set_taskbar_icon(window); } app.set_startup_update_check(true); app.printer_source = Some(pdfcraft_ui_egui::system_printers()); app.two_sided_source = Some(pdfcraft_ui_egui::system_two_sided()); app.os_key_store_ids = cfg!(any(target_os = "macos", target_os = "windows")); + // The native menu bar. Its Quit (⌘Q) closes the window rather than ending the process as + // winit's does (#1136), so the close path asks about unsaved changes, as for the close + // button. #[cfg(target_os = "macos")] - { - app.os_events = Some(apple_events.connect(&cc.egui_ctx)); - // The native menu bar. Its Quit (⌘Q) closes the window rather than ending the process as - // winit's does (#1136), so `guard_quit` asks about unsaved changes, as for the close - // button. - if !app.install_native_menu(&cc.egui_ctx) { - log::warn!("couldn't install the macOS menu bar; the menus stay in the window"); - } + if !app.install_native_menu(&cc.egui_ctx) { + log::warn!("couldn't install the macOS menu bar; the menus stay in the window"); } - if let Some(server) = instance { - app.os_events = Some(server.connect(&cc.egui_ctx, native_wayland(cc))); + // `--control` was asked for: carrying on without the server would leave a script driving + // nothing, so a port that can't be listened on stops the launch before any document opens. + if let Some((port, token)) = &control { + let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx); + let (requests, listening) = craft::automation::server::listen(*port, token.clone(), host).map_err(|e| format!("--control {port}: {e}"))?; + app.attach_control(requests, Some(listening)); } - if let Some(file) = &control_file { - let client = app.attach_control(&cc.egui_ctx); - open_control_channel(file, pdfcraft_ui_egui::control::serve(client))?; - } - // Autosave unsaved changes; offer to recover documents a crashed session left behind. - if let Some(dir) = pdfcraft_ui_egui::RecoveryStore::default_dir() { - app.enable_recovery(pdfcraft_ui_egui::RecoveryStore::new(dir)); - } - // The OCR Verify screen stores its per-language dictionary beside recovery data. - app.ocr_verify.dictionary_dir = pdfcraft_ui_egui::default_dictionary_dir(); + // The OCR Verify screen stores its per-language dictionary in the data folder. + app.ocr_verify.dictionary_dir = pdfcraft_ui_egui::settings::dictionary_dir(); if let Some(state) = &cc.wgpu_render_state { let adapter = state.adapter.get_info(); let max_texture_dimension_2d = state.device.limits().max_texture_dimension_2d; @@ -525,11 +549,8 @@ fn app_creator<'a>( log::info!("renderer: OpenGL (glow)"); } // A portable marker whose data folder can't be written (#157): say where settings went. - if let Some(w) = &pdfcraft_ui_egui::portable::current().unwritable { - app.notify_fmt( - "Portable mode is off: {folder} can't be written ({error}). Settings are kept in your user folder instead.", - &[("folder", &w.folder.display().to_string()), ("error", &w.error)], - ); + if let Some(warning) = &pdfcraft_ui_egui::settings::resolution().warning { + app.notify(warning.clone()); } let defer_layout = two_paged && !files.is_empty() && !create_images; if create_images { @@ -565,130 +586,6 @@ fn notify_software_renderer(app: &mut PdfCraftApp, device_type: eframe::wgpu::De } } -/// Publish a started control channel in `file`. -/// -/// A failure stops the app. `--control` was asked for, so carrying on without it would leave a -/// script driving nothing, and the file that couldn't be replaced may be another user's, planted -/// at a shared path such as `/tmp/pc.json` to receive the commands. This runs before any document -/// opens, so nothing is lost. -fn open_control_channel(file: &str, endpoint: std::io::Result) -> Result<(), String> { - match endpoint.and_then(|ep| write_control_file(file, ep.port, &ep.token).map(|()| ep.port)) { - // Never the token (AGENTS.md §3): it stays in the owner-only file. - Ok(port) => { - log::info!("UI control channel on 127.0.0.1:{port} (connection details in {file})"); - Ok(()) - } - Err(e) => { - // cmd.exe doesn't expand `~` (#3922). - let example = if cfg!(windows) { r"%USERPROFILE%\.pdfcraft-control.json" } else { "~/.pdfcraft-control.json" }; - let message = format!("--control {file}: {e}. Use a control file in a folder only you can write, such as {example}"); - log::error!("{message}"); - Err(message) - } - } -} - -/// Write the control endpoint so that only the current user can read the token. -/// -/// The JSON goes to a new file, created fresh and owner-only, which then replaces `path`. On Unix -/// the file sits next to `path` with mode 0600. On Windows it sits in a new folder next to `path` -/// whose access list, of this user and SYSTEM only, it inherits when it is created, so no other -/// account can open it at any time (#3922; review on #3956). Opening `path` itself would follow a -/// link planted there and truncate whatever it points at; a rename replaces the link and leaves -/// its target alone. A reader polling for the file also never sees it half-written. -fn write_control_file(path: &str, port: u16, token: &str) -> std::io::Result<()> { - use std::io::ErrorKind; - let json = serde_json::json!({ "port": port, "token": token, "pid": std::process::id() }).to_string(); - let path = std::path::Path::new(path); - let name = path.file_name().ok_or_else(|| std::io::Error::new(ErrorKind::InvalidInput, "not a file name"))?; - // Windows: the user's SID, read once for the private folder and for the file in it, since each - // lookup starts `whoami` (review on #3956). - #[cfg(windows)] - let me = pdfcraft_platform::owner_only::current_user_sid()?; - #[cfg(windows)] - let restrict = |file: &std::path::Path| pdfcraft_platform::owner_only::restrict_to_owner(file, &me); - #[cfg(not(windows))] - let restrict = |_: &std::path::Path| Ok::<(), std::io::Error>(()); - // Unpredictable suffixes, so the name can't be planted in advance. `RandomState` is keyed from - // the operating system's random source. - let random = std::hash::RandomState::new(); - for i in 0..16u32 { - let mut staged = std::ffi::OsString::from("."); - staged.push(name); - staged.push(format!(".{:016x}.tmp", std::hash::BuildHasher::hash_one(&random, i))); - let staged = path.with_file_name(staged); - // Windows: a file created next to `path` would inherit that folder's access list, which may - // let other users read it, and restricting it afterwards leaves a window in which one of - // them opens a handle; Windows checks access only when a handle is opened, so a later - // change of the list doesn't revoke it. The file is created in a private folder instead, - // and that folder is removed once the file has left it. - #[cfg(windows)] - let (staging, staged) = { - match pdfcraft_platform::owner_only::create_private_dir(&staged, &me) { - Ok(()) => {} - Err(e) if e.kind() == ErrorKind::AlreadyExists => continue, - // As for a file below: something at the name we may not open still takes it. - Err(e) if e.kind() == ErrorKind::PermissionDenied && staged.symlink_metadata().is_ok() => continue, - Err(e) => return Err(e), - } - let file = staged.join(name); - (staged, file) - }; - let done = stage_control_file(&staged, path, &json, &restrict); - #[cfg(windows)] - let _ = std::fs::remove_dir(&staging); - match done { - Some(done) => return done, - None => continue, - } - } - Err(std::io::Error::new(ErrorKind::AlreadyExists, "no free name for the control file's temporary copy")) -} - -/// Create `staged` fresh and owner-only, `restrict` it, write `json` to it and rename it to `path`. -/// `None` when something already has the name, so the caller tries another. On any other failure -/// the new file is removed and nothing is left at `path`'s side. -fn stage_control_file( - staged: &std::path::Path, - path: &std::path::Path, - json: &str, - restrict: &dyn Fn(&std::path::Path) -> std::io::Result<()>, -) -> Option> { - use std::io::{ErrorKind, Write}; - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - opts.mode(0o600); - } - let file = match opts.open(staged) { - Ok(f) => f, - Err(e) if e.kind() == ErrorKind::AlreadyExists => return None, - // Windows refuses `create_new` on a folder with "access denied"; the name is taken all - // the same. A folder we can't write to, with nothing at the name, still fails here. - Err(e) if e.kind() == ErrorKind::PermissionDenied && staged.symlink_metadata().is_ok() => return None, - Err(e) => return Some(Err(e)), - }; - // Windows: the file inherited the private folder's list. It also gets a list of its own, so it - // stays private wherever the rename puts it, and that is checked before the token is written; - // nothing is written if that fails (#3922). Unix has mode 0600 above, and `restrict` does nothing. - if let Err(e) = restrict(staged) { - drop(file); - let _ = std::fs::remove_file(staged); - return Some(Err(e)); - } - // The block closes the file before it is renamed. - let written = { - let mut file = file; - file.write_all(json.as_bytes()) - }; - let done = written.and_then(|()| std::fs::rename(staged, path)); - if done.is_err() { - let _ = std::fs::remove_file(staged); - } - Some(done) -} /// How wgpu finds a GPU. Each choice yields to its wgpu environment variable. /// diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9016c57dc7..dacca4c344 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The framework facade with the crates the UI uses (owed by pdf-hub-w1, which owns this manifest). -craft = { workspace = true, features = ["ui", "draw", "pages", "print", "review", "dialogs", "docpath", "font-catalog", "window", "settings", "platform", "atomic", "automation", "keymap", "menu", "quit", "web-host", "text", "text-font-picker", "font-manager", "platform-clipboard", "update", "theme-store", "imaging"] } +craft = { workspace = true, features = ["ui", "draw", "pages", "print", "review", "dialogs", "docpath", "font-catalog", "text-font-picker", "text-find", "imaging", "window", "settings", "platform", "platform-clipboard", "atomic", "automation", "keymap", "menu", "quit", "web-host"] } edit-session = { workspace = true } craft-ui = { workspace = true } # The menus: native on macOS, an egui bar elsewhere, from one definition (menus.rs). @@ -57,17 +57,12 @@ unicode-bidi = "0.3" skrifa = "0.44" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-update = { workspace = true } +# Help ▸ Check for updates: the facade's update crate builds only natively. +craft = { workspace = true, features = ["update"] } # Control-channel tokens. getrandom = "0.4" # Create ▸ Clipboard (images; already in the tree through egui-winit). arboard = { version = "3.6", default-features = false, features = ["image-data"] } -# Waits for native file pickers off the UI thread (already in the tree through wgpu). -pollster = "1.0" - -[target.'cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))'.dependencies] -# Discover configured font directories without linking libfontconfig or running a subprocess. -fontconfig-parser = "0.5.8" [target.'cfg(target_os = "macos")'.dependencies] # Safe AppKit calls for drag coordinates and repairing an existing per-file PDFCraft binding. @@ -95,9 +90,8 @@ js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "HtmlIFrameElement", "HtmlImageElement", "HtmlCollection", "Node", "EventTarget", "Navigator", "RequestCache", "RequestInit", "Response", "Worker", "WorkerOptions", "WorkerType", "MessageEvent"] } [dev-dependencies] -# The framework's test drivers (`craft::ui::testing`) for the kittest suites. +# The fixture and suite runner the component trials drive the app's components with. craft = { workspace = true, features = ["ui-testing"] } -craft-update = { workspace = true } pdfcraft-xfa = { workspace = true } # A content stream that inflates past the renderer's limits, for the cut-content notice test. flate2 = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6e4a52ccea..01c62e5997 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,12 +1,20 @@ -use super::hooks::OsEvent; -use super::state::{ - Dialog, DocumentCopyJob, GridFile, LeftPanel, LinkOrigin, Mode, NumberDraft, PasswordPrompt, PendingLink, PropsTab, QuickTool, RecentFile, - RightPanel, UnlockPrompt, -}; +use super::state::{DocumentCopyJob, LeftPanel, LinkOrigin, Mode, PasswordPrompt, PendingLink, QuickTool, RecentFile, RightPanel, UnlockPrompt}; #[cfg(not(target_arch = "wasm32"))] use super::state::{OpenOutcome, OpenRequest, PendingRemoteLink}; use super::*; +use std::hash::Hash; +use std::path::PathBuf; +use std::sync::Arc; + +use craft::host::queue::{JobQueue, QueueOptions}; +use craft::host::{Host, Wake}; +use craft::platform::autosave::{Autosave, RecoveryStore}; +use craft::platform::clipboard::Clipboard; +use craft::platform::open::FileIntake; +use craft::ui::runtime::env::{RootEnv, Scale}; +use craft::ui::shell::embed; + mod clipboard; mod commands; mod control; @@ -21,13 +29,77 @@ mod window; pub(crate) use clipboard::{ObjectClipMark, copy_refused, print_refused}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use files::same_file; -use frame::migrate_panel_state; pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf}; -impl Default for PdfCraftApp { - fn default() -> Self { - Self::new() +/// Where the update check asks for the newest release, in place of GitHub (tests). +#[cfg(not(target_arch = "wasm32"))] +pub type UpdateSource = craft::update::updater::CheckSource; + +/// The services [`PdfCraftApp::with_host`] builds the app over: the real ones from +/// [`AppServices::system`], or a test's (`Wake::none()`, an inline watch). +pub struct AppServices { + wake: Wake, + clipboard: Clipboard, + recovery_dir: Option, + #[cfg(not(target_arch = "wasm32"))] + update_source: Option, + intake: FileIntake, + #[cfg(not(target_arch = "wasm32"))] + watch: craft::platform::watch::FileWatch, +} + +impl AppServices { + /// `wake` asks for a frame; `recovery_dir` is where autosaves go (`None`: autosave off); + /// `update_source` answers the update check in place of GitHub (`None`: GitHub); `intake` + /// holds the files to open; `watch` reports changes to open documents' files. + pub fn new( + wake: Wake, + clipboard: Clipboard, + recovery_dir: Option, + #[cfg(not(target_arch = "wasm32"))] update_source: Option, + intake: FileIntake, + #[cfg(not(target_arch = "wasm32"))] watch: craft::platform::watch::FileWatch, + ) -> Self { + Self { + wake, + clipboard, + recovery_dir, + #[cfg(not(target_arch = "wasm32"))] + update_source, + intake, + #[cfg(not(target_arch = "wasm32"))] + watch, + } } + + /// The desktop's or the browser's own services, waking `ctx`, reading the files to open from + /// `intake`. + pub fn system(ctx: &egui::Context, intake: FileIntake) -> Self { + let wake = wake_of(ctx); + // PLAN: assumed settings::recovery_dir() -> Option, the data folder's recovery folder (pdf-shell-w9). + #[cfg(not(target_arch = "wasm32"))] + { + let clipboard = Clipboard::new(craft::platform::clipboard::SystemClipboard::new()); + let watch = craft::platform::watch::FileWatch::new(wake.clone()); + Self::new(wake, clipboard, settings::recovery_dir(), None, intake, watch) + } + // PLAN: assumed clipboard::web_clipboard(&egui::Context) -> Clipboard, the browser's event clipboard (pdf-shell-w17). + #[cfg(target_arch = "wasm32")] + { + Self::new(wake, clipboard::web_clipboard(ctx), None, intake) + } + } +} + +/// A wake that asks `ctx` for a frame. +fn wake_of(ctx: &egui::Context) -> Wake { + let ctx = ctx.clone(); + Wake::new(move || ctx.request_repaint()) +} + +/// A queue of the app's over the host's jobs, named `name` for its lanes. +fn queue(host: &Host, wake: &Wake, name: &'static str) -> JobQueue { + JobQueue::new(host.jobs_shared().clone(), wake.clone(), QueueOptions { name, ..QueueOptions::default() }) } impl PdfCraftApp { @@ -64,10 +136,86 @@ impl PdfCraftApp { } } - /// Construct default session, panels, theme and control state with no active property-edit session. - pub fn new() -> Self { + /// The app over the desktop's own services, waking `ctx`. + #[cfg(not(target_arch = "wasm32"))] + pub fn new(ctx: &egui::Context) -> Self { + let (intake, _) = FileIntake::new(wake_of(ctx)); + Self::with_intake(ctx, intake) + } + + /// [`Self::new`] reading the files to open from `intake` (another launch's, the Apple events'). + #[cfg(not(target_arch = "wasm32"))] + pub fn with_intake(ctx: &egui::Context, intake: FileIntake) -> Self { + let services = AppServices::system(ctx, intake); + let (files, panels) = craft::dialogs::service::FileService::new(services.wake.clone()); + let host = Host::builder(APP_INFO).files(Arc::new(files)).build(); + let mut app = Self::with_host(Arc::new(host), services); + app.file_panels = Some(panels); + app + } + + /// The app over `host` and `services`, with no document open: every queue runs on the host's + /// jobs, so a test passes a host over `ManualJobs` and `ScriptedFiles`. + pub fn with_host(host: Arc, services: AppServices) -> Self { + let AppServices { + wake, + clipboard, + recovery_dir, + #[cfg(not(target_arch = "wasm32"))] + update_source, + intake, + #[cfg(not(target_arch = "wasm32"))] + watch, + } = services; + let store = recovery_dir.and_then(|dir| match RecoveryStore::open(dir) { + Ok(store) => Some(Arc::new(store)), + Err(e) => { + log::warn!("autosave is off: the recovery folder can't be used: {e}"); + None + } + }); + let recovered = store.as_ref().map(|s| s.leftovers()).unwrap_or_default(); + let autosave = Autosave::new(store.is_some().then(|| std::time::Duration::from_secs(recovery::AUTOSAVE_SECS))); + #[cfg(not(target_arch = "wasm32"))] + let updater = { + let updater = craft::update::updater::Updater::new(&UPDATE_APP, pdfcraft_engine::build_info::version().to_string()); + match update_source { + Some(source) => updater.with_source(source), + None => updater, + } + }; Self { + #[cfg(not(target_arch = "wasm32"))] + // PLAN: assumed open_worker::queue(&Host, Wake) -> JobQueue (pdf-shell-w13). + opens: open_worker::queue(&host, wake.clone()), + #[cfg(not(target_arch = "wasm32"))] + named_destinations: queue(&host, &wake, "pdfcraft-destinations"), + pinned_jobs: queue(&host, &wake, "pdfcraft-pinned-folders"), + recent_check: persist::recent_check::RecentCheck::new(queue(&host, &wake, "pdfcraft-recent-check")), + text_copies: queue(&host, &wake, "pdfcraft-copy-text"), + ocr_runs: queue(&host, &wake, "pdfcraft-ocr"), + ocr_batches: queue(&host, &wake, "pdfcraft-ocr-files"), + verify_jobs: queue(&host, &wake, "pdfcraft-ocr-verify"), + action_jobs: queue(&host, &wake, "pdfcraft-actions"), + space_audit_jobs: queue(&host, &wake, "pdfcraft-space-audit"), + optimize_jobs: queue(&host, &wake, "pdfcraft-optimize"), + scan_cleans: queue(&host, &wake, "pdfcraft-scan-clean"), + export_jobs: queue(&host, &wake, "pdfcraft-export"), + font_scan: queue(&host, &wake, "pdfcraft-font-scan"), + print_tasks: print_ui::PrintTasks::new(host.jobs_shared().clone(), wake.clone()), + host, + wake, + intake, + #[cfg(not(target_arch = "wasm32"))] + file_panels: None, + settings: None, + dialogs: craft::ui::dialog::DialogHost::new(), + prompts: Default::default(), + preferences: None, + shortcuts: None, panes: Default::default(), + dock: side_panels::default_workspace(), + rail_side: Default::default(), session: Session::new(), status_captions_lang: None, views: Vec::new(), @@ -76,51 +224,39 @@ impl PdfCraftApp { mode: Mode::AllTools, default_mode: Mode::AllTools, view_defaults: Default::default(), + highlight_fields: true, units: Default::default(), blank_paper: crate::paper::Paper::system(), - date_format_draft: None, mode_override: None, left: LeftPanel::AllTools, - side_panels: Default::default(), left_open: true, - right: None, last_right: RightPanel::Comments, right_before_read: None, comments_panel_closed: false, right_panel_closed: false, portfolio_initial: None, portfolio_seen: None, - #[cfg(target_arch = "wasm32")] - web_reads: Default::default(), portfolio_panel: None, quick_tool: QuickTool::Select, - space_hand: None, full_screen_tool: None, comment_prefs: Default::default(), + recent_colours: Default::default(), hotbar: Default::default(), - theme: ThemeKind::Light, // A fresh install follows the desktop's appearance (#1248); saved settings override. - theme_preference: ThemePreference::System, + theme_preference: craft::theme::ModeChoice::System, reading_colors: Default::default(), show_page_edge_shadows: true, - #[cfg(target_os = "linux")] - desktop_theme: None, - #[cfg(target_os = "linux")] - desktop_theme_enabled: false, scroll_speed: scroll_speed::ScrollSpeed::default(), invert_middle_drag: false, - animation_effects: motion::AnimationEffects::default(), - motion: motion::Motion::default(), + animation_effects: craft::theme::MotionChoice::System, language: i18n::AUTO.to_string(), ui_scale: None, - system_text_scale: 1.0, - ui_scale_applied: None, + title_bar_choice: Default::default(), flatten_fill_sign_on_save: false, ask_to_lock_signatures: true, placed_signatures: Default::default(), pending_lock: None, lock_answered: None, - lock_remember: false, fill_text_size: fill_sign::TEXT_SIZE, fill_tool: fill_sign::FillTool::Signature, fill_text_color: [0.0; 3], @@ -128,106 +264,70 @@ impl PdfCraftApp { fill_text_border_color: None, fill_text_border_shape: pdfcraft_engine::BorderShape::Rectangle, fill_text_default: fill_sign::TextBorder::NONE, - dialog: None, - updates: updates::Updates::default(), + #[cfg(not(target_arch = "wasm32"))] + updater, + startup_check: false, printer_source: None, options_source: None, default_paper_source: None, printer_papers_source: None, spooler: None, two_sided_source: None, - print_tasks: print_ui::PrintTasks::default(), palette_open: false, - palette_query: String::new(), all_tools_expanded: false, all_tools_full: false, all_tools_query: String::new(), all_tools_tab: (None, false), recent: Vec::new(), recent_limit: crate::RECENT_FILES_DEFAULT, + recent_view: craft::ui::shell::RecentView::List, + recent_sort: craft::ui::shell::RecentSort::Opened, reopen_last_session: false, restore_last_view: true, last_views: Vec::new(), last_session: Default::default(), - quit_session: None, + session_keeper: Default::default(), reload_changed_files: true, update_check_at_start: true, show_secured_notice: true, text_links: true, always_default_view: false, #[cfg(not(target_arch = "wasm32"))] - watch: Default::default(), + watch, #[cfg(not(target_arch = "wasm32"))] - open_worker: None, + reload_request: None, #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec::new(), #[cfg(not(target_arch = "wasm32"))] - deferred_opens: Default::default(), - #[cfg(not(target_arch = "wasm32"))] password_retry: None, #[cfg(not(target_arch = "wasm32"))] - pending_destinations: Vec::new(), - #[cfg(not(target_arch = "wasm32"))] next_open_token: 0, #[cfg(not(target_arch = "wasm32"))] launch_layout: None, #[cfg(not(target_arch = "wasm32"))] launch_display_target: None, - #[cfg(all(test, not(target_arch = "wasm32")))] - open_prepare_gate: None, + picks: Default::default(), + save_flow: Default::default(), + pending_save: None, pinned: Default::default(), - recent_check: Default::default(), - #[cfg(not(target_arch = "wasm32"))] - reveal_errors: Default::default(), pinned_tools: Vec::new(), - pin_tool_search: String::new(), - toast: None, - toast_script: None, script_messages: std::collections::VecDeque::new(), script_messages_dropped: 0, - toast_dropped: 0, - integrated_titlebar: false, - window_controls: None, - system_title_bar: false, - app_frame_shown: None, + script_shown: None, + posted_notices: Vec::new(), + progress_cards: Default::default(), password_prompt: None, - document_copy: None, unlock_prompt: None, - full_screen: false, - inbox: Default::default(), - startup_inbox: Default::default(), - startup_superseded: false, - failed_inbox: Default::default(), - unsaved_flag: Default::default(), - os_events: None, - host_save: None, + screen_mode: Default::default(), host_dirty: None, - close_request: None, - save_prompt_button: Default::default(), - save_prompt_seen: false, - save_prompt_attention: false, - #[cfg(not(target_arch = "wasm32"))] - pending_overwrite: None, - save_override: None, - props_draft: None, - attachment_description_draft: None, - view_draft: None, - custom_draft: None, + close_guard: None, props_session: None, - requests: Default::default(), - #[cfg(not(target_arch = "wasm32"))] - pickers: Default::default(), - #[cfg(not(target_arch = "wasm32"))] - pick_override: None, - export_dir_override: None, - split_draft: SplitDraft::default(), - extract_draft: ExtractDraft::default(), - rotate_draft: RotateDraft::default(), summary_sort: Default::default(), + summarize_dialog: None, sign_draft: None, presign: None, digital_ids: Vec::new(), - sig_expanded: Vec::new(), + sig_open: Default::default(), a11y_options: a11y_ui::A11yOptions::default(), ocr_draft: ocr_ui::OcrDraft::default(), ocr_run: None, @@ -237,16 +337,13 @@ impl PdfCraftApp { #[cfg(target_arch = "wasm32")] ocr_web_waiting: None, ocr_verify: ocr_verify::OcrVerify::default(), - run_inline: false, panicking_frames: 0, frame_panicked: false, logic_without_ui: false, #[cfg(test)] panic_next: None, custom_actions: Vec::new(), - wizard: Default::default(), action_run: None, - action_files_override: None, pdfa: Default::default(), compare_old: None, compare_pages: String::new(), @@ -254,14 +351,13 @@ impl PdfCraftApp { js_console: Default::default(), #[cfg(not(target_arch = "wasm32"))] script_pending: None, - doc_js: Default::default(), + js_dialog: None, a11y: a11y_ui::A11yState::default(), tags_state: Default::default(), a11y_skipped: Default::default(), - alt_draft: Default::default(), os_key_store_ids: false, cert_viewer: None, - space_audit: Vec::new(), + space_audit: Default::default(), space_audit_of: None, combine_draft: Vec::new(), combine_conflicts: Default::default(), @@ -270,99 +366,68 @@ impl PdfCraftApp { combine_view: Default::default(), combine_zoom: 1.0, organize_zoom: 1.0, - combine_thumbs: Default::default(), image_import: None, custom_stamps: Vec::new(), - stamp_draft: Default::default(), - optimize_draft: OptimizeDraft::default(), + stamp_dialog: None, optimize_run: None, scan_clean_draft: scan_clean_ui::ScanCleanDraft::default(), scan_clean_run: None, - progress_notice: None, page_clipboard: None, comment_clipboard: None, object_clipboard: None, object_clip_mark: Default::default(), - grid_drop: None, last_snapshot: None, last_snapshot_of: None, last_copied_image: None, last_copied_file: None, - system_clipboard: true, - html_clipboard_override: None, - #[cfg(not(target_arch = "wasm32"))] - os_clipboard: None, - clipboard_override: None, - attach_override: None, - duplicate_draft: None, + clipboard, page_props_draft: None, - field_table_draft: None, form_preview: false, + recovery: store, + recovered, + autosave, + recovered_paths: Default::default(), + native_menu: None, + fonts_ready: false, window_title: String::new(), page_title: String::new(), - recovery: None, - recoverable: Vec::new(), - recovery_keys: Default::default(), - recovered_paths: Default::default(), - last_autosave: None, - allow_quit: false, - deferred_commands: Vec::new(), - native_menu: None, - menu_input: Vec::new(), - menu_pastes: 0, - page_keys: Default::default(), - dialog_seen: None, - dialog_epoch: 0, - ctx: None, - #[cfg(not(target_arch = "wasm32"))] - window_state: Default::default(), - styled: false, - fonts_ready: false, - fonts_cjk: theme::CjkPreference::Default, control: None, + control_server: None, + control_epoch: 0, bookmark_rename: None, bookmark_clipboard: None, - last_opened_url: None, - community_card_closed: false, - pending_link: None, - pending_full_screen: None, - pending_window: None, - pending_remote_link: None, - protect_draft: Default::default(), + word_count_options: Default::default(), + printer_marks_draft: Default::default(), + convert_colours_draft: Default::default(), + hairlines_draft: Default::default(), text_style_draft: Default::default(), boxes_draft: Default::default(), marks_draft: Default::default(), - unmarked_page: Default::default(), + marks_preview: None, + attachment_description: None, export_draft: Default::default(), export_status: None, signature: None, initials: None, - signature_draft: Default::default(), - signature_preview: None, - signature_photo: None, - saved_signature_previews: [None, None], sign_graphic: sign_ui::SignGraphic::Name, - sign_graphic_preview: None, - #[cfg(target_arch = "wasm32")] - signature_images: Default::default(), comment_props: None, - field_props: None, - bulk_field_props: None, redact_prefs: RedactPrefs::default(), redact_defaults: RedactPrefs::default(), - redact_before: None, - redact_pages_draft: RedactPagesDraft::default(), + redact_props: None, redact_search: RedactSearchDraft::default(), - hidden_draft: HiddenDraft::default(), + redact_search_open: false, + hidden_draft: None, print_draft: PrintDraft::default(), - link_draft: None, text_style: content_ui::default_style(), - replace_draft: None, - number_draft: NumberDraft { from: 1, to: 1, style: pdfcraft_engine::LabelStyle::Decimal, prefix: String::new(), start: 1 }, - word_count_draft: word_count_ui::Draft::default(), - printer_marks_draft: Default::default(), - convert_colours_draft: Default::default(), - hairlines_draft: Default::default(), + edit_more: false, + replace_source: None, + #[cfg(not(target_arch = "wasm32"))] + document_fonts: None, + last_opened_url: None, + community_card_closed: false, + pending_link: None, + pending_window: None, + pending_remote_link: None, } } @@ -374,99 +439,60 @@ impl PdfCraftApp { && !self.form_preview } - /// A number that changes whenever the open dialog changes (opened, closed or replaced by - /// another), checked every frame. A picker started from a dialog's Browse… button answers - /// only into the same showing of that dialog. - pub(crate) fn dialog_epoch(&mut self) -> u64 { - if self.dialog != self.dialog_seen { - self.dialog_seen = self.dialog; - self.dialog_epoch = self.dialog_epoch.wrapping_add(1); - } - self.dialog_epoch - } - pub fn active_ids(&self) -> Option<(usize, DocId)> { self.active.and_then(|i| self.views.get(i).map(|v| (i, v.id))) } - /// Whether something over the pages has the keyboard: what covers them - /// ([`Self::covers_pages`]), the hotbar's tools window, a popup, a menu of the menu bar, or the - /// bar holding the keyboard (Alt, F10). - pub(crate) fn over_pages(&self, ctx: &egui::Context) -> bool { - self.covers_pages() - || self.hotbar.picker_over_pages(ctx) - || egui::Popup::is_any_open(ctx) - || craft_menu::bar::is_open(ctx) - || craft_menu::bar::is_focused(ctx) + /// The right panel showing, as the dock has it. + pub(crate) fn right(&self) -> Option { + side_panels::right_of(&self.dock) } - /// Edit ▸ Copy, Cut, Select all and Delete stand for keys, and Edit ▸ Paste for the paste the - /// platform answers with. They go where the user's would: to a text field that has the - /// keyboard, else to the pages. They join the input once the menu bar has let go of the keys, - /// which an in-window menu's click does a pass later (craft-menu stores the menu as open on - /// the pass its click closes it). A native menu's click leaves egui's popups and the Hotbar - /// tools window open, which hold the pages' keys; a click anywhere else closes them, and so - /// does this. Edit ▸ Paste asks the platform for the clipboard only then, so its answer, on a - /// later pass, is an ordinary paste. With a text field focused, a native click on Copy, Cut, - /// Paste or Select all doesn't come here: craft-menu taps the shortcut for the field instead. - fn release_menu_input(&mut self, ctx: &egui::Context) { - if self.menu_input.is_empty() && self.menu_pastes == 0 { - return; - } - if craft_menu::bar::is_open(ctx) || craft_menu::bar::is_focused(ctx) { - ctx.request_repaint(); - return; - } - if !ctx.text_edit_focused() { - egui::Popup::close_all(ctx); - self.hotbar.close_picker(); - } - let events = std::mem::take(&mut self.menu_input); - ctx.input_mut(|i| i.events.extend(events)); - for _ in 0..std::mem::take(&mut self.menu_pastes) { - ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste); - } + /// The app's root values for this frame: appearance mode, motion, interface scale and the + /// interface language's direction. The one place the app's `RootEnv` is built. + // PLAN: `ui_scale: None` gives scale 1; following the desktop's text scale (`env::system_text_scale`) needs a ctx, and hub-w3 calls this as `root_env()`. + pub(crate) fn root_env(&self) -> RootEnv { + let lang = i18n::Lang::from_pref(&self.language); + let direction = if lang.rtl() { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr }; + let mut root = RootEnv::new().mode(self.theme_preference).direction(direction).scale(Scale::new(self.ui_scale.unwrap_or(1.0))); + root.motion = self.animation_effects; + root } /// Read mode and full screen hide the hotbar (the quick tools), and its tools window with it. pub(crate) fn hotbar_hidden(&self) -> bool { - self.mode == crate::Mode::Read || self.full_screen + self.mode == crate::Mode::Read || self.screen_mode.body_only() } /// The pages are covered, and no page key reaches them, a menu click's included: by a dialog or - /// prompt that turns the menus off (`modal_open`), by the full-screen and update prompts, which - /// leave the menus on, by the palette, which turns them off, or by the OCR Verify screen, which - /// takes the pages' place. + /// prompt (`modal_open`), by the palette, or by the OCR Verify screen, which takes the pages' + /// place. pub(crate) fn covers_pages(&self) -> bool { // Full screen draws the page alone: not the palette, nor the OCR Verify screen it was // entered over. Dialogs and prompts show there too. - let shown = !(self.full_screen && self.active.is_some()); - self.modal_open() || self.pending_full_screen.is_some() || self.updates.prompt_open() || (self.palette_open || self.ocr_verify.open) && shown + let shown = !(self.screen_mode.body_only() && self.active.is_some()); + self.modal_open() || (self.palette_open || self.ocr_verify.open) && shown } /// A dialog or prompt is open over the window: the keyboard is its own, and nothing may act /// on the document underneath it. pub(crate) fn modal_open(&self) -> bool { - #[cfg(not(target_arch = "wasm32"))] - if self.script_pending.as_ref().is_some_and(|pending| pending.has_prompt()) { - return true; - } - self.dialog.is_some() - || self.close_request.is_some() - || self.password_prompt.is_some() - || self.unlock_prompt.is_some() - || self.pending_link.is_some() - || self.pending_remote_link.is_some() - || self.updates.open + !self.dialogs.is_empty() + || self.preferences.is_some() + || self.shortcuts.is_some() + || self.redact_props.is_some() + || self.redact_search_open + || self.hidden_draft.is_some() + || self.sign_draft.is_some() + || self.cert_viewer.is_some() + || self.js_dialog.is_some() + || self.comment_props.is_some() + || self.stamp_dialog.is_some() } - /// Show `msg` in the toast now, in place of whatever it showed. Script messages still waiting - /// show after it. + /// Show `msg` as a notice. pub fn notify(&mut self, msg: impl Into) { - // A left-out count it replaces is said again once the toast is free. - self.script_messages_dropped = self.script_messages_dropped.saturating_add(std::mem::take(&mut self.toast_dropped)); - self.toast = Some((msg.into(), 0.0)); - self.toast_script = None; + self.posted_notices.push(craft::ui::notices::PostedNotice::new(msg)); } /// Notify with a static message in the UI language. @@ -532,56 +558,46 @@ impl PdfCraftApp { } impl eframe::App for PdfCraftApp { - /// While files are dragged over the window the system sends no pointer moves, so egui - /// would keep the place the pointer entered at: tell it where the pointer really is, so the - /// page grid can show (and use) the gap under it. + /// The runtime's fired commands and this frame's root values, before egui reads the input. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - // The button's release a window move or resize kept from egui. - window_controls::release_after_desktop_grab(ctx, raw); - // The wheel after Alt+Tab back, before the mouse has moved (#1518). - let known = ctx.input(|i| i.pointer.latest_pos().is_some()); - let size = ctx.input(|i| i.viewport().inner_rect).map_or(egui::Vec2::ZERO, |r| r.size()); - drag_pointer::locate_wheel(raw, known, size, || drag_pointer::in_window(ctx)); self.prepare_raw_input(ctx, raw); - if raw.hovered_files.is_empty() && raw.dropped_files.is_empty() { - return; - } - if let Some(pos) = drag_pointer::in_window(ctx) { - raw.events.push(egui::Event::PointerMoved(pos)); - } - ctx.request_repaint(); } - fn save(&mut self, storage: &mut dyn eframe::Storage) { - // eframe has just stored the window as it is now: not while it is minimized. - #[cfg(not(target_arch = "wasm32"))] - { - let minimized = self.ctx.as_ref().is_some_and(|c| c.input(|i| i.viewport().minimized == Some(true))); - self.window_state.keep(storage, minimized); - } - storage.set_string("pdfcraft", self.persist()); + /// The preferences go to the settings store, which writes them when they changed. + fn save(&mut self, _storage: &mut dyn eframe::Storage) { + self.save_settings(); } /// Starts an update that waits for the exit. On macOS the process ends before the app is dropped. fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { - self.updates.exiting(); + #[cfg(not(target_arch = "wasm32"))] + self.updater.start_pending_update(); } - /// Each frame's work before drawing: opens, operating-system and control-channel requests, - /// the quit guard, shortcuts, and the background jobs' results. + /// Each frame's work before drawing: the update check, opens, control-channel requests, the + /// background jobs' results, and last the close path (the "save changes?" questions). /// /// Last-resort guard (AGENTS.md §4, #3914): a panic in a frame is reported and the app, with /// every open tab, keeps running; see `frame_guard`. fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { self.begin_logic(); + #[cfg(not(target_arch = "wasm32"))] + self.update_logic(ctx); self.guarded_frame(|app| app.logic_unguarded(ctx)); if self.frame_panicked { self.close_after_panic(ctx); } + self.run_close_path(ctx); } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + embed::before_ui(ui.ctx(), frame); self.begin_ui(); + // The native file panels the host's file service asked for, over this window. + #[cfg(not(target_arch = "wasm32"))] + if let Some(panels) = self.file_panels.as_mut() { + panels.pump_with(&mut self.dialogs, Some(&*frame)); + } self.guarded_frame(|app| app.ui_unguarded(ui)); self.end_ui(); } @@ -591,13 +607,9 @@ impl PdfCraftApp { fn logic_unguarded(&mut self, ctx: &egui::Context) { #[cfg(test)] self.injected_panic(crate::frame_guard::FramePart::Logic); - self.ctx = Some(ctx.clone()); #[cfg(not(target_arch = "wasm32"))] self.poll_script_dialog(ctx); - #[cfg(not(target_arch = "wasm32"))] - self.window_state.repair(ctx); - self.dialog_epoch(); - // Notices raised outside `ui` (opened files, OS events, the control channel) translate too. + // Notices raised outside `ui` (opened files, the control channel) translate too. let lang = i18n::Lang::from_pref(&self.language); i18n::set_current(lang); self.apply_status_captions(lang); @@ -606,138 +618,28 @@ impl PdfCraftApp { pdfcraft_engine::dates::use_form_date_language(self.session.date_language().unwrap_or(lang.code())); #[cfg(not(target_arch = "wasm32"))] { - if let Some(worker) = &self.open_worker { - worker.set_context(ctx); - } self.poll_pending_opens(); - self.show_reveal_errors(); self.poll_pending_destinations(); } self.check_restored_recent(); - // Chinese wants its own faces before the Japanese ones (one baseline per line). - let cjk = theme::CjkPreference::for_language(lang.code()); - if !self.styled { - egui_extras::install_image_loaders(ctx); - theme::install_fonts_for(ctx, cjk); - self.fonts_cjk = cjk; - theme::apply(ctx, self.theme); - self.styled = true; - } else { - self.fonts_ready = true; - if cjk != self.fonts_cjk { - // Same family names as before, so named fonts stay valid while the new set loads. - theme::install_fonts_for(ctx, cjk); - self.fonts_cjk = cjk; - } - } - self.sync_theme(ctx); - let native = ctx.native_pixels_per_point().unwrap_or(1.0); - ui_scale::sync(ctx, ui_scale::zoom(self.ui_scale, self.system_text_scale, native), &mut self.ui_scale_applied); - // Remember user work even if its tab is subsequently closed or Home is selected. - self.startup_superseded |= !self.views.is_empty() || self.combine_showing() || self.dialog.is_some() || self.password_prompt.is_some(); - // Also done in `raw_input_hook`, before input; here for hosts that don't call the hook. - self.scroll_speed.set_line_speed(ctx); - // Motion reads this frame's wheel input, so it begins in `ui`, in a known UI phase: - // `logic` also runs alone while hidden, where the input events and time are stale. - // Before taking this frame's drop: the grid must be drawn once with the pointer where - // the files were let go before the gap is read. - self.finish_grid_drop(ctx); // Showing a document hides the Combine files tab. if self.active.is_some() { self.combine_tab.focused = false; } - #[cfg(target_arch = "wasm32")] - self.process_signature_images(); - let dropped = ctx.input(|i| i.raw.dropped_files.clone()); - #[cfg(not(target_arch = "wasm32"))] - let dropped = self.drop_on_signature_pad(dropped); - #[cfg(not(target_arch = "wasm32"))] - let dropped = self.drop_on_grid(dropped, ctx); - // Files dropped on the Combine files tab join its list, all at once, instead of opening. - if self.combine_showing() && !dropped.is_empty() { - self.drop_into_combine(dropped, ctx); - } else { - for f in dropped { - self.open_dropped(f, ctx); - } - } - let arrived: Vec<(String, Vec)> = self.inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default(); - for (name, bytes) in arrived { - if let Err(e) = self.open_bytes(&name, None, bytes) { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e.to_string())]); - } - } - // Don't replace a pending prompt or import. A startup file may need its own password - // prompt, so its bytes stay queued until the current interaction finishes. - #[cfg(not(target_arch = "wasm32"))] - let opening = !self.pending_opens.is_empty() || !self.deferred_opens.is_empty(); - #[cfg(target_arch = "wasm32")] - let opening = false; - if !opening - && self.password_prompt.is_none() - && self.image_import.is_none() - && self.dialog.is_none() - && self.close_request.is_none() - && self.pending_link.is_none() - && self.pending_remote_link.is_none() - { - let startup = self.startup_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default(); - for (name, bytes) in startup { - let activate = !self.startup_superseded; - if let Err(e) = self.open_bytes_with_focus(&name, None, bytes, activate) { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]); - } - } - } - let failed: Vec<(String, String)> = self.failed_inbox.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default(); - for (name, e) in failed { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &e)]); - } - let os_events = self.os_events.as_mut().map(|poll| poll()).unwrap_or_default(); - for e in os_events { - match e { - #[cfg(not(target_arch = "wasm32"))] - OsEvent::Open(paths) => { - paths.iter().for_each(|p| { - self.open_path(p); - }); - // Files handed to the running app (Finder, or another launch): bring its - // window to the front, also when minimized or full screen on another Space. - ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - // Combine from File Explorer's PDF menu, also handed to the running app: the dialog - // it opens has to be seen, so the window comes to the front as for Open. - #[cfg(not(target_arch = "wasm32"))] - OsEvent::Combine(paths) => { - self.combine_paths(&paths); - ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - #[cfg(target_arch = "wasm32")] - OsEvent::Open(_) | OsEvent::Combine(_) => {} - // Like closing the window: `guard_quit` asks about unsaved changes. - OsEvent::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), - } - } + // PLAN: assumed PdfCraftApp::open_intake(&mut self, &egui::Context), which opens what the intake holds (pdf-shell-w13). + self.open_intake(ctx); self.present_portfolios(); if let Some((_, id)) = self.active_ids() { let out = self.session.take_js_output(id); self.handle_js(id, out); } self.script_tick(ctx); - if let Some(mut control) = self.control.take() { - control.tick(ctx, self); - self.control = Some(control); - } - self.guard_quit(ctx); - // macOS: quit through `terminate:` instead of dropping the window (Touch Bar crash, #1136). - #[cfg(target_os = "macos")] - craft_quit::on_close_request(ctx); + self.control_logic(ctx); self.autosave_tick(ctx, web_time::Instant::now()); // Reload documents whose files a build rewrote (#431). + // PLAN: assumed reload::watch_files(&mut PdfCraftApp, &egui::Context) at crate::platform::reload (pdf-shell-w14). #[cfg(not(target_arch = "wasm32"))] - self.watch_files(); + crate::platform::reload::watch_files(self, ctx); if self.host_dirty.is_some() { // An OCR review not yet accepted or rejected is work the page would lose, too. let dirty = self.work_at_risk(); @@ -745,52 +647,32 @@ impl PdfCraftApp { report(dirty); } } - self.poll_updates(); + // The browser asks before a reload or a tab close loses that work. + #[cfg(target_arch = "wasm32")] + craft::quit::web::hold_leave(self.work_at_risk()); self.poll_print(); - // Shortcuts deferred last frame: the text field has taken that frame's typing since. - let deferred = std::mem::take(&mut self.deferred_commands); - self.native_menu_clicks(ctx); - // The input a menu click stands for (⌘C, Delete…), before anything reads this frame's keys. - self.release_menu_input(ctx); - // A command's chord pressed with the keyboard on the menu bar (Alt, F10) takes it off the - // bar, so the chord runs in the same press, the pages' as well as the registry's. - craft_menu::bar::leave_for_shortcut(ctx); - self.hotbar.close_hidden_picker(ctx, self.hotbar_hidden()); - self.page_keys = page_keys::PageKeys::new(self.over_pages(ctx)); - self.shortcuts(ctx); // Scrolling and group-drag previews are transient: never resume after changing tabs, // opening a modal/palette, or returning to a window that lost focus. let blocked = self.modal_open() || self.palette_open || !ctx.input(|i| i.focused); for (index, view) in self.views.iter_mut().enumerate() { let shut = blocked || self.active != Some(index); view.objects.set_input_blocked(shut); - if shut { - view.auto_scroll.cancel(); - // Edit text and Add text's drags end while their input is blocked rather than wait, to - // land wherever the pointer is once it opens again. - if matches!(self.quick_tool, QuickTool::EditText | QuickTool::AddText) { - view.cancel_edit_text_gestures(); - } - } - } - // A field that refused its value this frame keeps the shortcut from saving or printing - // behind the user's back; so does a save prompt opened since. - if self.process_pending_edits() && self.close_request.is_none() { - for (id, doc) in deferred { - // Only in the document the shortcut was pressed in. - if self.active_ids().map(|(_, active)| active) == doc { - self.execute(id); - } + // Edit text and Add text's drags end while their input is blocked rather than wait, to + // land wherever the pointer is once it opens again. + if shut && matches!(self.quick_tool, QuickTool::EditText | QuickTool::AddText) { + view.cancel_edit_text_gestures(); } } + self.process_pending_edits(); self.poll_export(); self.auto_ocr_scanned_page(); self.poll_ocr(); self.poll_optimize(); self.poll_scan_clean(); self.poll_action(); - // The OCR Verify screen's worker may have finished while no frame was drawn. - if self.ocr_verify.phase == workflows::ocr_verify::Phase::Running { + // The OCR Verify screen's runs and re-reads may have finished while no frame was drawn. + let verify = self.verify_jobs.counts(); + if verify.queued + verify.running + verify.finished > 0 { workflows::ocr_verify::with_state(self, workflows::ocr_verify::OcrVerify::poll); } // A run or re-read asked for while the web build downloaded the models starts when they land. @@ -798,17 +680,7 @@ impl PdfCraftApp { if self.ocr_verify.awaiting_models.is_some() { workflows::ocr_verify::with_state(self, workflows::ocr_verify::OcrVerify::poll_models); } - // So may a page or region re-read's worker. - if self.ocr_verify.reread.is_some() { - workflows::ocr_verify::with_state(self, workflows::ocr_verify::OcrVerify::poll_reread); - } - self.process_file_requests(); - #[cfg(not(target_arch = "wasm32"))] - self.process_picked(); self.settle_presign(); - // Last, after everything that can open or answer the "save changes?" question. - self.attend_save_prompt(ctx); - self.sync_native_menu(ctx); self.sync_titles(ctx); } @@ -817,35 +689,29 @@ impl PdfCraftApp { self.injected_panic(crate::frame_guard::FramePart::Ui); let ctx = ui.ctx().clone(); i18n::set_current(i18n::Lang::from_pref(&self.language)); - // A language change switches stock chrome between LTR and RTL before anything is drawn. - theme::sync_direction(&ctx); // Fonts registered via set_fonts only take effect next frame; named families would panic now. if !self.fonts_ready { ctx.request_repaint(); return; } - // Before any widget reads this frame's wheel input or draws. - self.motion.begin_pass(&ctx, self.animation_effects); - // One-time 0.36 -> 0.37 panel persistence migration, before any panel stores or reads state. - migrate_panel_state(ui); - // Another tool lets go of a click whose picture is still being found, whether or not its - // page is drawn to see the change. - let picks = self.quick_tool == QuickTool::Select; - for view in &mut self.views { - view.begin_render_frame(); - if !picks { + // Another tool lets go of a click whose picture is still being found. + if self.quick_tool != QuickTool::Select { + for view in &mut self.views { view.pending_pick = None; } } panes::frame(self); // Forms' scripts read Highlight fields as `app.runtimeHighlight`. - let highlight = self.active.and_then(|i| self.views.get(i)).map_or(self.view_defaults.highlight_fields, |v| v.highlight_fields); + let highlight = self.active.and_then(|i| self.views.get(i)).map_or(self.highlight_fields, |v| v.highlight_fields); self.session.set_field_highlight(highlight); self.sync_titles(&ctx); // The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on // Windows) can tell it apart (#4614). egui builds the root node afresh every pass. ctx.accesskit_node_builder(egui::accesskit_root_id(), |root| root.set_label(self.window_title.as_str())); - if self.full_screen && self.active.is_some() { + // PLAN: assumed chrome::shell(&mut PdfCraftApp, &mut egui::Ui), the AppShell pass: menu bar, tab strip, mode bar, window edges and captions (pdf-chrome-w10). + chrome::shell(self, ui); + self.follow_screen_mode(); + if self.screen_mode.body_only() && self.active.is_some() { // Full screen: the page on black, nothing else, as Acrobat's Full Screen Mode (Esc // or ⌘L to leave). egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::BLACK)).show(ui, |ui| { @@ -856,77 +722,46 @@ impl PdfCraftApp { } } }); - dialogs::show(self, &ctx); - // Notices too: a refused field value or a failed save must be seen in full screen. - self.show_progress(&ctx); - widgets::toast(self, &ctx); - self.finish_render_frame(&ctx); - if let Some(mut control) = self.control.take() { - control.finish_frame(&ctx, self); - self.control = Some(control); + } else { + // Another mode or the Home tab puts the OCR Verify screen away, as Exit does; Correct + // recognized text brings it back with its review as it was. + if self.ocr_verify.open && (self.active.is_none() || self.ocr_verify.shown_in.is_some_and(|m| m != self.mode)) { + self.ocr_verify.open = false; } - return; - } - self.sync_window_frame(&ctx); - if self.draws_window_frame() { - window_controls::resize_edges(&ctx); - } - chrome::tab_strip(self, ui); - // A document can hide the toolbars, the menu and the panels around it in its tab (ISO - // 32000-2 Table 147); the tab strip stays, and F8 brings the rest back (`viewer_prefs`). - let hidden = self.hidden_interface(); - if !hidden.mode_bar(self.native_menu.is_some()) { - chrome::mode_bar(self, ui); - } - // Another mode or the Home tab puts the OCR Verify screen away, as Exit does; Correct - // recognized text brings it back with its review as it was. - if self.ocr_verify.open && (self.active.is_none() || self.ocr_verify.shown_in.is_some_and(|m| m != self.mode)) { - self.ocr_verify.open = false; - } - self.ocr_verify.shown_in = self.ocr_verify.open.then_some(self.mode); - if self.ocr_verify.open { - // The OCR Verify screen takes the document area (its four panes) under the window's - // tabs, menus and toolbar, which stay (#6485); the palette, dialogs and notices - // still show above it. - workflows::ocr_verify::show(self, ui); - palette::show(self, &ctx); - dialogs::show(self, &ctx); - self.show_progress(&ctx); - widgets::toast(self, &ctx); - self.finish_render_frame(&ctx); - if let Some(mut control) = self.control.take() { - control.finish_frame(&ctx, self); - self.control = Some(control); - } - return; - } - // Whichever way another tab came to the front, it shows instead of the expanded view. - if self.all_tools_full && self.all_tools_tab != self.shown_tab() { - self.all_tools_full = false; - } - if !hidden.window_ui { - side_panels::show(self, ui); - } - let t = theme::Tokens::get(&ctx); - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| { - if self.mode == Mode::AllTools && self.all_tools_full && !hidden.window_ui { - all_tools_ui::show(self, ui); + self.ocr_verify.shown_in = self.ocr_verify.open.then_some(self.mode); + if self.ocr_verify.open { + // The OCR Verify screen takes the document area (its four panes) under the window's + // tabs, menus and toolbar, which stay (#6485). + workflows::ocr_verify::show(self, ui); } else { - panes::page_area(self, ui); + // Whichever way another tab came to the front, it shows instead of the expanded view. + if self.all_tools_full && self.all_tools_tab != self.shown_tab() { + self.all_tools_full = false; + } + // A document can hide the toolbars, the menu and the panels around it in its tab (ISO + // 32000-2 Table 147); the tab strip stays, and F8 brings the rest back (`viewer_prefs`). + let hidden = self.hidden_interface(); + if !hidden.window_ui { + side_panels::dock(self, ui); + } + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { + if self.mode == Mode::AllTools && self.all_tools_full && !hidden.window_ui { + all_tools_ui::show(self, ui); + } else { + panes::page_area(self, ui); + } + }); + // FitWindow and CenterWindow, once the document just opened is laid out. + self.window_preferences_frame(&ctx); + self.process_pending_edits(); } - }); - // FitWindow and CenterWindow, once the document just opened is laid out. - self.window_preferences_frame(&ctx); - self.process_pending_edits(); - palette::show(self, &ctx); - dialogs::show(self, &ctx); - self.show_progress(&ctx); - widgets::toast(self, &ctx); - self.finish_render_frame(&ctx); - // Screenshots are issued only after a settled pass that really drew the window. - if let Some(mut control) = self.control.take() { - control.finish_frame(&ctx, self); - self.control = Some(control); + palette::show(self, &ctx); } + // Dialogs and notices show in full screen too: a refused field value or a failed save must be seen. + dialogs::show(self, ui); + crate::notices::show(self, ui); + // Screenshots are issued only after a settled pass that really drew the window. + // PLAN: assumed PdfCraftApp::control_frame_end(&mut self, &egui::Context), the control channel's capture issue after the pass (pdf-shell-w11). + self.control_frame_end(&ctx); } } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 733eabdd8e..f8d07e71d1 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,208 +1,25 @@ use super::*; -impl PdfCraftApp { - /// Draw the running job's progress card and pass a Cancel click on to the job. - pub(super) fn show_progress(&mut self, ctx: &egui::Context) { - if widgets::progress_notice(self, ctx) { - self.cancel_optimize(); - self.cancel_scan_clean(); - } - } - - pub(super) fn sync_theme(&mut self, ctx: &egui::Context) { - #[cfg_attr(not(target_os = "linux"), expect(unused_mut))] - let mut system = ctx.system_theme().map(|theme| theme == egui::Theme::Dark); - #[cfg(target_os = "linux")] - { - let active = self.theme_preference == ThemePreference::System; - if self.desktop_theme_enabled && active && self.desktop_theme.is_none() { - let ctx = ctx.clone(); - self.desktop_theme = Some(pdfcraft_platform::desktop_theme::DesktopTheme::start(move || ctx.request_repaint())); - } - if let Some(desktop) = &self.desktop_theme { - desktop.set_active(active); - // The standard portal supplies Linux desktop appearance. No preference - // must clear an earlier answer rather than retaining stale dark chrome. - system = desktop.get().map(|appearance| appearance == pdfcraft_platform::desktop_theme::DesktopAppearance::Dark); - } - } - let kind = self.theme_preference.resolve(system, ThemeKind::Light); - if kind != self.theme { - self.theme = kind; - theme::apply(ctx, kind); - } - } -} - -/// Root-level panel salts whose 0.36 persisted state key changed in 0.37. -/// -/// The shared rail and side panes now own their state. The legacy `rail` and -/// `read_right_panel` entries are inert; the former `rail-nav` footer is no longer migrated. -const PANEL_SALTS: [&str; 4] = ["tab_strip", "mode_bar", "rail", "read_right_panel"]; - -/// Copy persisted 0.36 panel sizes to 0.37's parent-scope key, once, before the first panel. -/// -/// 0.36 stored [`egui::PanelState`] under the panel's own `Id::unique(salt)`; 0.37 derives it -/// from the parent `Ui`'s scope plus an `IdSalt`. A missing copy would reset a width the user -/// chose. The old entry is left untouched, so rolling back to 0.36 still finds it. -pub(super) fn migrate_panel_state(ui: &egui::Ui) { - if ui.ctx().viewport_id() != egui::ViewportId::ROOT { - return; - } - for salt in PANEL_SALTS { - migrate_panel_state_from(ui, salt); - } -} - -/// Copy one 0.36 panel's state to the key derived from this exact parent `Ui`. -/// -/// The parent must be the `Ui` the panel is shown in (for a nested panel, the panel's content -/// `Ui`), because 0.37's key includes that `Ui`'s scope. -pub(crate) fn migrate_panel_state_from(ui: &egui::Ui, salt: &str) { - let old = egui::Id::unique(salt); - let new = ui.scope_id().with_salt(egui::IdSalt::new(salt)); - if old == new || egui::PanelState::load(ui.ctx(), new).is_some() { - return; - } - if let Some(state) = egui::PanelState::load(ui.ctx(), old) { - ui.ctx().data_mut(|data| data.insert_persisted(new, state)); - log::debug!("migrated panel {salt} state {:?}", state.size()); - } -} +use craft::ui::runtime::frame::FrameInput; +use craft::ui::shell::embed; impl PdfCraftApp { - /// The parts of [`eframe::App::raw_input_hook`] that must run before egui's input hooks: - /// publish this pass's input-target generation to the control plugin, and hand the wheel - /// input to the reduced-motion reader. - /// - /// A test host that drives the app without eframe's raw hook can call this first, so its - /// frame ordering matches production instead of hiding focus-change bugs. - #[doc(hidden)] - pub fn prepare_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - // The control plugin's input hook runs next: give it this pass's input generation. - if let Some(control) = &self.control { - control.set_epoch(self.input_epoch()); - } - // Before egui reads this frame's wheel input. - self.scroll_speed.apply(ctx, raw); - // The native menu's key equivalents. - if let Some(native) = self.native_menu.as_mut() { - native.raw_input(raw); - } - } -} - -impl PdfCraftApp { - pub(crate) fn finish_render_frame(&mut self, ctx: &egui::Context) { - self.finish_document_copy(ctx); - // The Combine grid's thumbnails, whichever tab shows (renders under way still finish). - self.combine_thumbs_frame(ctx); - // Retire hidden documents before admitting the visible documents' textures, so the - // three cache limits apply to the application, regardless of how many tabs are open. - // On screen: the active tab, the comparison's old file side by side with it, and what - // split view's other pane shows. - let shown = self.views_on_screen(); - let shown_docs: std::collections::HashSet = shown.iter().filter_map(|&i| self.views.get(i)).map(|v| v.id).collect(); - for (i, view) in self.views.iter_mut().enumerate() { - if shown.contains(&i) { - continue; + /// The app's part of [`eframe::App::raw_input_hook`], before egui reads the frame's input: + /// what the platform pasted goes to the clipboard service, then the runtime hands over what + /// it gathered since the last frame (the commands fired) and takes this frame's root values, + /// command states and host. eframe calls the hook once per frame, before the first pass, so + /// a second pass of the same frame runs on what this call set and fires nothing twice. + pub(super) fn prepare_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.offer_pasted(raw); + embed::before_input(ctx, |output| { + for fired in &output.fired { + self.run_fired(ctx, fired); } - if shown_docs.contains(&view.id) { - // Another tab of this document is on screen, and renders through its pool. - view.release_rasters(); - } else if let Some(doc) = self.session.get(view.id) { - view.suspend_rendering(&doc.renderer); + for declined in &output.declined { + self.run_declined(declined); } - } - // Each document on screen once: two views of it (split view) share its render pool. - let mut done = std::collections::HashSet::new(); - for &i in &shown { - let Some(id) = self.views.get(i).map(|v| v.id) else { continue }; - if !done.insert(id) { - continue; - } - let Some(doc) = self.session.get(id) else { continue }; - let group: Vec = shown.iter().copied().filter(|&k| self.views.get(k).is_some_and(|v| v.id == id)).collect(); - match group.as_slice() { - [only] => { - if let Some(view) = self.views.get_mut(*only) { - view.finish_render_frame(ctx, &doc.info, &doc.renderer); - } - } - _ => DocView::finish_shared_render_frame(ctx, &doc.info, &doc.renderer, &mut self.views, &group), - } - } - } -} - -#[cfg(test)] -mod panel_migration_tests { - use super::*; - - fn state(width: f32) -> egui::PanelState { - egui::PanelState { outer_rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(width, 900.0)) } - } - - /// 0.36 stored a panel's persisted size under `Id::unique(salt)`. 0.37 derives the key from - /// the root `Ui`'s scope; the upgrade must carry the chosen width over, not reset it. - #[test] - fn upgrade_from_036_panel_memory_keeps_width() { - let ctx = egui::Context::default(); - let old = egui::Id::unique("rail"); - ctx.data_mut(|d| d.insert_persisted(old, state(287.0))); - let mut migrated = None; - let mut new_id = None; - let output = ctx.run_ui(egui::RawInput::default(), |ui| { - migrate_panel_state(ui); - new_id = Some(ui.scope_id().with_salt(egui::IdSalt::new("rail"))); - migrated = egui::PanelState::load(ui.ctx(), new_id.expect("an id")); - }); - output.drop_without_applying_deltas(); - let migrated = migrated.expect("the 0.36 panel width migrates to the 0.37 key"); - assert!((migrated.size().x - 287.0).abs() <= 1.0, "width survives: {:?}", migrated.size()); - assert_eq!(new_id.unwrap(), ctx.viewport_id().root_ui_id().with_salt(egui::IdSalt::new("rail"))); - assert!(egui::PanelState::load(&ctx, old).is_some(), "the old key stays for rollback"); - } - - /// A synthetic nested panel is keyed from its own parent `Ui`, not the root. - /// Migrating it at the root would silently miss its 0.36 state; the fixture uses - /// legacy rail names but does not model the current shared rail implementation. - #[test] - fn nested_panel_state_migrates_from_its_actual_parent_ui() { - let ctx = egui::Context::default(); - let old = egui::Id::unique("rail-nav"); - ctx.data_mut(|d| d.insert_persisted(old, state(140.0))); - let mut nested_id = None; - let mut migrated = None; - let output = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::Panel::right("rail").resizable(false).exact_size(48.0).show(ui, |ui| { - migrate_panel_state_from(ui, "rail-nav"); - // The key egui will use for the nested panel shown in this same Ui. - let key = ui.scope_id().with_salt(egui::IdSalt::new("rail-nav")); - nested_id = Some(key); - migrated = egui::PanelState::load(ui.ctx(), key); - egui::Panel::bottom("rail-nav").resizable(false).show(ui, |_ui| {}); - }); - }); - output.drop_without_applying_deltas(); - let migrated = migrated.expect("the nested 0.36 state migrates to its parent-scoped key"); - assert_eq!(migrated.size().x, 140.0); - assert_ne!(nested_id.unwrap(), ctx.viewport_id().root_ui_id().with_salt(egui::IdSalt::new("rail-nav")), "the nested key is not the root key"); - } - - /// The one-time copy must never overwrite state a 0.37 run has already stored. - #[test] - fn migration_does_not_replace_a_037_panel_state() { - let ctx = egui::Context::default(); - let old = egui::Id::unique("rail"); - let new = ctx.viewport_id().root_ui_id().with_salt(egui::IdSalt::new("rail")); - ctx.data_mut(|d| { - d.insert_persisted(old, state(287.0)); - d.insert_persisted(new, state(412.0)); + let commands = crate::commands::catalog::command_input(self, ctx); + FrameInput::new(self.root_env()).commands(commands).host(self.host.clone()) }); - let output = ctx.run_ui(egui::RawInput::default(), |ui| migrate_panel_state(ui)); - output.drop_without_applying_deltas(); - let kept = egui::PanelState::load(&ctx, new).expect("the 0.37 state"); - assert_eq!(kept.size().x, 412.0); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d77c7b1eb7..773772235d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,13 +12,14 @@ /// PdfCraft as craft-update knows it, with its 128 px icon and accent colour: the update /// prompt shows both, and an AppImage's menu entry gets the icon. #[cfg(not(target_arch = "wasm32"))] -pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { +pub const UPDATE_APP: craft::update::app::App = craft::update::app::App { icon_png: Some(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.pdfcraft.png")), accent: Some([0xb7, 0x02, 0x28]), - ..craft_update::suite::PDFCRAFT + ..craft::update::suite::PDFCRAFT }; -use crate::control::Host as _; +/// PdfCraft as the framework's services know it (the host, About, recovery). +pub const APP_INFO: craft::host::AppInfo = craft::host::AppInfo { id: "pdfcraft", name: "PdfCraft", version: env!("CARGO_PKG_VERSION") }; /// Translate an English UI string into the current language (see [`i18n`]). macro_rules! tl { @@ -36,25 +37,22 @@ macro_rules! tl_ctx { } pub mod canvas; mod chrome; -mod image_engine; -pub use combine_grid::ThumbState as CombineThumb; -pub use combine_ui::{Columns as CombineColumns, CombineView, Lock as CombineLock, SortKey}; +pub use combine_ui::{CombineView, Lock as CombineLock, SortKey}; mod commands; pub mod control; mod menus; mod properties_session; /// Header & footer / watermark / background dialog types (tests and automation). pub mod marks { - pub use crate::marks_ui::{MarksDraft, PageRange, Subset}; + pub use crate::marks_ui::MarksDraft; + pub use craft::pages::{PageRange, PageScope, Subset}; } pub use content_ui::TextDraft; pub use create_ui::Clip; -pub use link_ui::LinkDraft; -pub use optimize_ui::{OptimizeDraft, OptimizeTab}; pub use sign_ui::{DigitalIdEntry, SignDraft, SignGraphic, SignStep}; mod bidi; mod dialogs; -pub use edit_text_ui::{CropMode, DragTarget, ImageDrag, ImageHandle, ImageSelection}; +pub use edit_text_ui::{CropMode, ImageSelection}; mod editing; mod home; mod hotbar; @@ -64,27 +62,28 @@ pub use print_ui::{ DefaultPaperSource, Handling as PrintHandling, OptionsSource, PrintDraft, PrinterPapersSource, PrinterSetup, PrinterSource, Spooler, TwoSidedSource, Which as PrintWhich, system_printers, system_two_sided, }; -pub use redact_ui::{HiddenDraft, PagesDraft as RedactPagesDraft, RedactPrefs, SearchDraft as RedactSearchDraft, SearchMode as RedactSearchMode}; +pub use redact_ui::{HiddenDraft, RedactPrefs, SearchDraft as RedactSearchDraft, SearchMode as RedactSearchMode}; pub mod i18n; -pub mod theme; pub mod viewer_prefs; -mod widgets; +// PLAN: the lead adds `mod notices; mod icons; mod brand; mod colour_picker; pub mod fonts;` here, and `pub mod settings;` in app.rs, at combine (L-212). use pdfcraft_engine::{DocId, Session}; -pub use canvas::{DocView, RasterMemory}; -#[doc(hidden)] -pub use editing::download_mime_type; +pub use app::AppServices; +#[cfg(not(target_arch = "wasm32"))] +pub use app::UpdateSource; +pub use canvas::DocView; /// Smallest window the shell is laid out for, in egui points (logical pixels, so the OS scale /// factor is already applied: 480 points are 600 px at 125 % and 720 px at 150 %). 480 is half of a /// 1440-wide screen at 150 % scaling, the tightest common half-screen split on Windows; the mode /// bar, tab strip and notice bars adapt below the old 820 minimum (#1913). pub const MIN_WINDOW_SIZE: [f32; 2] = [480.0, 520.0]; -pub use editing::{CloseRequest, SaveTarget}; -pub use files::{ExtractDraft, FilePurpose, FileRequest, RotateDraft, SplitDraft, SplitMode, SplitPlan}; -pub use recovery::{AUTOSAVE_SECS, RecoveryMeta, RecoveryStore, default_dictionary_dir}; -use theme::{ThemeKind, ThemePreference}; +pub use dialogs::properties::PropsTab; +pub use editing::SaveTarget; +pub use files::{ExtractOptions, FilePurpose, SplitPlan}; +pub use recovery::AUTOSAVE_SECS; +pub use workflows::js_dialogs::JsDialog; pub use workflows::ocr_verify::{OcrVerify, Phase}; mod app; @@ -98,30 +97,20 @@ mod state; mod tools; mod workflows; -#[cfg(not(target_arch = "wasm32"))] -pub(crate) mod os_clipboard; - +pub use app::settings; #[cfg(not(target_arch = "wasm32"))] pub(crate) use app::same_file; pub(crate) use app::{MAX_AUTHOR_CHARS, copy_refused, date_text_for_pdf, print_refused}; -use canvas::autoscroll; use canvas::crop; -use canvas::fling; use canvas::image_pick; -use canvas::page_cursor; -use canvas::page_keys; -use canvas::page_pointer; -use canvas::page_router; +use canvas::page_parts; pub use canvas::scroll_speed; use canvas::signature_drag; -use canvas::wheel_boost; -use canvas::wheel_pager; use canvas::zoom_snap; use dialogs::appearance; pub use dialogs::bookmark_styles_ui; use dialogs::comment_props; use dialogs::convert_colours_ui; -use dialogs::credits; use dialogs::hairlines_ui; use dialogs::marks_ui; use dialogs::pageboxes; @@ -131,13 +120,12 @@ use dialogs::protect; use dialogs::standards_ui; use dialogs::word_count_ui; pub use home::folders_ui; -pub use hooks::{FailedInbox, HostDirtyFn, HostSaveFn, Inbox, OsEvent, OsEventsFn}; +pub use hooks::HostDirtyFn; use menus::tab_context; use panels::all_tools_ui; use panels::comments_panel; use panels::format_text_ui; use panels::organize_panel; -use panels::page_selection_ui; use panels::search_ui; pub use panels::side_panels; pub use persist::last_session; @@ -145,35 +133,21 @@ pub use persist::last_view; pub use persist::paper; use persist::recovery; pub use persist::units; -#[cfg(not(target_arch = "wasm32"))] -pub use persist::window_state; -use platform::drag_pointer; use platform::file_filter; -#[cfg(not(target_arch = "wasm32"))] -pub use platform::file_watch; #[cfg(target_os = "macos")] use platform::macos_association; -pub use platform::motion; #[cfg(not(target_arch = "wasm32"))] use platform::open_worker; -#[cfg(not(target_arch = "wasm32"))] -use platform::pickers; -pub use platform::portable; -#[cfg(not(target_arch = "wasm32"))] -use platform::system_fonts; pub use platform::ui_scale; -pub use platform::updates; -pub use platform::window_controls; #[cfg(test)] use state::CopyPage; +use state::DocumentCopyJob; #[cfg(not(target_arch = "wasm32"))] use state::OpenRequest; pub use state::{ - CommentClip, CustomDraft, Dialog, DuplicateDraft, LeftPanel, LinkOrigin, Mode, NumberDraft, OpenOutcome, PageClip, PagePropsDraft, - PasswordPrompt, PendingLink, PendingRemoteLink, PropsTab, QuickTool, RECENT_FILES_DEFAULT, RECENT_FILES_MAX, RecentFile, RightPanel, - UnlockPrompt, + CommentClip, LeftPanel, LinkOrigin, Mode, OpenOutcome, PageClip, PagePropsDraft, PasswordPrompt, PendingLink, PendingRemoteLink, QuickTool, + RECENT_FILES_DEFAULT, RECENT_FILES_MAX, RecentFile, RightPanel, UnlockPrompt, }; -use state::{DocumentCopyJob, GridFile}; pub use tools::bulk_fields; use tools::calc_order_ui; use tools::camera_ui; @@ -191,8 +165,6 @@ use tools::redact_ui; use tools::sign_ui; use tools::stamps_ui; use tools::tags_ui; -use widgets::icon_data; -pub use widgets::icons; use workflows::a11y_ui; use workflows::actions_ui; use workflows::combine_grid; @@ -201,6 +173,7 @@ use workflows::compare_ui; use workflows::create_ui; use workflows::export_ui; use workflows::files; +use workflows::js_dialogs; use workflows::js_ui; #[cfg(target_arch = "wasm32")] use workflows::ocr_route; @@ -214,102 +187,54 @@ use workflows::print_ui; use workflows::scan_clean_ui; use workflows::web_print; -/// Files dropped on a document's page grid or its Pages panel. -struct GridDrop { - doc: pdfcraft_engine::DocId, - /// Dropped on the Pages panel (its gap decides where they go), not the page grid. - panel: bool, - files: Vec, - /// When to stop waiting for the pointer (monotonic: `logic` may run without a UI pass). - deadline: web_time::Instant, -} - -/// A whole-document copy reading its pages off the UI thread (in place on the web, which has no -/// threads). Dropping it (a new copy, the document closed) stops the reading. -struct DocumentCopy { - doc: DocId, - rx: std::sync::mpsc::Receiver, - cancel: std::sync::Arc, -} - -impl DocumentCopy { - fn start(doc: DocId, job: DocumentCopyJob, ctx: &egui::Context) -> DocumentCopy { - let (tx, rx) = std::sync::mpsc::channel(); - let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - #[cfg(not(target_arch = "wasm32"))] - { - let (stop, ctx) = (cancel.clone(), ctx.clone()); - let spawned = std::thread::Builder::new().name("copy-document-text".into()).spawn(move || { - if let Some(text) = job.text(&stop) { - let _ = tx.send(text); - ctx.request_repaint(); - } - }); - if let Err(e) = spawned { - log::warn!("copying the document's text: {e}"); - } - } - #[cfg(target_arch = "wasm32")] - { - let _ = ctx; - if let Some(text) = job.text(&cancel) { - let _ = tx.send(text); - } - } - DocumentCopy { doc, rx, cancel } - } -} - -impl Drop for DocumentCopy { - fn drop(&mut self) { - self.cancel.store(true, std::sync::atomic::Ordering::Relaxed); - } -} +/// A background job queue of the app, built over the host's jobs and the app's wake. +type Queue = craft::host::queue::JobQueue; +/// A file being opened in the background, waiting for the open queue's answer. #[cfg(not(target_arch = "wasm32"))] struct PendingOpen { token: u64, - receiver: std::sync::mpsc::Receiver, name: String, path: Option, - stamp: Option, + stamp: Option, activate: bool, after_open: Option, - recovered: Option, + recovered: Option, then: Option<&'static str>, - display_override: Option<(canvas::PageLayout, bool)>, - /// A reply taken from `receiver` and kept back for later (a password prompt waiting for an + display_override: Option, + /// An answer taken from the queue and kept back for later (a password prompt waiting for an /// earlier file's password retry). ready: Option, } -/// A file named while the worker's queue was full: submitted once it has room. -#[cfg(not(target_arch = "wasm32"))] -struct DeferredOpen { - path: String, - after_open: Option, - then: Option<&'static str>, - display_override: Option<(canvas::PageLayout, bool)>, -} - -/// Puts `(html, plain_text)` on a clipboard; `false` when it couldn't, and plain-text Copy is -/// used instead. -pub type HtmlClipboard = Box bool>; - -/// A named destination being looked up off the UI thread: reading a large document's name tree -/// takes a noticeable moment. -#[cfg(not(target_arch = "wasm32"))] -struct PendingDestination { - doc: DocId, - name: String, - receiver: std::sync::mpsc::Receiver>, -} - pub struct PdfCraftApp { + /// The app's services: jobs, files, settings sections, commands. Every queue is built from it. + pub(crate) host: std::sync::Arc, + /// Asks for a frame from any thread; every queue calls it when a job finishes. + pub(crate) wake: craft::host::Wake, + /// Files the operating system, another launch, a drop or the embedding page asked to open. + intake: craft::platform::open::FileIntake, + /// The native file panels the host's file service asks through; pumped every pass. + #[cfg(not(target_arch = "wasm32"))] + file_panels: Option, + // PLAN: assumed settings::Store, the opened settings store, and PdfCraftApp::{apply_settings, attach_settings, save_settings} (pdf-shell-w9). + /// The settings store the preferences are read from and written to. + pub(crate) settings: Option, + /// The dialogs, prompts and notices the app has open, and their results. + pub dialogs: craft::ui::dialog::DialogHost, + /// The questions an open asks (password, unlock, links, full screen) on the dialog host. + pub(crate) prompts: dialogs::prompts::OpenPrompts, + /// Preferences, while its window is open. + pub(crate) preferences: Option, + /// Keyboard Shortcuts, while its window is open. + pub(crate) shortcuts: Option, /// Split view (`panes`); which pane shows each tab is its view's. pub panes: panes::Panes, - /// Tools side and pane widths; which panes are open is `left_open` and `right`. - pub side_panels: side_panels::SidePanels, + // PLAN: assumed side_panels::{PanelId, RailSide, default_workspace, right_of} (pdf-chrome-w1, L-136). + /// Where the side panels are docked, their sizes and which are open. + pub dock: craft::behavior::dock::Workspace, + /// The side the rail of panel buttons sits on. + pub rail_side: side_panels::RailSide, pub session: Session, /// The interface language signature status captions were last drawn in. pub(crate) status_captions_lang: Option, @@ -324,18 +249,16 @@ pub struct PdfCraftApp { /// Documents and view). Continuous scrolling at fit width by default, which never snaps /// between pages. pub view_defaults: canvas::ViewDefaults, + /// Preferences ▸ Highlight fields for newly opened forms (saved as `highlight_fields`). + pub(crate) highlight_fields: bool, /// The unit page sizes and margins are shown in (Preferences ▸ Documents and view). pub units: units::Unit, /// The paper Create ▸ Blank page makes (#5644): the system region's. pub blank_paper: paper::Paper, - /// The Preferences ▸ Date format box while it's being edited, or while it holds an invalid - /// pattern (the session keeps the last valid one). - pub date_format_draft: Option, /// Explicit CLI/control mode lasts for this session and is never persisted. mode_override: Option, pub left: LeftPanel, pub left_open: bool, - pub right: Option, /// The side panel F4 reopens: the one open last. pub(crate) last_right: RightPanel, /// The right panel that was open when the user switched to Read mode, which starts with the @@ -354,52 +277,37 @@ pub struct PdfCraftApp { portfolio_initial: Option<(DocId, String)>, /// The document whose tab [`Self::present_portfolios`] last saw active. portfolio_seen: Option, - /// Browser file reads still under way (drops, the web file picker): each file opens in front - /// when it arrives. - #[cfg(target_arch = "wasm32")] - web_reads: std::sync::Arc, /// A portfolio's file list is showing in place of this panel (`None`: the panel was /// closed), given back when its tab is left. portfolio_panel: Option>, pub quick_tool: QuickTool, - /// The tool to go back to when Space, held for a temporary Hand, is released. - space_hand: Option, /// The tool before full screen, given back on leaving it (see [`Self::apply_full_screen`]). full_screen_tool: Option, /// Comment author, per-tool colours and widths, pin. pub comment_prefs: comments::CommentPrefs, + /// The colours picked last in the comment tools' colour pickers. + pub(crate) recent_colours: crate::colour_picker::RecentColours, pub(crate) hotbar: hotbar::Hotbar, - /// Resolved colours, including the current OS theme when following the system. - pub theme: ThemeKind, - pub theme_preference: ThemePreference, + /// Preferences ▸ Appearance: light, dark, or as the system says. + pub theme_preference: craft::theme::ModeChoice, /// The reading-colours preference (Preferences ▸ Reading colours): applied to every open /// document, and documents open with it (Acrobat's Replace Document Colors). pub reading_colors: pdfcraft_render::ReadingColors, /// App-wide page decoration only; never part of a PDF edit or render request. pub show_page_edge_shadows: bool, - /// The Linux portal is enabled only by the native host, and starts on the first System choice. - #[cfg(target_os = "linux")] - desktop_theme: Option, - #[cfg(target_os = "linux")] - desktop_theme_enabled: bool, /// How far a mouse-wheel notch scrolls. pub scroll_speed: scroll_speed::ScrollSpeed, /// Preferences ▸ Invert middle-button drag: the middle button's pan or auto-scroll moves the /// view the other way. Off by default. pub invert_middle_drag: bool, /// Preferences ▸ Animation effects: on, off, or as the system's animation setting says. - pub animation_effects: motion::AnimationEffects, - /// Whether the system asked for no animations, and how the desktop app asks it. - pub motion: motion::Motion, + pub animation_effects: craft::theme::MotionChoice, /// Interface language preference: `auto` (follow the system) or a code from [`i18n::LANGUAGES`]. pub language: String, - /// Preferences ▸ Interface size as a factor, or `None` to follow [`Self::system_text_scale`]. + /// Preferences ▸ Interface size as a factor, or `None` for the usual size. pub ui_scale: Option, - /// The desktop's text scaling (GNOME's text scaling factor), which the desktop app reads at - /// launch. 1.0 elsewhere, so tests and screenshots don't depend on the machine. - pub system_text_scale: f32, - /// The interface size last given to egui ([`ui_scale::sync`]). - ui_scale_applied: Option, + /// Preferences ▸ Use system title bar. + pub title_bar_choice: craft::window::policy::TitleBarPref, /// Preferences: bake Fill & Sign marks into the page when saving. Off, so a normal save stays editable. pub flatten_fill_sign_on_save: bool, /// Ask on the first save after Fill & Sign places a signature or initials whether to lock @@ -408,13 +316,12 @@ pub struct PdfCraftApp { /// Documents with a Fill & Sign signature placed since their last save, asked about on /// saving (#2149). Not part of the recovery data: a recovered document isn't asked. pub(crate) placed_signatures: std::collections::HashSet, - /// A save waiting behind [`Dialog::LockSignatures`], and its Don't ask again box. + /// A save waiting behind the Lock signatures question. pub(crate) pending_lock: Option, /// The document whose lock question was just answered: the save that follows the answer /// doesn't ask again. The placed-signature mark itself stays until that save succeeds, so a /// save that fails or is cancelled asks again next time. pub(crate) lock_answered: Option, - pub(crate) lock_remember: bool, /// Point size for new Fill & Sign text and dates, kept across launches. pub fill_text_size: f64, pub fill_tool: fill_sign::FillTool, @@ -430,9 +337,11 @@ pub struct PdfCraftApp { /// The border new Fill & Sign text starts each launch with, kept across launches: what Make /// Current Properties Default last took from typed text (none at first). pub fill_text_default: fill_sign::TextBorder, - pub dialog: Option, - /// How to ask for the latest release (the desktop app sets it; see `updates`). - pub(crate) updates: updates::Updates, + /// The update check, its prompt and the self-update. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) updater: craft::update::updater::Updater, + /// The desktop app asks for a newer release once it has started (Preferences permitting). + pub(crate) startup_check: bool, /// Lists the Print dialog's printers in the background (the desktop app sets it; see /// [`PrinterSource`]). pub printer_source: Option, @@ -451,7 +360,6 @@ pub struct PdfCraftApp { #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) print_tasks: print_ui::PrintTasks, pub palette_open: bool, - pub palette_query: String, pub all_tools_expanded: bool, /// The All tools view fills the workspace (its sidebar's expand button). pub all_tools_full: bool, @@ -462,6 +370,10 @@ pub struct PdfCraftApp { pub recent: Vec, /// How many recent files to keep, 0 for no list (Preferences ▸ Documents and view, #5572). pub recent_limit: usize, + /// Home's recent files as cards or as a list. + pub recent_view: craft::ui::shell::RecentView, + /// Home's recent files' order. + pub recent_sort: craft::ui::shell::RecentSort, /// Preferences: reopen the files that were open when PdfCraft last closed (#442). pub reopen_last_session: bool, /// Restore last view settings when reopening documents (Preferences ▸ Documents and view; @@ -471,9 +383,9 @@ pub struct PdfCraftApp { pub last_views: Vec, /// The files open when PdfCraft last closed, read from the settings for /// [`PdfCraftApp::reopen_last_files`]. - pub last_session: last_session::LastSession, - /// Quitting closes unsaved tabs one by one: what was open when the quit began. - quit_session: Option, + pub last_session: craft::platform::session::Session, + /// What a quit that closes unsaved tabs one by one began with. + session_keeper: craft::platform::session::SessionKeeper, /// Preferences: reload a document when its file changes on disk (#431). pub reload_changed_files: bool, /// Preferences: ask for a newer release when the desktop app starts (#5737). Off, the app @@ -490,125 +402,73 @@ pub struct PdfCraftApp { pub always_default_view: bool, /// Open documents' files, watched for changes on disk. #[cfg(not(target_arch = "wasm32"))] - pub(crate) watch: file_watch::FileWatch, - /// One native worker prepares opened documents without owning app or session state. + pub(crate) watch: craft::platform::watch::FileWatch, + // PLAN: assumed Option, the document whose changed file waits to be reloaded (pdf-shell-w14). + /// A document whose changed file waits to be reloaded. #[cfg(not(target_arch = "wasm32"))] - open_worker: Option, + pub(crate) reload_request: Option, + /// Opened files read and prepared off the UI thread, by open token. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) opens: Queue, #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec, - /// Files waiting for room in the worker's bounded queue, in the order they were named. - #[cfg(not(target_arch = "wasm32"))] - deferred_opens: std::collections::VecDeque, /// The open retrying a closed password prompt's file with its password: replies behind it /// wait for it. #[cfg(not(target_arch = "wasm32"))] password_retry: Option, + /// Named destinations being looked up off the UI thread: reading a large document's name tree + /// takes a noticeable moment. #[cfg(not(target_arch = "wasm32"))] - pending_destinations: Vec, + pub(crate) named_destinations: Queue<(DocId, String), Option<(usize, pdfcraft_render::DestView)>>, #[cfg(not(target_arch = "wasm32"))] next_open_token: u64, /// Explicit CLI layout waits for flagged launch opens, never targeting restored tabs. #[cfg(not(target_arch = "wasm32"))] - launch_layout: Option<(canvas::PageLayout, bool)>, + launch_layout: Option, #[cfg(not(target_arch = "wasm32"))] launch_display_target: Option, - #[cfg(all(test, not(target_arch = "wasm32")))] - open_prepare_gate: Option>, + // PLAN: assumed HashMap and editing::save::{SaveFlow, PendingSave} (pdf-shell-w14). + /// The file picks asked of the host's file service, by ticket, with what each is for. + pub(crate) picks: std::collections::HashMap, + /// Where a save that asks first (Save As, a replace question) stands. + pub(crate) save_flow: editing::save::SaveFlow, + /// A save waiting for the answer to a question it asked. + pub(crate) pending_save: Option, /// Folders pinned to Home, and what they held when last listed. pub pinned: folders_ui::PinnedFolders, + /// The pinned folders being listed off the UI thread. + pub(crate) pinned_jobs: Queue<(), Vec>, /// The recent files restored from settings, checked off the UI thread (#5682). recent_check: persist::recent_check::RecentCheck, - /// Failures of the Reveal worker, taken each frame and shown as a notification. - #[cfg(not(target_arch = "wasm32"))] - reveal_errors: std::sync::Arc>>, /// Tools pinned to Home, in user-defined order. pub pinned_tools: Vec, - /// Search query for the Pin a tool selection dialog. - pub pin_tool_search: String, - pub toast: Option<(String, f64)>, - /// The form script message the toast shows now, if it shows one: drawn with its title and - /// icon (#4293). - pub toast_script: Option, - /// Form script messages waiting for the toast, in the order the scripts showed them: each - /// takes the toast when the one before it is gone, so every one is seen (#4294). + /// Form script messages waiting for a notice, in the order the scripts showed them, so every + /// one is seen (#4294). pub script_messages: std::collections::VecDeque, - /// Form script messages the waiting queue had no room for, since the toast last said how many. + /// Form script messages the waiting queue had no room for, since a notice last said how many. pub script_messages_dropped: u64, - /// The left-out count the toast is saying now ([`Self::next_script_message`]): put back to be - /// said again if another notice replaces the toast before it has been shown its time. - pub toast_dropped: u64, - /// Whether the macOS title bar is drawn by us (traffic lights over our tab strip). - pub integrated_titlebar: bool, - /// Set when the desktop leaves the window frame to the app (GNOME on Wayland): the tab strip - /// carries these window buttons and the window's edges resize it. - pub window_controls: Option, - /// Preferences ▸ Use system title bar: where `window_controls` is set, give the window back - /// winit's frame instead of drawing the header bar (#1001). - pub system_title_bar: bool, - /// Whether the window currently has the app's header bar (`None` until the first frame). - app_frame_shown: Option, + /// The form script message a notice shows now, drawn with its title and icon (#4293). + pub(crate) script_shown: Option, + /// The notices posted since the last pass, which `notices::show` hands to the toast service. + pub(crate) posted_notices: Vec, + /// The progress card of each background job that shows one. + pub(crate) progress_cards: std::collections::HashMap, pub password_prompt: Option, - /// Copy of a whole document's text (#2639) whose pages are being read off the UI thread. - document_copy: Option, + /// Whole-document text copies (#2639) reading their pages off the UI thread. + pub(crate) text_copies: Queue, pub unlock_prompt: Option, - pub full_screen: bool, - /// Files delivered asynchronously (web drag-and-drop, web file picker). - pub inbox: Inbox, - /// The browser's startup `?file=` download. Unlike a deliberate Open or drop, a late - /// arrival opens in the background once the user has started working (#171). - pub startup_inbox: Inbox, - startup_superseded: bool, - /// Asynchronous opens that failed (web `?file=` fetches), shown as a notice. - pub failed_inbox: FailedInbox, - /// Mirrors "some document has unsaved work, or an OCR review is open" each frame, so the web page's `beforeunload` handler can read it (#812). - pub unsaved_flag: std::sync::Arc, - /// Requests from the operating system, polled every frame (macOS Apple events). - pub os_events: Option, - /// Save delivers to the embedding page instead of downloading (web, see [`HostSaveFn`]). - pub host_save: Option, + /// Standard, full screen with the menu bar, or full screen. + pub screen_mode: craft::ui::shell::ScreenMode, /// Reports unsaved work, or an open OCR review, to the embedding page (web, see [`HostDirtyFn`]). pub host_dirty: Option, - /// A pending "save changes?" question (closing a dirty tab or quitting). - pub close_request: Option, - /// The button of the "save changes?" question the keyboard has chosen; Save when it opens. - pub(crate) save_prompt_button: dialogs::PromptButton, - /// `attend_save_prompt` has seen the pending "save changes?" question. It is false again once - /// the question is answered, so the next document's question is told apart from it. - save_prompt_seen: bool, - /// The "save changes?" question asked for the user's attention and the request still stands - /// (see `attend_save_prompt`). - save_prompt_attention: bool, - /// A save waiting behind [`Dialog::OverwriteChanged`] (the web build has no files to check). - #[cfg(not(target_arch = "wasm32"))] - pub pending_overwrite: Option, - /// Save to this path instead of asking (tests and automation). - pub save_override: Option, - /// Document Properties ▸ Description fields being edited: (document, Title/Author/Subject/Keywords). - pub props_draft: Option<(DocId, [String; 4])>, - /// Attachment description being edited: (document, name-tree key, description). - pub attachment_description_draft: Option<(DocId, u64, String, String, String, bool)>, - /// Document Properties ▸ Initial View (and reading options) being edited. - pub view_draft: Option<(DocId, pdfcraft_engine::InitialView)>, - /// Document Properties ▸ Custom being edited. - pub custom_draft: Option<(DocId, CustomDraft)>, + /// The "save changes?" questions of a closing tab or a quit, asked one document at a time. + pub(crate) close_guard: Option>, /// Original values and document revision for the editable Properties tabs. pub(crate) props_session: Option, - /// Files picked asynchronously for combine / insert (web). - pub requests: files::Requests, - /// Native file pickers in flight (they never block the frame; see `pickers`). - #[cfg(not(target_arch = "wasm32"))] - pickers: pickers::Pickers, - /// Pick these files instead of showing a picker (tests and automation). - #[cfg(not(target_arch = "wasm32"))] - pub pick_override: Option>, - /// Write exported files (split) here instead of asking (tests and automation). - pub export_dir_override: Option, - /// Split dialog settings. - pub split_draft: SplitDraft, - pub extract_draft: ExtractDraft, - pub rotate_draft: RotateDraft, /// Summarize Comments: sort order. pub summary_sort: pdfcraft_engine::SummarySort, + /// The Summarize Comments dialog, while it is open. + pub(crate) summarize_dialog: Option, /// The signing dialogs' state. pub sign_draft: Option, /// A dynamic form's preSign step, run when signing a field began: the document and its undo @@ -617,13 +477,18 @@ pub struct PdfCraftApp { /// Digital ID files the user has created or added. pub digital_ids: Vec, /// Signatures panel: expanded entries (field names). - pub sig_expanded: Vec, + pub sig_open: craft::ui::list::OpenSet, /// Accessibility Checker: options, the last check, and rules skipped by hand. pub a11y_options: a11y_ui::A11yOptions, - /// Scan & OCR: the Recognize Text choices, the running job, and (tests) run it inline. + /// Scan & OCR: the Recognize Text choices and the running job. pub ocr_draft: ocr_ui::OcrDraft, pub ocr_run: Option, - pub ocr_batch: Option>>, + // PLAN: assumed workflows::JobCount, a batch's shared done/total count (pdf-workflows-w14, pdf-print-ocr-w6). + pub ocr_batch: Option>, + /// Pages being recognized, by document. + pub(crate) ocr_runs: Queue, String>>, + /// Recognize Text in Multiple Files: the batch's summary. + pub(crate) ocr_batches: Queue<(), String>, /// The web build's files being read in Web Workers (progress in `ocr_batch`). #[cfg(target_arch = "wasm32")] ocr_web_batch: Option, @@ -633,8 +498,8 @@ pub struct PdfCraftApp { ocr_web_waiting: Option, /// Scan & OCR ▸ Correct recognized text: the OCR Verify screen (its state, never persisted). pub ocr_verify: ocr_verify::OcrVerify, - /// Background jobs (OCR, actions, listing pinned folders) run inline instead (tests). - pub run_inline: bool, + /// The OCR Verify screen's runs and re-reads. + pub(crate) verify_jobs: Queue, /// Frames in a row whose logic or drawing panicked, and whether this frame's did /// (`frame_guard`, #3914). panicking_frames: u32, @@ -645,36 +510,36 @@ pub struct PdfCraftApp { /// Tests: the part of the next frame that panics on purpose. #[cfg(test)] panic_next: Option, - /// Action Wizard: the user's actions, the dialog state, the running action and (tests) the - /// files to use instead of a picker. + /// Action Wizard: the user's actions and the running action. pub custom_actions: Vec, - pub wizard: actions_ui::Wizard, - pub action_run: Option>>, - pub action_files_override: Option>, - /// Standards ▸ PDF/A: level and last result. + pub action_run: Option>, + // PLAN: assumed the queue aliases actions_ui::ActionJobs, export_ui::ExportJobs, optimize_ui::{OptimizeJobs, SpaceAuditJobs} (pdf-workflows-w14). + pub(crate) action_jobs: actions_ui::ActionJobs, + /// Standards ▸ PDF/A: the level. pub pdfa: standards_ui::PdfaState, /// Compare files: the chosen older document and the last result. pub compare_old: Option, /// The Compare Files dialog's Pages field: the new file's pages to compare, empty for all. pub compare_pages: String, pub compare: Option, - /// The JavaScript console and the Document JavaScripts draft. + /// The JavaScript console. pub js_console: js_ui::JsConsole, #[cfg(not(target_arch = "wasm32"))] pub(crate) script_pending: Option, - pub doc_js: js_ui::DocJsDraft, + /// The JavaScript dialog open (the console, the document's scripts), if any. + pub js_dialog: Option, pub a11y: a11y_ui::A11yState, pub(crate) tags_state: tags_ui::State, /// Rules skipped by hand, for the document they were skipped in. pub a11y_skipped: std::collections::HashSet<(DocId, pdfcraft_engine::a11y::Rule)>, - pub alt_draft: a11y_ui::AltDraft, /// List the OS key store's signing identities among the digital IDs (the desktop app). pub os_key_store_ids: bool, pub cert_viewer: Option, - /// The last space audit. - pub space_audit: Vec, + /// The last space audit, written by its job and read by the dialog. + pub space_audit: std::sync::Arc>>, /// The document and edit generation `space_audit` was measured from. pub(crate) space_audit_of: Option<(DocId, u64)>, + pub(crate) space_audit_jobs: optimize_ui::SpaceAuditJobs, /// Combine files: the files staged so far. pub combine_draft: Vec, /// The combine list's field-name conflict preview (computed once per list, never saved). @@ -682,31 +547,27 @@ pub struct PdfCraftApp { /// The Combine files tab: whether it is open, shown, its selection and undo history. pub combine_tab: combine_ui::CombineTab, /// The Combine files table's column order and widths (kept in the settings). - pub combine_columns: combine_ui::Columns, + pub combine_columns: craft::ui::contract::collection::ColumnLayout, /// Combine files as thumbnails or as the table (kept in the settings). pub combine_view: combine_ui::CombineView, - /// How large the Combine grid draws its cards (1.0 = the usual; kept in the settings). Set - /// with [`PdfCraftApp::set_combine_zoom`]. - pub combine_zoom: f32, + /// How large the Combine grid draws its cards (1.0 = the usual; kept in the settings). + pub combine_zoom: f64, /// How large Organize pages draws its grid, for every document (1.0 = the usual; kept in /// the settings). - pub organize_zoom: f32, - /// The Combine grid's thumbnails: rendered off the UI thread, a few at a time. - pub(crate) combine_thumbs: combine_grid::Thumbs, + pub organize_zoom: f64, /// Images waiting for the resolution choice (released on cancel). pub image_import: Option, - /// The custom stamp library, and the stamp being created. + /// The custom stamp library. pub custom_stamps: Vec, - pub stamp_draft: stamps_ui::StampDraft, - /// PDF Optimizer choices. - pub optimize_draft: OptimizeDraft, + /// Create custom stamp, while it is open. + pub(crate) stamp_dialog: Option, /// The running optimization (Optimize PDF ▸ Advanced optimization). pub optimize_run: Option, + pub(crate) optimize_jobs: optimize_ui::OptimizeJobs, /// Scan & OCR ▸ Enhance scanned file: the dialog's choices and the running clean-up. pub scan_clean_draft: scan_clean_ui::ScanCleanDraft, pub scan_clean_run: Option, - /// A background job's progress card (see [`widgets::progress_notice`]). - pub progress_notice: Option, + pub(crate) scan_cleans: Queue>, /// Pages copied or cut in Organize Pages, ready to paste (into any document). pub page_clipboard: Option, /// Copied comments (XFDF), to paste into this or another document (M14). @@ -715,94 +576,55 @@ pub struct PdfCraftApp { pub object_clipboard: Option, /// What copying them put on the system clipboard (see [`app::ObjectClipMark`]). pub(crate) object_clip_mark: app::ObjectClipMark, - /// Files dropped on the page grid, waiting for the pointer to say which gap they go to. - grid_drop: Option, - /// The last snapshot (width, height, RGBA); `system_clipboard` also puts it on the - /// system clipboard (tests turn that off). + /// The last snapshot (width, height, RGBA), also put on the clipboard. pub last_snapshot: Option<(u32, u32, pdfcraft_render::Pixels)>, /// What `last_snapshot` was taken of: (document, page, rectangle in page view points). last_snapshot_of: Option<(DocId, usize, [f32; 4])>, /// The last image copied with Copy Image (width, height, straight RGBA), also put on the - /// system clipboard when `system_clipboard` is on. + /// clipboard. pub last_copied_image: Option<(u32, u32, Vec)>, /// The last image copied in its original format (file name, bytes), also put on the - /// system clipboard as a file when `system_clipboard` is on. + /// clipboard as a file. pub last_copied_file: Option<(String, Vec)>, - pub system_clipboard: bool, - /// Where Copy with formatting puts its HTML and the plain alternative instead of the system - /// clipboard, when `system_clipboard` is on (tests). - pub html_clipboard_override: Option, - /// The system clipboard Copy with formatting writes to, kept open so that X11 goes on - /// serving the copy after the frame. - #[cfg(not(target_arch = "wasm32"))] - os_clipboard: Option, - /// What ⌘V reads instead of the system clipboard (tests). - pub clipboard_override: Option, - /// Attach file: the file to attach instead of asking (tests, automation). - pub attach_override: Option<(String, Vec)>, - /// Duplicate Field: which field and onto which pages. - pub duplicate_draft: Option, - /// Page Properties: which pages, and the tab order chosen for them. + /// The clipboard every copy and paste goes through. + pub(crate) clipboard: craft::platform::clipboard::Clipboard, + /// Page Properties: which pages, and the tab order they have. pub page_props_draft: Option, - /// Text field table: the table being set up, and the page it goes on. - pub field_table_draft: Option, /// Prepare a form ▸ Preview: fill the form instead of editing its fields. pub form_preview: bool, /// Where autosaves go (`None`: autosave off, e.g. on the web and in tests). - pub recovery: Option, - /// Entries left by a previous session, offered in the Recovery dialog. - pub recoverable: Vec, - recovery_keys: std::collections::HashMap, + pub(crate) recovery: Option>, + /// Copies an earlier run left, offered for recovery. + pub(crate) recovered: Vec, + /// When each document is due for its next autosave. + pub(crate) autosave: craft::platform::autosave::Autosave, /// Recovered documents whose path came from a recovery sidecar and no save has confirmed /// yet: their first Save asks where, starting at that path, instead of writing it (#3923). recovered_paths: std::collections::HashSet, - last_autosave: Option, - allow_quit: bool, - /// Shortcuts pressed while a text field had the keyboard, run on the next frame (see - /// `registry_shortcuts`). - deferred_commands: Vec<(&'static str, Option)>, /// The native menu bar (macOS), while it is installed; the in-window bar shows otherwise. - pub(crate) native_menu: Option, - /// Input a menu click stands for (⌘C, Delete…), waiting to join a pass's input (see - /// `release_menu_input`). - pub(crate) menu_input: Vec, - /// Edit ▸ Paste clicks waiting to ask the platform for the clipboard (see - /// `release_menu_input`). - pub(crate) menu_pastes: usize, - /// This frame's keys as the pages see them: none while something is over them. - pub(crate) page_keys: page_keys::PageKeys, - /// The dialog seen at the last check, and a counter bumped whenever it changes (see - /// [`Self::dialog_epoch`]). - dialog_seen: Option, - dialog_epoch: u64, - /// The egui context, for commands that change window or theme state. - ctx: Option, - /// The window's size and place kept across a minimized close (desktop). - #[cfg(not(target_arch = "wasm32"))] - pub window_state: window_state::WindowState, - styled: bool, + pub(crate) native_menu: Option, fonts_ready: bool, - /// The CJK fallback order the installed fonts follow (see `theme::installed_font_definitions`). - fonts_cjk: theme::CjkPreference, /// The window title last sent to the platform. pub window_title: String, /// The web page's title last set: the window title, but always with the file's name. pub page_title: String, /// The UI control channel, when enabled (`--control`; off by default). - control: Option, + control: Option, + /// The control server, while it listens (the desktop app's `--control`). + control_server: Option, + /// Changes whenever what injected input aims at changes, so the control channel withdraws + /// input aimed at what was there before. + pub(crate) control_epoch: u64, /// A bookmark being renamed in the Bookmarks panel: (path, text so far). pub bookmark_rename: Option<(Vec, String)>, /// Bookmarks copied or cut in the Bookmarks panel, with their subtrees, ready to paste into /// any document. Destinations are page indices. pub bookmark_clipboard: Option>, - /// Number pages dialog settings (1-based pages). - pub number_draft: NumberDraft, - pub(crate) word_count_draft: word_count_ui::Draft, + /// Word Count's options, kept between showings. + pub(crate) word_count_options: word_count_ui::WordCountOptions, pub printer_marks_draft: printer_marks_ui::PrinterMarksDraft, pub convert_colours_draft: convert_colours_ui::ConvertColoursDraft, pub hairlines_draft: hairlines_ui::HairlinesDraft, - /// Protect Using Password dialog state. - pub protect_draft: protect::ProtectDraft, /// New bookmarks from text styles dialog state (#1693). pub text_style_draft: bookmark_styles_ui::TextStyleDraft, /// Set Page Boxes dialog state. @@ -810,52 +632,51 @@ pub struct PdfCraftApp { /// Header & footer / watermark / background dialog state. pub marks_draft: marks_ui::MarksDraft, /// The Update dialogs' preview page without the marks they replace. - pub(crate) unmarked_page: marks_ui::UnmarkedPage, + pub(crate) marks_preview: Option, + /// An attachment's Edit description dialog, and what it was opened for. + pub(crate) attachment_description: Option<(craft::ui::dialog::DialogId, dialogs::attachment_description::AttachmentOpen)>, /// Export dialog settings. pub export_draft: export_ui::ExportDraft, /// A running export's progress. - export_status: Option, - /// The saved Fill & Sign signature and initials (drawn or typed). - pub signature: Option, - pub initials: Option, - /// The Create signature / initials dialog, and its typed preview. - pub signature_draft: fill_sign::SigDraft, - pub(crate) signature_preview: Option<(fill_sign::SavedSig, egui::TextureHandle)>, - /// The Scan tab's photo, keyed by its version. - pub(crate) signature_photo: Option<(u64, egui::TextureHandle)>, - pub(crate) saved_signature_previews: [Option<(fill_sign::SavedSig, egui::TextureHandle)>; 2], - /// What visible digital signatures show on their left, and its preview in Sign as. + export_status: Option>, + pub(crate) export_jobs: export_ui::ExportJobs, + /// The saved Fill & Sign signature and initials (drawn, typed or an image). + pub signature: Option, + pub initials: Option, + /// What visible digital signatures show on their left. pub sign_graphic: sign_ui::SignGraphic, - pub(crate) sign_graphic_preview: Option<(fill_sign::SavedSig, egui::TextureHandle)>, - #[cfg(target_arch = "wasm32")] - pub(crate) signature_images: fill_sign::ImageInbox, - /// The Comment Properties dialog's state. - pub comment_props: Option, - pub field_props: Option, - pub bulk_field_props: Option, + /// The Comment Properties dialog, while it is open. + pub comment_props: Option, pub redact_prefs: RedactPrefs, /// The Redaction Tool Properties kept for the next run (what the last OK with "Make - /// properties default" ticked left), and the values before the dialog opened, for Cancel. + /// properties default" ticked left). pub redact_defaults: RedactPrefs, - pub redact_before: Option, - pub redact_pages_draft: RedactPagesDraft, + /// Redaction Tool Properties, while it is open: the values before it opened, for Cancel. + pub(crate) redact_props: Option, pub redact_search: RedactSearchDraft, - pub hidden_draft: HiddenDraft, + /// Find text to redact, while it is open. + pub(crate) redact_search_open: bool, + /// Remove hidden information, while it is open. + pub hidden_draft: Option, pub print_draft: PrintDraft, - pub link_draft: Option, /// The style new text gets (Edit a PDF ▸ Format text). pub text_style: pdfcraft_engine::AddedText, - /// The Replace Pages dialog's state. - pub replace_draft: Option, + /// Edit a PDF shows its More tools. + pub(crate) edit_more: bool, + // PLAN: assumed files::{ReplaceSource, InstalledFonts, FontFile} (pdf-workflows-w13). + /// The file Replace pages takes its pages from, once picked. + pub(crate) replace_source: Option>, + /// The fonts installed on this machine, for Add text and font embedding (desktop). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) document_fonts: Option, + /// The installed fonts being listed off the UI thread. + pub(crate) font_scan: Queue<(), Vec>, /// The last web link the app asked the system to open (tests and automation). pub last_opened_url: Option, /// The home screen's community card was closed; it comes back next launch (not remembered). pub community_card_closed: bool, /// A document asked to open this address; the user hasn't answered yet (#90, #91). pub pending_link: Option, - /// A document just opened asks to be shown in Full Screen mode (`/PageMode /FullScreen`): - /// the person is asked first, as in Acrobat, and this is the document waiting for the answer. - pub pending_full_screen: Option, /// A document just opened asks for its window to fit its first page or to be centred /// (`FitWindow`, `CenterWindow`): done once the page is laid out. pub pending_window: Option, diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8d524ad85b..2d3e7c868e 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -95,153 +95,15 @@ pub enum QuickTool { ColumnSelect, } -/// A file dropped on a page grid: its name, and its bytes or, for a file on disk, the path they are -/// read from when the file's turn to be inserted comes (so a long drop holds one file at a time). -pub(crate) type GridFile = (String, Result, std::path::PathBuf>); - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Dialog { - WordCount, - CreateImages, - Properties(PropsTab), - About, - Shortcuts, - Split, - /// Pages ▸ Number pages… (page labels). - NumberPages, - /// Print production ▸ Add printer marks. - PrinterMarks, - /// Print production ▸ Convert colours. - ConvertColours, - /// Print production ▸ Fix hairlines. - FixHairlines, - /// Organize pages ▸ Page properties (the tab order of the selected pages). - PageProps, - /// Protect Using Password. - Protect, - /// Bookmarks ▸ New bookmarks from text styles (#1693). - BookmarksFromTextStyles, - /// Set Page Boxes (crop, trim, bleed, art, media). - PageBoxes, - /// Add / Update Header and Footer, Watermark, Background. - Marks(pdfcraft_engine::MarkKind), - /// Export a PDF ▸ Image / Text. - Export(export_ui::ExportKind), - /// Fill & Sign ▸ Create signature (the drawing pad). - Signature, - /// Comment Properties. - CommentProps, - /// Edit the description of an embedded document attachment. - AttachmentDescription, - /// Replace Pages (after choosing the file). - ReplacePages, - /// Prepare a form ▸ Field Properties. - FieldProps, - /// Shared properties of several selected form fields. - BulkFieldProps, - /// Redact a PDF ▸ Redact pages, Find text and redact, Set properties, apply confirmation. - RedactPages, - RedactSearch, - RedactProps, - RedactApply, - /// File ▸ Print. - Print, - /// File ▸ Revert confirmation. - Revert, - /// Save over a file that changed on disk since the document came from it (#2166). - OverwriteChanged, - /// Saving a document with a signature just placed by Fill & Sign: lock it into the page - /// first? (#2149) - LockSignatures, - /// Link Properties. - LinkProps, - /// Organize ▸ Extract (options), Rotate Pages. - Extract, - RotatePages, - /// Remove Hidden Information and Sanitize Document. - RemoveHidden, - Sanitize, - /// Documents from a session that ended unexpectedly. - Recovery, - /// Comments ▸ Summarize comments (options). - SummarizeComments, - /// Sign with a Digital ID ▸ Configure ▸ Sign as. - Sign, - /// Optimize PDF ▸ Advanced optimization. - Optimize, - /// Prepare a form ▸ right-click a field ▸ Duplicate. - DuplicateField, - /// Prepare a form ▸ Text field table: a movable window rather than a modal (`field_table_ui`). - FieldTable, - /// Check for accessibility ▸ Accessibility Checker Options. - AccessibilityOptions, - /// Scan & OCR ▸ Recognize text. - RecognizeText, - /// Scan & OCR ▸ Enhance scanned file. - EnhanceScan, - /// The JavaScript console (⌘J). - JsConsole, - /// Document JavaScripts. - DocumentJs, - /// Preferences. - Preferences, - /// Compare files: choose the older version. - CompareFiles, - /// Action Wizard. - ActionWizard, - /// Standards ▸ PDF/A. - PdfA, - /// Custom stamps ▸ Create. - CreateStamp, - /// Prepare for accessibility ▸ Add alternate text. - AltText, - /// PDF Optimizer ▸ Audit space usage (then back to the optimizer). - AuditSpace, - /// Signatures ▸ Show certificate. - CertificateViewer, - /// Pin tools to Home: selection modal. - PinTool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PropsTab { - Description, - InitialView, - Security, - Fonts, - Custom, - Advanced, - SpaceAudit, -} - -/// Document Properties ▸ Custom being edited: the properties as they will be after OK, in order, -/// and the Name and Value fields. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct CustomDraft { - pub props: Vec<(String, String)>, - pub name: String, - pub value: String, -} - -/// Duplicate Field: the field and the pages (all, or a range, 1-based). -#[derive(Clone, Debug, PartialEq)] -pub struct DuplicateDraft { - pub name: String, - pub all: bool, - pub from: usize, - pub to: usize, -} - /// Page Properties: the document and pages it applies to (0-based), the document's edit /// generation when the dialog opened, and the pages' tab order as they have it (`None` when they -/// differ) and as chosen (`None` until one is chosen). +/// differ). The order chosen is the hosted dialog's value. #[derive(Clone, Debug, PartialEq)] pub struct PagePropsDraft { pub doc: DocId, pub generation: u64, pub pages: Vec, pub before: Option, - pub tab_order: Option, } /// Copied comments: their XFDF (each with its replies), for `Edit::PasteComments`. @@ -308,7 +170,7 @@ impl DocumentCopyJob { /// The document's text in page order, a page per line run. Each page read here is let go /// once its text is taken, so a large document never holds every page's text layer at once. /// `None` when `cancel` was set. - pub(crate) fn text(self, cancel: &std::sync::atomic::AtomicBool) -> Option { + pub(crate) fn text(self, cancel: &craft::host::queue::Cancel) -> Option { let mut renderer: Option = None; let mut out = String::new(); let mut push = |text: String| { @@ -326,7 +188,7 @@ impl DocumentCopyJob { None => t.text_of(0..t.glyphs.len()), }; for (page, p) in self.pages.into_iter().enumerate() { - if cancel.load(std::sync::atomic::Ordering::Relaxed) { + if cancel.is_cancelled() { return None; } match p { @@ -360,63 +222,53 @@ pub struct PasswordPrompt { pub path: Option, pub bytes: std::sync::Arc>, #[cfg(not(target_arch = "wasm32"))] - pub(crate) stamp: Option, - pub input: String, + pub(crate) stamp: Option, pub error: Option, /// A late startup file must stay in the background even after it is unlocked. pub(crate) activate: bool, /// The bytes are a recovery snapshot: once the document is open it takes the snapshot's /// path and recovery entry. Cancelling the prompt drops the association with it (#813). - pub(crate) recovered: Option, + pub(crate) recovered: Option, /// The tool that asked for this file (a tool chosen with no document open): it runs once /// the document is unlocked. pub(crate) then: Option<&'static str>, /// A link destination to apply after the linked PDF is unlocked. pub(crate) after_open: Option, /// A launch-time display override, applied only after this PDF is unlocked. - pub(crate) display_override: Option<(canvas::PageLayout, bool)>, -} - -impl Drop for PasswordPrompt { - fn drop(&mut self) { - zeroize::Zeroize::zeroize(&mut self.input); - } + pub(crate) display_override: Option, } #[cfg(not(target_arch = "wasm32"))] pub(crate) struct OpenRequest { pub(crate) name: String, pub(crate) path: Option, - pub(crate) stamp: Option, + pub(crate) stamp: Option, pub(crate) input: open_worker::Input, pub(crate) password: Option>, pub(crate) activate: bool, pub(crate) after_open: Option, - pub(crate) recovered: Option, + pub(crate) recovered: Option, pub(crate) then: Option<&'static str>, + /// Where the open waits in the worker's queue: a file the user named goes before files + /// reopened from the last session. + pub(crate) priority: craft::host::queue::Priority, } /// Asks for the permissions password of an open document whose security restricts it, which /// lifts the restrictions (#995). Acrobat asks for it when such a document's security is changed. +/// The typed password stays in the prompt's own field, never here. pub struct UnlockPrompt { pub doc: DocId, pub name: String, - pub input: String, pub error: Option, /// The command to run once unlocked (Protect using password, Remove security), if any. pub then: Option<&'static str>, } -impl Drop for UnlockPrompt { - fn drop(&mut self) { - zeroize::Zeroize::zeroize(&mut self.input); - } -} - impl UnlockPrompt { /// Ask for document `doc`'s permissions password, then run command `then`, if any. pub(crate) fn new(doc: &pdfcraft_engine::Document, then: Option<&'static str>) -> Self { - Self { doc: doc.id, name: doc.name.clone(), input: String::new(), error: None, then } + Self { doc: doc.id, name: doc.name.clone(), error: None, then } } } @@ -469,21 +321,11 @@ pub struct PendingRemoteLink { pub destination: pdfcraft_render::RemoteDestination, } -/// Settings for the Number pages dialog. -#[derive(Clone, Debug, PartialEq)] -pub struct NumberDraft { - pub from: usize, - pub to: usize, - pub style: pdfcraft_engine::LabelStyle, - pub prefix: String, - pub start: u32, -} - /// What [`PdfCraftApp::open_path`] did: opened the file in a new tab, focused the tab already /// 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 +/// through a notice; 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)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum OpenOutcome { /// The file opened in a new tab (or raised its password prompt). Opened, @@ -492,6 +334,7 @@ pub enum OpenOutcome { /// 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, + /// The file could not be read or opened; the user was told this text, which the control + /// reply carries too. + Failed(String), }