mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-26 04:58:07 +00:00
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)
This commit is contained in:
@@ -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"] }
|
||||
|
||||
@@ -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=<url>` 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<std::sync::atomic::AtomicBool>) {
|
||||
use eframe::wasm_bindgen::{JsCast, closure::Closure};
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let handler = Closure::<dyn FnMut(web_sys::Event)>::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<String> {
|
||||
let search = web_sys::window()?.location().search().ok()?;
|
||||
@@ -143,14 +131,16 @@ fn app_canvas() -> Option<web_sys::HtmlCanvasElement> {
|
||||
/// 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()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+130
-233
@@ -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 <file>` enables the UI control channel (off by default): the app listens on a random
|
||||
//! loopback port and writes `{"port", "token", "pid"}` to `<file>` (owner-only permissions). The
|
||||
//! app doesn't start if it can't.
|
||||
//! Agents then drive it with `pdfcraft-cli ui --control <file> <method> …`.
|
||||
//! `--control <PORT>` enables the UI control channel (off by default): the app listens on
|
||||
//! 127.0.0.1:<PORT> (`0` picks a free one) and asks for the token `--control-token <TOKEN>` or
|
||||
//! `--control-token-file <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 <file> enable the UI control channel (pdfcraft-cli ui --control <file> …)
|
||||
--control <PORT> enable the UI control channel on 127.0.0.1:<PORT> (0: a free port)
|
||||
--control-token-file <FILE> the control channel's token, from FILE (or --control-token <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<PathBuf>} (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<std::path::PathBuf> {
|
||||
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<std::path::PathBuf> {
|
||||
/// 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::<Vec<_>>()) {
|
||||
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 <PORT>`, `--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<String>, token: Option<String>, token_file: Option<String>) -> Result<Option<(u16, String)>, 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!("{} <PORT>", 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 '{} <PORT>' needs '{} <TOKEN>' or '{} <FILE>' (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<String>,
|
||||
options: Vec<(String, String)>,
|
||||
control_file: Option<String>,
|
||||
/// 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<pdfcraft_ui_egui::window_controls::Layout>,
|
||||
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<pdfcraft_ui_egui::control::Endpoint>) -> 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<std::io::Result<()>> {
|
||||
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.
|
||||
///
|
||||
|
||||
@@ -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 }
|
||||
|
||||
+322
-487
File diff suppressed because it is too large
Load Diff
+16
-199
@@ -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<DocId> = 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<usize> = 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);
|
||||
}
|
||||
}
|
||||
|
||||
+196
-375
@@ -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<GridFile>,
|
||||
/// 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<String>,
|
||||
cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
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<K, R> = craft::host::queue::JobQueue<K, R>;
|
||||
|
||||
/// 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<open_worker::ResultMessage>,
|
||||
name: String,
|
||||
path: Option<String>,
|
||||
stamp: Option<file_watch::Stamp>,
|
||||
stamp: Option<craft::platform::watch::FileStamp>,
|
||||
activate: bool,
|
||||
after_open: Option<pdfcraft_render::RemoteDestination>,
|
||||
recovered: Option<RecoveryMeta>,
|
||||
recovered: Option<craft::platform::autosave::RecoveryEntry>,
|
||||
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<craft::pages::PageDisplay>,
|
||||
/// An answer taken from the queue and kept back for later (a password prompt waiting for an
|
||||
/// earlier file's password retry).
|
||||
ready: Option<open_worker::ResultKind>,
|
||||
}
|
||||
|
||||
/// 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<pdfcraft_render::RemoteDestination>,
|
||||
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<dyn FnMut(&str, &str) -> 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<Option<(usize, pdfcraft_render::DestView)>>,
|
||||
}
|
||||
|
||||
pub struct PdfCraftApp {
|
||||
/// The app's services: jobs, files, settings sections, commands. Every queue is built from it.
|
||||
pub(crate) host: std::sync::Arc<craft::host::Host>,
|
||||
/// 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<craft::dialogs::service::FilePanels>,
|
||||
// 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<settings::Store>,
|
||||
/// 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<dialogs::preferences::PreferencesSession>,
|
||||
/// Keyboard Shortcuts, while its window is open.
|
||||
pub(crate) shortcuts: Option<dialogs::shortcuts::ShortcutsSession>,
|
||||
/// 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<side_panels::PanelId>,
|
||||
/// 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<i18n::Lang>,
|
||||
@@ -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<String>,
|
||||
/// Explicit CLI/control mode lasts for this session and is never persisted.
|
||||
mode_override: Option<Mode>,
|
||||
pub left: LeftPanel,
|
||||
pub left_open: bool,
|
||||
pub right: Option<RightPanel>,
|
||||
/// 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<DocId>,
|
||||
/// 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<std::sync::atomic::AtomicUsize>,
|
||||
/// 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<Option<RightPanel>>,
|
||||
pub quick_tool: QuickTool,
|
||||
/// The tool to go back to when Space, held for a temporary Hand, is released.
|
||||
space_hand: Option<QuickTool>,
|
||||
/// The tool before full screen, given back on leaving it (see [`Self::apply_full_screen`]).
|
||||
full_screen_tool: Option<QuickTool>,
|
||||
/// 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<pdfcraft_platform::desktop_theme::DesktopTheme>,
|
||||
#[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<f32>,
|
||||
/// 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<f32>,
|
||||
/// 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<pdfcraft_engine::DocId>,
|
||||
/// 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<editing::PendingLock>,
|
||||
/// 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<pdfcraft_engine::DocId>,
|
||||
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<Dialog>,
|
||||
/// 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<PrinterSource>,
|
||||
@@ -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<RecentFile>,
|
||||
/// 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<last_view::LastView>,
|
||||
/// 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<last_session::LastSession>,
|
||||
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<DocId>,
|
||||
// PLAN: assumed Option<DocId>, 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<open_worker::OpenWorker>,
|
||||
pub(crate) reload_request: Option<DocId>,
|
||||
/// Opened files read and prepared off the UI thread, by open token.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) opens: Queue<u64, open_worker::ResultKind>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pending_opens: Vec<PendingOpen>,
|
||||
/// 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<DeferredOpen>,
|
||||
/// 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<u64>,
|
||||
/// 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<PendingDestination>,
|
||||
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<craft::pages::PageDisplay>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
launch_display_target: Option<DocId>,
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
open_prepare_gate: Option<std::sync::Arc<open_worker::PrepareGate>>,
|
||||
// PLAN: assumed HashMap<PickId, FilePurpose> 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<craft::host::PickId, FilePurpose>,
|
||||
/// 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<editing::save::PendingSave>,
|
||||
/// 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<folders_ui::FolderListing>>,
|
||||
/// 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<std::sync::Mutex<Vec<String>>>,
|
||||
/// Tools pinned to Home, in user-defined order.
|
||||
pub pinned_tools: Vec<String>,
|
||||
/// 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<pdfcraft_engine::js::Message>,
|
||||
/// 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<pdfcraft_engine::js::Message>,
|
||||
/// 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<window_controls::Layout>,
|
||||
/// 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<bool>,
|
||||
/// The form script message a notice shows now, drawn with its title and icon (#4293).
|
||||
pub(crate) script_shown: Option<js_ui::ScriptShown>,
|
||||
/// The notices posted since the last pass, which `notices::show` hands to the toast service.
|
||||
pub(crate) posted_notices: Vec<craft::ui::notices::PostedNotice>,
|
||||
/// The progress card of each background job that shows one.
|
||||
pub(crate) progress_cards: std::collections::HashMap<crate::notices::ProgressKey, craft::ui::runtime::toast::ToastId>,
|
||||
pub password_prompt: Option<PasswordPrompt>,
|
||||
/// Copy of a whole document's text (#2639) whose pages are being read off the UI thread.
|
||||
document_copy: Option<DocumentCopy>,
|
||||
/// Whole-document text copies (#2639) reading their pages off the UI thread.
|
||||
pub(crate) text_copies: Queue<DocId, String>,
|
||||
pub unlock_prompt: Option<UnlockPrompt>,
|
||||
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<std::sync::atomic::AtomicBool>,
|
||||
/// Requests from the operating system, polled every frame (macOS Apple events).
|
||||
pub os_events: Option<OsEventsFn>,
|
||||
/// Save delivers to the embedding page instead of downloading (web, see [`HostSaveFn`]).
|
||||
pub host_save: Option<HostSaveFn>,
|
||||
/// 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<HostDirtyFn>,
|
||||
/// A pending "save changes?" question (closing a dirty tab or quitting).
|
||||
pub close_request: Option<CloseRequest>,
|
||||
/// 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<editing::PendingOverwrite>,
|
||||
/// Save to this path instead of asking (tests and automation).
|
||||
pub save_override: Option<String>,
|
||||
/// 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<craft::quit::CloseGuard<DocId>>,
|
||||
/// Original values and document revision for the editable Properties tabs.
|
||||
pub(crate) props_session: Option<properties_session::Draft>,
|
||||
/// 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<Vec<String>>,
|
||||
/// Write exported files (split) here instead of asking (tests and automation).
|
||||
pub export_dir_override: Option<String>,
|
||||
/// 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<craft::ui::dialog::DialogId>,
|
||||
/// The signing dialogs' state.
|
||||
pub sign_draft: Option<SignDraft>,
|
||||
/// 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<DigitalIdEntry>,
|
||||
/// Signatures panel: expanded entries (field names).
|
||||
pub sig_expanded: Vec<String>,
|
||||
pub sig_open: craft::ui::list::OpenSet<String>,
|
||||
/// 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<ocr_ui::OcrRun>,
|
||||
pub ocr_batch: Option<std::sync::Arc<std::sync::Mutex<ocr_ui::BatchProgress>>>,
|
||||
// PLAN: assumed workflows::JobCount, a batch's shared done/total count (pdf-workflows-w14, pdf-print-ocr-w6).
|
||||
pub ocr_batch: Option<std::sync::Arc<workflows::JobCount>>,
|
||||
/// Pages being recognized, by document.
|
||||
pub(crate) ocr_runs: Queue<DocId, Result<Vec<pdfcraft_engine::ocr::OcrPage>, 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<ocr_web::Batch>,
|
||||
@@ -633,8 +498,8 @@ pub struct PdfCraftApp {
|
||||
ocr_web_waiting: Option<ocr_ui::WaitingFiles>,
|
||||
/// 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<ocr_verify::VerifyJob, ocr_verify::VerifyDone>,
|
||||
/// 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<frame_guard::FramePart>,
|
||||
/// 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<pdfcraft_engine::actions::Action>,
|
||||
pub wizard: actions_ui::Wizard,
|
||||
pub action_run: Option<std::sync::Arc<std::sync::Mutex<actions_ui::RunProgress>>>,
|
||||
pub action_files_override: Option<Vec<String>>,
|
||||
/// Standards ▸ PDF/A: level and last result.
|
||||
pub action_run: Option<std::sync::Arc<workflows::JobCount>>,
|
||||
// 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<DocId>,
|
||||
/// The Compare Files dialog's Pages field: the new file's pages to compare, empty for all.
|
||||
pub compare_pages: String,
|
||||
pub compare: Option<compare_ui::CompareState>,
|
||||
/// 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<script_dialog::Pending>,
|
||||
pub doc_js: js_ui::DocJsDraft,
|
||||
/// The JavaScript dialog open (the console, the document's scripts), if any.
|
||||
pub js_dialog: Option<js_dialogs::JsDialog>,
|
||||
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<sign_ui::CertViewer>,
|
||||
/// The last space audit.
|
||||
pub space_audit: Vec<pdfcraft_engine::optimize::SpaceUse>,
|
||||
/// The last space audit, written by its job and read by the dialog.
|
||||
pub space_audit: std::sync::Arc<std::sync::RwLock<Vec<pdfcraft_engine::optimize::SpaceUse>>>,
|
||||
/// 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<combine_ui::CombineFile>,
|
||||
/// 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<create_ui::ImageImport>,
|
||||
/// The custom stamp library, and the stamp being created.
|
||||
/// The custom stamp library.
|
||||
pub custom_stamps: Vec<stamps_ui::CustomStamp>,
|
||||
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<stamps_ui::CreateStampDialog>,
|
||||
/// The running optimization (Optimize PDF ▸ Advanced optimization).
|
||||
pub optimize_run: Option<optimize_ui::OptimizeRun>,
|
||||
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<scan_clean_ui::ScanCleanRun>,
|
||||
/// A background job's progress card (see [`widgets::progress_notice`]).
|
||||
pub progress_notice: Option<widgets::ProgressNotice>,
|
||||
pub(crate) scan_cleans: Queue<DocId, Result<scan_clean_ui::ScanCleaned, pdfcraft_engine::EditError>>,
|
||||
/// Pages copied or cut in Organize Pages, ready to paste (into any document).
|
||||
pub page_clipboard: Option<PageClip>,
|
||||
/// Copied comments (XFDF), to paste into this or another document (M14).
|
||||
@@ -715,94 +576,55 @@ pub struct PdfCraftApp {
|
||||
pub object_clipboard: Option<pdfcraft_engine::ObjectClipboard>,
|
||||
/// 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<GridDrop>,
|
||||
/// 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<u8>)>,
|
||||
/// 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<u8>)>,
|
||||
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<HtmlClipboard>,
|
||||
/// 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<arboard::Clipboard>,
|
||||
/// What ⌘V reads instead of the system clipboard (tests).
|
||||
pub clipboard_override: Option<create_ui::Clip>,
|
||||
/// Attach file: the file to attach instead of asking (tests, automation).
|
||||
pub attach_override: Option<(String, Vec<u8>)>,
|
||||
/// Duplicate Field: which field and onto which pages.
|
||||
pub duplicate_draft: Option<DuplicateDraft>,
|
||||
/// 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<PagePropsDraft>,
|
||||
/// Text field table: the table being set up, and the page it goes on.
|
||||
pub field_table_draft: Option<field_table_ui::FieldTableDraft>,
|
||||
/// 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<RecoveryStore>,
|
||||
/// Entries left by a previous session, offered in the Recovery dialog.
|
||||
pub recoverable: Vec<RecoveryMeta>,
|
||||
recovery_keys: std::collections::HashMap<DocId, String>,
|
||||
pub(crate) recovery: Option<std::sync::Arc<craft::platform::autosave::RecoveryStore>>,
|
||||
/// Copies an earlier run left, offered for recovery.
|
||||
pub(crate) recovered: Vec<craft::platform::autosave::RecoveryEntry>,
|
||||
/// 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<DocId>,
|
||||
last_autosave: Option<web_time::Instant>,
|
||||
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<DocId>)>,
|
||||
/// The native menu bar (macOS), while it is installed; the in-window bar shows otherwise.
|
||||
pub(crate) native_menu: Option<craft_menu::NativeMenu>,
|
||||
/// Input a menu click stands for (⌘C, Delete…), waiting to join a pass's input (see
|
||||
/// `release_menu_input`).
|
||||
pub(crate) menu_input: Vec<egui::Event>,
|
||||
/// 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>,
|
||||
dialog_epoch: u64,
|
||||
/// The egui context, for commands that change window or theme state.
|
||||
ctx: Option<egui::Context>,
|
||||
/// 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<craft::menu::NativeMenu>,
|
||||
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::Control>,
|
||||
control: Option<craft::automation::ControlChannel>,
|
||||
/// The control server, while it listens (the desktop app's `--control`).
|
||||
control_server: Option<craft::automation::server::Listening>,
|
||||
/// 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<usize>, 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<Vec<pdfcraft_engine::OutlineNode>>,
|
||||
/// 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<marks_ui::MarksPreview>,
|
||||
/// 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<export_ui::ExportStatus>,
|
||||
/// The saved Fill & Sign signature and initials (drawn or typed).
|
||||
pub signature: Option<fill_sign::SavedSig>,
|
||||
pub initials: Option<fill_sign::SavedSig>,
|
||||
/// 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<std::sync::Arc<workflows::JobCount>>,
|
||||
pub(crate) export_jobs: export_ui::ExportJobs,
|
||||
/// The saved Fill & Sign signature and initials (drawn, typed or an image).
|
||||
pub signature: Option<craft::review::SavedSignature>,
|
||||
pub initials: Option<craft::review::SavedSignature>,
|
||||
/// 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<comment_props::PropsDraft>,
|
||||
pub field_props: Option<prepare::FieldDraft>,
|
||||
pub bulk_field_props: Option<bulk_fields::Draft>,
|
||||
/// The Comment Properties dialog, while it is open.
|
||||
pub comment_props: Option<comment_props::CommentPropsDialog>,
|
||||
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<RedactPrefs>,
|
||||
pub redact_pages_draft: RedactPagesDraft,
|
||||
/// Redaction Tool Properties, while it is open: the values before it opened, for Cancel.
|
||||
pub(crate) redact_props: Option<RedactPrefs>,
|
||||
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<HiddenDraft>,
|
||||
pub print_draft: PrintDraft,
|
||||
pub link_draft: Option<LinkDraft>,
|
||||
/// 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<files::ReplaceDraft>,
|
||||
/// 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<std::sync::Arc<files::ReplaceSource>>,
|
||||
/// The fonts installed on this machine, for Add text and font embedding (desktop).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) document_fonts: Option<files::InstalledFonts>,
|
||||
/// The installed fonts being listed off the UI thread.
|
||||
pub(crate) font_scan: Queue<(), Vec<files::FontFile>>,
|
||||
/// The last web link the app asked the system to open (tests and automation).
|
||||
pub last_opened_url: Option<String>,
|
||||
/// 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<PendingLink>,
|
||||
/// 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<DocId>,
|
||||
/// 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<viewer_prefs::PendingWindow>,
|
||||
|
||||
+18
-175
@@ -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<Vec<u8>, 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<usize>,
|
||||
pub before: Option<pdfcraft_engine::TabOrder>,
|
||||
pub tab_order: Option<pdfcraft_engine::TabOrder>,
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
pub(crate) fn text(self, cancel: &craft::host::queue::Cancel) -> Option<String> {
|
||||
let mut renderer: Option<pdfcraft_render::PageRenderer> = 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<String>,
|
||||
pub bytes: std::sync::Arc<Vec<u8>>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) stamp: Option<file_watch::Stamp>,
|
||||
pub input: String,
|
||||
pub(crate) stamp: Option<craft::platform::watch::FileStamp>,
|
||||
pub error: Option<String>,
|
||||
/// 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<RecoveryMeta>,
|
||||
pub(crate) recovered: Option<craft::platform::autosave::RecoveryEntry>,
|
||||
/// 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<pdfcraft_render::RemoteDestination>,
|
||||
/// 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<craft::pages::PageDisplay>,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) struct OpenRequest {
|
||||
pub(crate) name: String,
|
||||
pub(crate) path: Option<String>,
|
||||
pub(crate) stamp: Option<file_watch::Stamp>,
|
||||
pub(crate) stamp: Option<craft::platform::watch::FileStamp>,
|
||||
pub(crate) input: open_worker::Input,
|
||||
pub(crate) password: Option<zeroize::Zeroizing<String>>,
|
||||
pub(crate) activate: bool,
|
||||
pub(crate) after_open: Option<pdfcraft_render::RemoteDestination>,
|
||||
pub(crate) recovered: Option<RecoveryMeta>,
|
||||
pub(crate) recovered: Option<craft::platform::autosave::RecoveryEntry>,
|
||||
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<String>,
|
||||
/// 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),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user