//! Background Save and Background Export (Preferences → File Handling): a save or an export encodes //! and writes a snapshot of the document on a worker thread while editing goes on. The status bar //! shows what is in progress; the result is applied on the UI thread when it arrives (a save marks //! the document saved as of its snapshot, so edits made meanwhile keep it modified). Exports and //! saves show in the progress window ([`crate::export_progress`]) with Cancel and Continue in //! Background. //! //! It needs a thread-safe writer from the host ([`crate::Services::write_shared`], desktop); //! without one (the web, which downloads) the work runs at once, as with the preference off. use std::collections::VecDeque; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::progress::Progress; use vectorcraft_engine::file_access::ScopeHandle; use crate::{VectorcraftApp, export_progress}; /// Writes a file; callable from any thread. pub type SharedWriteFn = std::sync::Arc Result<(), String> + Send + Sync>; /// Writes the file at a path with what the filler it is given writes into it (atomically, as /// `vectorcraft_format::write_atomic_with`); callable from any thread. pub type SharedStreamFn = std::sync::Arc std::io::Result<()>) -> Result<(), String> + Send + Sync>; /// A writer for the work: the host's file writer (or browser download) on the UI thread, the /// shared one on the worker. pub type Writer<'a> = &'a mut dyn FnMut(&str, &[u8]) -> Result<(), String>; /// Encodes and writes a snapshot (no access to the app) → the result handed to [`Then`]. type Work = Box Result + Send>; /// Applies a result on the UI thread (document state, status, recent files) → the command result. type Then = Box) -> Result>; /// A job's id and the work's result, back from the worker. type Done = (u64, Result); /// Work waiting on a [`Lane`]. type Task = Box; /// What a [`Lane`] shares with the job that drains it. #[derive(Default)] struct LaneState { queue: VecDeque, /// A drain job was spawned and has not found the queue empty yet. running: bool, } /// Work that runs one task at a time in the order it was pushed, on one job of the host's /// [`craft::host::Jobs`]. `Jobs::spawn` runs jobs side by side and a `JobQueue` runs the newest /// first among equals, but a save's result is applied in start order and a batch of large /// pictures is decoded in turn. #[derive(Default)] pub(crate) struct Lane { state: Arc>, } impl Lane { /// Queues `task`; when no job drains the lane, spawns one named `name`. pub(crate) fn push(&self, jobs: &dyn craft::host::Jobs, name: &'static str, task: Task) { let spawn = { let Ok(mut state) = self.state.lock() else { return }; state.queue.push_back(task); !std::mem::replace(&mut state.running, true) }; if spawn { let state = self.state.clone(); jobs.spawn(name, Box::new(move || drain(&state))); } } } /// Runs the lane's tasks until none is left; the lock is not held while one runs, so a task may push /// another and an inline `Jobs` may run this inside `push`. fn drain(state: &Mutex) { loop { let task = { let Ok(mut state) = state.lock() else { return }; match state.queue.pop_front() { Some(task) => task, None => { state.running = false; return; } } }; task(); } } /// What a job that shows in the progress window does: its Cancel and Continue in Background act on /// the jobs of its kind. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { /// An export (Background Export): `file.cancelExport`, `file.exportInBackground`. Export, /// A save (Background Save): `file.cancelSave`, `file.saveInBackground`. Save, } /// A job in progress. pub struct Job { id: u64, /// What the job does, for the progress window and its commands. pub kind: Kind, /// What the status bar and `ui.inspect` show ("Saving Poster.vectorcraft"); empty for work they /// don't show. pub label: String, /// The document the job reads (`DocState::uid`), if any. pub doc: Option, /// How far an export or a save has got, and its Cancel ([`crate::export_progress`] shows it). pub progress: Option>, /// Continue in Background: the progress dialog no longer shows this job. pub hidden: bool, /// [`export_progress::now`] when the job started, which the progress window waits /// [`export_progress::DELAY`] from. pub(crate) started: f64, /// [`crate::state::UiState::status_sets`] before the job set its status line. sets: u64, /// The status line the job set ("