Files
vectorcraft/crates/ui-egui/src/opening.rs
T

261 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Opening documents off the UI thread (desktop): a file the user asks to open (File › Open, Open
//! Recent, the Home screen, files handed to the app) is decoded on a thread of its own, which also
//! reads its linked files and lays out its type, while the status bar shows it, and opens in a new tab
//! once it is ready, as it would at once: the same notes, recent files and errors. A file that takes
//! longer than [`crate::export_progress::DELAY`] shows a progress window ([`shown`]): its name, a bar that moves while it is
//! read (the reader counts no steps), Cancel (also Esc, `file.cancelOpen`: the file doesn't open)
//! and Continue in Background (`file.openInBackground`: it goes on, shown in the status bar). On
//! wasm (no threads) and in unit tests it opens at once ([`available`]).
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use serde_json::{Value, json};
use vectorcraft_engine::cancel::{self, CancelToken};
use vectorcraft_engine::cmd::fileio::{self, ReadFile};
use vectorcraft_engine::file_access::ScopeHandle;
use crate::VectorcraftApp;
use crate::export_progress::Shown;
/// A file being read.
pub struct Pending {
/// Where it is.
pub path: String,
/// What the status bar shows ("Opening Poster.vectorcraft").
pub label: String,
done: Receiver<Result<ReadFile, String>>,
/// The automation roots in force where the open started: the document is installed under
/// them too (its links are read as it opens).
scope: ScopeHandle,
/// Raised by Cancel, on the thread reading the file: an importer plug-in stops.
token: CancelToken,
/// Continue in Background: the progress window no longer shows it.
pub hidden: bool,
/// [`crate::export_progress::now`] when the read started.
pub(crate) started: f64,
}
/// The files being read.
#[derive(Default)]
pub struct Opening {
pub pending: Vec<Pending>,
/// Open documents asked for again while the active one couldn't change: their tabs come to
/// the front once it can ([`may_switch`]), each in the file access scope it was asked in.
pub activate: Vec<(String, ScopeHandle)>,
}
/// Is a long operation running that should show the busy cursor and status spinner (background
/// save/export with a label, a file opening or being read for Place off the UI thread, a heavy plug-in filter, or an
/// Image Trace)?
pub fn long_operation_busy(app: &VectorcraftApp) -> bool {
app.background.jobs.iter().any(|j| !j.label.is_empty() && !j.cancelled())
|| !app.opening.pending.is_empty()
|| !app.plugin_runs.running.is_empty()
|| !app.placing.pending.is_empty()
|| !app.trace_runs.running.is_empty()
|| crate::retype_runs::any_running(app)
}
/// Does opening happen off the UI thread here? Not on wasm (no threads), in unit tests (they look
/// at the document right after asking for it, unless one turns it on: [`tests::with_threads`]), or
/// with `VECTORCRAFT_SYNC_OPEN` set.
#[cfg(not(test))]
pub fn available() -> bool {
!(cfg!(target_arch = "wasm32") || std::env::var_os("VECTORCRAFT_SYNC_OPEN").is_some())
}
#[cfg(test)]
pub fn available() -> bool {
tests::threads_on()
}
/// Decode `bytes`, the file at `path`, read its linked files and lay out its type on a job of its
/// own ([`fileio::read_for_open`]) → `{background: true, status}`. A job that could not start
/// leaves the result channel closed, which [`poll`] reports.
pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>) -> Value {
start_with(app, path, bytes, Value::Null)
}
/// [`start`] with the `document.open` options in `params` (`importer` and its `params`).
pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>, params: Value) -> Value {
// A plug-in still loading may be the importer that reads the file.
app.session.finish_plugin_loads();
let (tx, done) = channel();
let name = path.to_string();
// Update Links (Preferences › File Handling) applies there as it is set now.
let update_links = app.session.prefs.update_links == "automatically";
let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps;
let open_params = app.session.prefs.with_pdf_font_choice(&params);
// The automation roots in force here are in force there.
let scope = ScopeHandle::capture();
let opener = scope.clone();
let token = CancelToken::new();
let raised = token.clone();
app.jobs().spawn(
"vectorcraft-open",
Box::new(move || {
let r = scope
.run(|| {
vectorcraft_engine::guard::catch_panic(|| {
cancel::scope(&raised, None, || {
// A profile question Edit › Color Settings asks waits for the UI thread.
fileio::read_for_open_asking(&name, &bytes, Some(name.clone()), &open_params, update_links, low_res_proxy_eps, true)
.map_err(|e| e.to_string())
})
})
})
.unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)")));
// The file's bytes go before the document is handed over.
drop(bytes);
// The app may have quit meanwhile: nothing to hand it to.
let _ = tx.send(r);
}),
);
track(app, path, done, opener, token)
}
/// Do the rest of the read of `file`, read for File › Open from `path` once its profile question
/// is answered or gone (its linked files and type, [`ReadFile::finish_read`]), on a job of its
/// own under `scope`; it then opens as a file read off the UI thread does → `{background: true,
/// status}`.
pub(crate) fn finish_answered(app: &mut VectorcraftApp, path: &str, file: ReadFile, scope: ScopeHandle) -> Value {
let (tx, done) = channel();
let run = scope.clone();
app.jobs().spawn(
"vectorcraft-open",
Box::new(move || {
let mut file = file;
let r = run
.run(|| vectorcraft_engine::guard::catch_panic(|| file.finish_read().map_err(|e| e.to_string())))
.unwrap_or_else(|msg| Err(format!("internal error: {msg} (please report this bug)")));
let r = r.map(|()| file);
// The app may have quit meanwhile: nothing to hand it to.
let _ = tx.send(r);
}),
);
track(app, path, done, scope, CancelToken::new())
}
/// Lists the file being read for `path` and tells the status bar → `{background: true, status}`.
fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, String>>, scope: ScopeHandle, token: CancelToken) -> Value {
let label = format!("Opening {}", fileio::file_name(path));
let started = crate::export_progress::now(app);
app.opening.pending.push(Pending { path: path.to_string(), label: label.clone(), done, scope, token, hidden: false, started });
let status = format!("{label}…");
app.status(status.clone());
json!({ "background": true, "status": status })
}
/// May the active document change now ([`poll`])?
pub(crate) fn may_switch(app: &VectorcraftApp) -> bool {
let s = &app.session;
!(app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) || s.in_interaction() || (s.tool_busy() && s.pointer_held()))
}
/// Open the files that are ready (each frame). Not while a dialog is open: a document that opens
/// becomes the active one, and the dialog's OK acts on the active document (#1694: Save As
/// options confirmed after another file had finished opening saved that file's art under the
/// first one's name). The files wait, their status line too, until the dialog is closed. Nor while
/// an interaction is open (a drag, a slider's preview, or a tool's preview between its clicks) or
/// a tool is busy with a drag of its own while the pointer button is held: a document that opens
/// cancels it. A tool that is busy while the button is not held and no interaction is open is
/// waiting between its clicks (the Dimension tool after its first point): the file opens, and the
/// tool starts afresh, as when the user switches documents.
pub fn poll(app: &mut VectorcraftApp) {
// One at a time: a document that opens again (closed meanwhile) may ask about its links or
// fonts, and the rest wait for that dialog too.
loop {
if !may_switch(app) {
return;
}
if app.opening.activate.is_empty() {
break;
}
let (path, scope) = app.opening.activate.remove(0);
// Closed meanwhile, it opens again; a failure is reported to the user there.
let _ = scope.run(|| crate::io::open_reporting(app, &path));
}
let mut i = 0;
while let Some(p) = app.opening.pending.get(i) {
let r = match p.done.try_recv() {
Ok(r) => r,
Err(TryRecvError::Empty) => {
i += 1;
continue;
}
Err(TryRecvError::Disconnected) => Err("the file stopped being read (please report this bug)".to_string()),
};
let p = app.opening.pending.remove(i);
// The status bar no longer says it is opening.
if app.ui.status == format!("{}…", p.label) {
app.ui.status.clear();
}
p.scope.run(|| finish(app, &p.path, r));
// A file that opened and asks about its links or fonts holds back the others too.
if !may_switch(app) {
return;
}
}
}
/// The progress window's Cancel: the files being read don't open. An importer plug-in stops
/// between two slices of its budget; a built-in reader finishes reading and the result is dropped
/// → `{cancelled: n}`.
pub fn cancel_all(app: &mut VectorcraftApp) -> Value {
let cancelled = std::mem::take(&mut app.opening.pending);
for p in &cancelled {
p.token.cancel();
// The status bar no longer says it is opening.
if app.ui.status == format!("{}…", p.label) {
app.ui.status.clear();
}
}
json!({ "cancelled": cancelled.len() })
}
/// The progress window's Continue in Background: the files go on being read, shown in the status
/// bar only → `{hidden: n}`.
pub fn hide_all(app: &mut VectorcraftApp) -> Value {
let mut n = 0;
for p in app.opening.pending.iter_mut().filter(|p| !p.hidden) {
p.hidden = true;
n += 1;
}
json!({ "hidden": n })
}
/// Is a file being read that the progress window shows?
pub fn any_shown(app: &VectorcraftApp) -> bool {
app.opening.pending.iter().any(|p| !p.hidden)
}
/// The progress window's entry for the first file being read it shows.
pub(crate) fn shown(app: &VectorcraftApp) -> Option<Shown> {
let waiting: Vec<&Pending> = app.opening.pending.iter().filter(|p| !p.hidden).collect();
let first = *waiting.first()?;
let more = waiting.len() - 1;
Some(Shown {
title: format!("{}…", crate::i18n::msg(&first.label)),
step: tl!("Reading the file…").to_string(),
fraction: None,
counts: None,
queued: (more > 0).then(|| crate::i18n::tn(more as u64, "{n} more file waiting", "{n} more files waiting").to_string()),
started: first.started,
cancel: "file.cancelOpen",
hide: Some("file.openInBackground"),
})
}
/// Open a file read off the UI thread, as [`crate::io::open_reporting`] opens one read at once,
/// after the profile question Edit › Color Settings asks about it, if any
/// ([`crate::dialogs::profile_mismatch::open_or_ask`]).
fn finish(app: &mut VectorcraftApp, path: &str, r: Result<ReadFile, String>) {
let opened = r.and_then(|file| crate::dialogs::profile_mismatch::open_or_ask(app, file, Some(path.to_string()), true));
if let Err(e) = opened {
crate::io::report_open_error(app, &fileio::file_name(path), &e);
}
}
#[cfg(test)]
pub(crate) mod tests;