diff --git a/Cargo.toml b/Cargo.toml index ada014ed0f..3405984f63 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,9 @@ craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bbe5b514a8 craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bbe5b514a8197c671a261339f297deecc4df881b" } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bbe5b514a8197c671a261339f297deecc4df881b" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "bbe5b514a8197c671a261339f297deecc4df881b", features = ["egui"] } +# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names +# the members it imports. +craft = { git = "https://github.com/storytold/craft-libs", rev = "bbe5b514a8197c671a261339f297deecc4df881b" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 3fbf039ec6..9052428f70 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -20,8 +20,25 @@ bundled-fonts = ["vectorcraft-engine/bundled-fonts"] interface-fonts = [] [dependencies] -craft-ui = { workspace = true } -craft-keymap = { workspace = true, features = ["egui"] } +craft = { workspace = true, features = [ + "ui", + "automation", + "color-ui", + "draw", + "font-catalog", + "font-catalog-system", + "font-manager", + "keymap", + "menu", + "pages", + "platform", + "platform-clipboard", + "print", + "settings", + "text", + "text-font-picker", + "window", +] } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } @@ -53,17 +70,12 @@ log = { workspace = true } # Floating panels open in OS windows of their own on the desktop; on the web they stay in the page. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-ui = { workspace = true, features = ["native-windows"] } -craft-update = { workspace = true } +# The folder picker and the updater are native only (`craft/Cargo.toml`: rfd and getrandom have no wasm build). +craft = { workspace = true, features = ["dialogs", "update"] } # The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in # Cargo.lock with the time-zone crates `clock` uses. chrono = { workspace = true, features = ["clock"] } -[target.'cfg(target_arch = "wasm32")'.dependencies] -# `now_ms` (src/lib.rs) reads the page's `performance.now()` with this crate in the web build. It is -# MIT OR Apache-2.0 and already in the build through eframe. -web-time = "1" - # The current user's id (`geteuid`): Preview in Browser uses its temporary folder only when that # user owns it (src/dialogs/save_for_web.rs). Already in Cargo.lock (tempfile), so this adds no # new crate. @@ -71,6 +83,8 @@ web-time = "1" rustix = { workspace = true, features = ["std", "process"] } [dev-dependencies] +# `Fixture` and the stories sit behind craft-ui's `testing` feature. +craft = { workspace = true, features = ["ui-testing"] } egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..3a07093079 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,50 +1,56 @@ +use craft::automation::ControlChannel; +use craft::host::{AppInfo, Host, Wake}; +use craft::platform::clipboard::{Clipboard, ClipboardProbe, EventClipboard}; +use craft::platform::clock::monotonic_ms; +use craft::theme::variant::Tone; +use craft::ui::contract::Bind; +use craft::ui::runtime::env::{RootEnv, Scale, ScrubDrags, WindowKey}; +use craft::ui::runtime::frame::{FrameInput, FrameOutput}; +use craft::ui::runtime::toast::{self, Toast}; +use craft::ui::runtime::windows::WindowHost; +use craft::ui::shell::embed::CloseDecision; +use craft::ui::shell::{AppShell, CanvasPanel, Slot}; +use vectorcraft_engine::cmd::clipboard::PASTE_ORDER; +use vectorcraft_engine::cmd::toast::Level; + use super::caches::{CanvasCache, Perf}; -use super::clock::now_ms; -use super::clock::now_secs; +use super::i18n::LangExt; use super::services::{Services, browsable_url}; -#[cfg(not(target_arch = "wasm32"))] -use super::state::FONT_INSTALL_POLL; -use super::state::{ - CaptureEpoch, GeometryStamp, InputGeneration, MAX_PENDING_SCREENSHOTS, MAX_SCREENSHOT_BYTES, MAX_SCREENSHOT_TOTAL_BYTES, PendingScreenshot, - QueuedScreenshot, SCREENSHOT_SETTLE_FRAMES, SCREENSHOT_TIMEOUT_ERROR, SCREENSHOT_TIMEOUT_MS, SYSTEM_CLIPBOARD_POLL, take_frame_once, -}; +use super::state::SYSTEM_CLIPBOARD_POLL; use super::{ - Arc, AutomationRoots, ControlRequest, Ordering, Receiver, Session, UiState, Value, VectorcraftApp, View, ViewInfo, background, canvas, chrome, - clipboard_probe, dialogs, export_progress, file_access, fileio, font_menu, graphics, i18n, io, json, menus, native_menu, opening, palette, - panel_docking, panels, picks, place, placing, plugin_runs, prefs_dialog, recovery, screen_color, scrub, shortcut_editor, shortcuts, theme, - titlebar, toolbar, tools_float, trace_runs, unsaved, updates_ui, widgets, + Arc, AutomationRoots, ControlRequest, Receiver, Session, UiState, Value, VectorcraftApp, View, ViewInfo, background, canvas, chrome, credits, + dialogs, export_progress, file_access, file_asks, fileio, font_menu, i18n, io, json, menus, opening, palette, panel_docking, panels, + place, placing, plugin_runs, prefs_dialog, recovery, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, }; -mod clipboard; mod commands; mod control; mod files; mod fonts; mod frame; -mod ime; mod input; mod links; mod prefs; -mod screenshot; +#[cfg(test)] +mod tests; mod view; pub use fonts::MAX_RECENT_FONTS; -impl VectorcraftApp { - /// Takes the host's Caps Lock state, which gives the drawing tools the crosshair while it is on - /// without changing the saved Use Precise Cursors preference. - pub fn set_caps_lock(&mut self, on: bool) { - if self.session.caps_lock != on - && let Err(err) = self.run("view.capsLock", json!({ "on": on })) - { - log::error!("Could not update Caps Lock cursor state: {err}"); - } - } +/// VectorCraft as the framework's services know it: the settings folder, the name and the version. +const APP_INFO: AppInfo = AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") }; - /// The app around `session`, reaching the platform through `services` (file pickers, the - /// clipboard, files and the like). It starts cataloguing the installed fonts at once, gives - /// Data Recovery the host's store and makes a view for each open document. - pub fn new(mut session: Session, services: Services) -> Self { +/// Monotonic seconds of the app's clock, which recovery, the clipboard look and the frame rate +/// count in. +fn now_secs() -> f64 { + monotonic_ms() / 1000.0 +} + +impl VectorcraftApp { + /// The app around `session`, reaching the platform through `services` (the clipboard, files + /// and the like). It starts cataloguing the installed fonts at once, gives Data Recovery the + /// host's store and makes a view for each open document. + pub fn new(mut session: Session, mut services: Services) -> Self { // The font menus and the first file opened need the installed fonts: catalog them now. vectorcraft_text::FontDb::global().scan_in_background(); if let Some(store) = &services.recovery_store { @@ -58,12 +64,25 @@ impl VectorcraftApp { let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); + let rich_clipboard = services.clipboard.is_some(); + // Without a host clipboard (tests, the web before its host sets one) copies stay inside the app. + // PLAN: `Clipboard::new` takes `impl ClipboardBackend`; a `Box` needs the framework's `impl ClipboardBackend for Box` (platform clipboard, shell-w14). + let clipboard = match services.clipboard.take() { + Some(backend) => Clipboard::new(backend), + None => Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))), + }; + // PLAN: the hosts (hub-w3) replace `host` with the one they build (files, settings, jobs); every frame installs it through `frame_input`. + let host = Arc::new(Host::builder(APP_INFO).i18n(i18n::shared()).build()); Self { session, ui: UiState::default(), views, view_uids, + clipboard_probe: None, + clipboard, + rich_clipboard, services, + host, canvas: CanvasCache { renderer: vectorcraft_render::Renderer::new(), texture: None, @@ -85,8 +104,7 @@ impl VectorcraftApp { find_font: None, hidden_chars: Default::default(), spelling: Default::default(), - selection_marks: Default::default(), - shared_paths: Default::default(), + momentary: None, selection_box: None, selection_bounds: None, content_bounds: None, @@ -95,13 +113,35 @@ impl VectorcraftApp { symbol_instances: None, plugin_keys: Default::default(), placed_keys: Default::default(), - cursors: Default::default(), view_moved: None, - hover_cursor: None, - presented: None, - opening_fit: None, panes: Default::default(), windows: crate::doc_windows::Windows::new(known), + images_with_other_art: None, + smooth_paths: None, + multi_color: None, + global_edit_count: None, + shape_angle: None, + trace_presets: None, + trace_target: None, + attributes_info: None, + svg_info: None, + css_shown: None, + svg_code: None, + artboard_thumbs: None, + document_families: None, + recently_added: None, + caret_kerning: None, + glyphs_found: None, + glyph_form_faces: None, + character_quads: None, + tabs_guide_axis: None, + appearance_summary: None, + transparency_state: None, + nav_region: None, + doc_info: None, + variable_rows: None, + map_surfaces: None, + palette: None, }, display_profile: Default::default(), perf: Perf::default(), @@ -109,119 +149,96 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_pathfinder: None, - last_warp: None, character_focus: None, run_count: 0, + channel: None, + captures: Default::default(), + context: 0, + ui_ctx: None, + updates_rt: Default::default(), + frame_rate: Default::default(), + hover_doc: None, clipboard_out: None, - clipboard_published: None, clipboard_in: None, clipboard_publishing: Default::default(), pending_url: None, - control_rx: None, - deferred_control: None, - synthetic_dropped_before: 0, - pending_screenshots: vec![], - pointer_replies: vec![], - queued_screenshots: vec![], - screenshot_token: 0, - screenshot_reserved: 0, - synthetic: vec![], - styled: false, - fonts_ready: false, - context: 0, - ui_ctx: None, - ui_fonts: Default::default(), - updates_rt: Default::default(), - frame_rate: Default::default(), - canvas_rect: None, - canvas_ui_zoom: 1.0, - control_rotate_press: None, - hover_doc: None, titlebar_from_env: false, - custom_titlebar: false, - caption_layout: Default::default(), - desktop_frame: false, desktop_keeps_frame: false, - last_window_title: String::new(), - fullscreen_for_mode: false, graphics_adapter: None, beacon: &crate::hang_beacon::BEACON, place: Default::default(), system_paste: false, clipboard_image_request: None, system_paste_at: f64::NEG_INFINITY, - clipboard_probe: None, - picks: picks::Picks::default(), + file_asks: Default::default(), + saves: Default::default(), original_editor: Default::default(), - screen_sampler: None, - font_check: None, - #[cfg(not(target_arch = "wasm32"))] - font_install_check_at: f64::NEG_INFINITY, - paste_chord: Default::default(), - // Held keys repeat their command (Cmd+= keeps zooming in). - dispatcher: craft_keymap::egui::Dispatcher::new().with_repeat(true), + screen_pick: craft::color_ui::ui::ScreenPick::new(), + font_watch: None, + fonts_seen: 0, + font_preview_owner: None, background: Default::default(), opening: Default::default(), plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), - toasts: Default::default(), recovery: Default::default(), - host_modifiers: Default::default(), - forwarded: Vec::new(), - forwarded_modifiers: None, - forwarded_modifiers_held: false, - forwarded_frame: false, - forwarded_clipboard: false, - forwarded_presses: vec![], - synthetic_modifiers: false, + closing: None, + prefs: None, + applied_prefs: None, + menus: Default::default(), + shortcuts_dialog: None, + shortcut_overrides: Default::default(), + told: Default::default(), + held: Default::default(), + edit_scopes: Default::default(), + command_dialog: Default::default(), + effect_dialogs: Default::default(), + three_d_dialog: None, + three_d: Default::default(), + export_dialogs: Default::default(), + web_export: Default::default(), + flattener_preview: Default::default(), + flatten_dialog: Default::default(), + print_dialog: Default::default(), + object_dialogs: Default::default(), + tool_dialogs: Default::default(), + color_dialogs: Default::default(), + plugin_dialog: None, + addon_panels: Default::default(), + addon_dialogs: Default::default(), + spelling: None, + char_style_preview: Default::default(), + para_style_preview: Default::default(), + justification: None, + bullets_preview: Default::default(), + pending_paste: None, + link_asks: None, ime_marked: None, ime_context: Default::default(), - ime_compositions: Default::default(), - ime_resets: Default::default(), - ime_caret_rect: None, - ime_discard: false, prefs_changed: false, - asset_export_presets: Value::Null, touch_screen: false, - scrub_group: false, - scrub_scope: None, automation_roots: None, - synthetic_frame: false, pending_plugin_install: None, pending_profile_open: None, queued_profile_opens: Default::default(), - script_picked: Vec::new(), - script_picked_left_out: false, pen_end: Default::default(), - host_iteration: 0, #[cfg(test)] now_override: None, #[cfg(test)] fail_next_tool_choice: None, - tick_iteration: None, - input_frames: vec![], - shortcuts_frames: vec![], held_tool: Vec::new(), - alt_tap: Default::default(), - hold_keys: Default::default(), - synthetic_injected: false, - injected_events: vec![], - injected_generation: InputGeneration::default(), - injected_settle_hook: false, - injected_settled: Default::default(), - geometry_epoch: 0, - geometry_stamp: None, } } + /// Answers the control channel whose requests arrive on `rx`. pub fn with_control(mut self, rx: Receiver) -> Self { - self.control_rx = Some(rx); + self.channel = Some(ControlChannel::new(rx)); self } /// Confine what the control channel does to `roots` (#832): its requests, the input it - /// injects (in the frames that carry it) and the saves and exports they start read and write + /// injects (in the passes that carry it) and the saves and exports they start read and write /// only inside them ([`file_access`]). The host's file services check every path they're given /// against the roots in force, and so does the engine; outside those scopes the person at the /// keyboard works as usual. @@ -254,10 +271,16 @@ impl VectorcraftApp { } self } + + /// The folders this pass may read and write: the automation roots while the pass carries + /// input the control channel injected, anywhere otherwise. + fn automation_scope(&self, ctx: &egui::Context) -> Option> { + WindowHost::of(ctx).injected_pass().then(|| self.automation_roots.clone()).flatten() + } } /// eframe isn't a dependency of this crate (the host owns the event loop); these entry points are -/// called from the host's `eframe::App` impl. +/// called from the host's `eframe::App` impl through `embed`'s hooks. impl VectorcraftApp { /// Applies the work that finished off the UI thread. It stays pending while a script runs, since /// every change to the documents ends in a busy error until the script ends. @@ -272,61 +295,89 @@ impl VectorcraftApp { placing::poll(self); } - /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a + /// The language the UI is drawn in: the Preferences window's choice while it is open (so a /// change shows before OK), else the `interfaceLanguage` preference (`auto` = the system's). pub fn ui_language(&self) -> i18n::Lang { - let editing = - self.ui.dialog.as_ref().filter(|d| d.kind == "preferences").and_then(|d| d.fields.get("interfaceLanguage")).and_then(Value::as_str); + // PLAN: assumed `prefs_dialog::draft_language(&VectorcraftApp) -> Option<&str>`, the open window's `interfaceLanguage` (sh.S9 gives the name only). + let editing = prefs_dialog::draft_language(self); i18n::Lang::from_pref(editing.unwrap_or(&self.session.prefs.interface_language)) } - /// The host starts one iteration: called from both hosts' `raw_input_hook`, before the host - /// decides whether a UI pass follows. It counts the iteration; it is not a frame or pass count - /// and does not promise that `ui` will run (a hidden window gets `tick` only). - pub fn begin_host_iteration(&mut self) { - self.host_iteration = self.host_iteration.wrapping_add(1); - // Frame keys identify input already taken in this host iteration. Each iteration starts - // fresh; this is what makes a viewport's discarded pass a duplicate, while two viewports' - // frame 0 both count. - self.input_frames.clear(); - self.shortcuts_frames.clear(); + /// What the runtime gets before each frame, from `embed::before_input`: the commands the last + /// frame fired run first, so the input reflects them; then the theme, the scale, the zoom + /// stops and the scrub choice from the preferences, the command states and the host with + /// the interface language. + pub fn frame_input(&mut self, out: FrameOutput) -> FrameInput { + // The output collects every pass of the last frame, so each fired command runs once here + // whatever number of passes fired it. + if let Some(ctx) = self.ui_ctx.clone() { + for fired in &out.fired { + shortcuts::run_fired(self, &ctx, fired); + } + menus::model::refresh(self, &ctx); + } + font_menu::end_previews(self, &out.ended_previews); + // PLAN: `out.removed_gestures` and `out.outer_edits` end the scopes in `edit_scopes`; widgets-w13's `edits` module owns that call (its contract row gives no signature). + let lang = self.ui_language(); + if self.host.lang() != lang { + self.host = Arc::new(self.host.with_lang(lang)); + } + let native_ppp = self.ui_ctx.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point() / ctx.zoom_factor()); + let root = root_env(&self.session.prefs, native_ppp); + FrameInput::new(root).commands(menus::model::command_input(self)).host(self.host.clone()) } - /// Background work, once per host iteration (full or logic-only): control requests, background - /// saves/exports/opens, plug-ins, recovery, font and clipboard polls, capture completion. It - /// reads only viewport state from `ctx.input` — never events or `i.time`: a logic-only pass + /// What the window's close button (or the system quitting the app) does, from `embed::logic`: + /// it waits for a running script to be asked and for a file dialog's sheet, and asks about + /// unsaved documents, once the saves running in the background are done and a Shape Builder + /// merge being computed is applied. With nothing to ask, the window closes and no recovery + /// copies are left behind. + pub fn close_decision(&mut self) -> CloseDecision { + unsaved::finish_pending(self); + if self.session.script_running() { + dialogs::script_run::ask_to_close(self); + return CloseDecision::Hold; + } + if self.file_sheet_open() { + self.status(file_asks::BUSY); + return CloseDecision::Hold; + } + if unsaved::any_dirty(self) { + if let Err(e) = unsaved::close_all(self, "quit") { + self.status(e); + } + return CloseDecision::Hold; + } + vectorcraft_engine::cmd::recovery::forget_all(&mut self.session); + CloseDecision::Close + } + + /// Background work, once per frame from eframe's `logic` (full or hidden): control requests, + /// background saves/exports/opens, plug-ins, recovery, font and clipboard polls. It reads + /// only viewport state from `ctx.input`, never events or `i.time`: a hidden window's `logic` /// leaves the last shown frame's input in place. /// - /// A bug that panics costs one iteration and shows an error, instead of closing the app with - /// unsaved work. + /// A bug that panics costs one frame's work and shows an error, instead of closing the app + /// with unsaved work. pub fn tick(&mut self, ctx: &egui::Context) { - let confined = self.synthetic_frame.then(|| self.automation_roots.clone()).flatten(); + let confined = self.automation_scope(ctx); if let Err(msg) = file_access::confine(confined.as_ref(), || vectorcraft_engine::guard::catch_panic(|| self.tick_frame(ctx))) { - self.picks.recover(); self.session.set_replaying(false); self.status(format!("Internal error: {msg} (please report this bug)")); } } - /// [`Self::tick`]'s work, once per host iteration: a second call in the same iteration (a - /// discarded rerun shares one hook call) does nothing. + /// [`Self::tick`]'s work. fn tick_frame(&mut self, ctx: &egui::Context) { - if self.tick_iteration == Some(self.host_iteration) { - return; - } - self.tick_iteration = Some(self.host_iteration); - let dialog_was_open = self.ui.dialog.is_some(); let lang = self.ui_language(); i18n::set_current(lang); // The engine gives new type the Japanese defaults while the UI is in Japanese. if self.session.ui_language.as_deref() != Some(lang.code()) { self.session.ui_language = Some(lang.code().to_string()); } - self.install_injected_settle_hook(ctx); - self.advance_geometry_epoch(ctx); - // Monotonic host time, never egui's `InputState::time`: a logic-only (hidden) iteration - // replays the last shown pass's time, freezing recovery, clipboard polling and deadlines. - // Tests inject a clock to drive idle scheduling deterministically. + // Monotonic host time, never egui's `InputState::time`: a hidden window's `logic` replays + // the last shown pass's time, freezing recovery, clipboard polling and deadlines. Tests + // inject a clock to drive idle scheduling deterministically. #[cfg(test)] let now = self.now_override.unwrap_or_else(now_secs); #[cfg(not(test))] @@ -336,12 +387,13 @@ impl VectorcraftApp { self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A - // background thread reads it where the host installs one (an unresponsive owner must never + // background thread reads it where the host gives one (an unresponsive owner must never // stall the frame loop); otherwise, or once that thread is gone, it is read here, at most a // few times a second (opening it locks it against other apps on some systems). let wanted = self.session.clipboard.is_empty() && self.session.active().is_some(); if let Some(make) = self.services.clipboard_probe.take() { - self.clipboard_probe = clipboard_probe::Probe::start(make, ctx.clone()); + let repaint = ctx.clone(); + self.clipboard_probe = ClipboardProbe::start(make, PASTE_ORDER.to_vec(), Wake::new(move || repaint.request_repaint())); } if let Some(pasteable) = self.clipboard_probe.as_mut().and_then(|p| p.pasteable(wanted)) { self.system_paste = pasteable; @@ -350,31 +402,29 @@ impl VectorcraftApp { self.system_paste_at = now; self.system_paste = wanted && self.system_clipboard_pasteable(); } - #[cfg(not(target_arch = "wasm32"))] - if !(0.0..FONT_INSTALL_POLL).contains(&(now - self.font_install_check_at)) { - self.font_install_check_at = now; - // Read on the next frame the app draws anyway: an idle app isn't woken for it. - self.refresh_installed_fonts(false); + if self.font_watch.is_none() { + self.watch_fonts(ctx); } - self.poll_font_check(ctx); - picks::poll(self, ctx); - // A Paste the host read before this iteration's formats were written must still wait for + self.follow_fonts(); + file_asks::poll(self); + io::save::pump(self, ctx); + // A Paste the host read before this frame's formats were written must still wait for // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); - screen_color::poll(self, ctx); + screen_color::tick(self, ctx); self.poll_finished_work(); crate::script_runs::poll(self); // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); - crate::dialogs::proof_setup::poll(self, ctx); if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() && self.session.script_picker().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. A - // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. + // script at a file dialog goes on when the dialog answers, and `file_asks::poll` looks + // for that. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), @@ -392,49 +442,14 @@ impl VectorcraftApp { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); } - // The window's close button (or the system quitting the app) asks about unsaved documents, - // once the saves running in the background are done and a Shape Builder merge being - // computed is applied. Not while a file dialog's sheet is on the window: what asked for it - // runs again when it answers. - if ctx.input(|i| i.viewport().close_requested()) { - // This native viewport is going away: release its IME context. No request is - // allocated here: the close prompt or file sheet publishes no custom descriptor, so a - // token would survive for a later stock field. A close the user then cancels starts a - // fresh generation on the next pass (never inherits a composition across the prompt). - crate::ime::close_viewport(self, ctx); - self.ime_context.end_viewport(ctx.viewport_id()); - unsaved::finish_pending(self); - if self.session.script_running() { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - dialogs::script_run::ask_to_close(self); - } else if self.file_sheet_open() { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - self.status(picks::busy()); - } else if unsaved::any_dirty(self) { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - if let Err(e) = unsaved::close_all(self, "quit") { - self.status(e); - } - } else { - // Quitting with nothing unsaved: no copies to leave behind. - vectorcraft_engine::cmd::recovery::forget_all(&mut self.session); - } - } if let Some(wait) = recovery::frame(self, now) { // The timer and heartbeat run in an idle window too. ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } crate::keymap::note_os(ctx); - shortcut_editor::sync(&self.ui); - crate::dialogs::svg_filter::sync(self); crate::panels::actions::sync_function_keys(&self.ui); prefs_dialog::apply_runtime(self, ctx); - // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the - // system title bar this is where the document name lives, as the in-app mark is hidden. - crate::chrome::sync_window_title(self, ctx); - crate::chrome::sync_fullscreen(self, ctx); - self.drain_control(ctx); - self.answer_pointer_replies(ctx); + self.run_control(ctx); // An egui `PasteImage` with a rich system clipboard: run the paste command now, once. It // goes through `run`, whose `edit.paste` branch calls `adopt_system_clipboard` (which clears // the request) to read the formats and then pastes them. A text paste in the same UI pass @@ -442,11 +457,10 @@ impl VectorcraftApp { if let Some(held) = self.clipboard_image_request.take() { crate::menus::invoke(self, crate::shortcuts::paste_command(held), json!({})); } - self.collect_screenshots(ctx); if let Some(u) = self.pending_url.take() { ctx.open_url(egui::OpenUrl::new_tab(u)); } - self.flush_clipboard_out(ctx); + self.flush_clipboard_out(); self.drain_inbox(); // An action playing at Step by Step or Pause For runs its next step when it is due, after // the control requests and opened files above: a Stop or a document switch they bring @@ -454,235 +468,165 @@ impl VectorcraftApp { if let Some(wait) = crate::panels::actions::tick_playback(self, now) { ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } - if self.viewport_hidden(ctx) && (self.needs_hidden_paint() || (!dialog_was_open && self.ui.dialog.is_some())) { - // A plain repaint runs only logic in a hidden window: the ui that applies injected - // input, shows a queued dialog or issues a capture needs this command. egui-winit - // handles it; the 0.37 web backend does not (a pending fork fix), so a hidden browser - // tab cannot be claimed as qualified. - ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); - } - if !self.synthetic.is_empty() || self.synthetic_injected || !self.pending_screenshots.is_empty() { - ctx.request_repaint(); - } } - /// The 0.36-style entry point, kept for the crate's tests, which call one `logic` inside a - /// `run_ui` pass and draw a panel afterwards (a UI phase). Production hosts call - /// `raw_input_hook`, then `tick` in `App::logic` and `ui` in `App::ui`; `tick` alone never - /// takes input, so a hidden logic-only iteration cannot replay the last shown frame's events. - /// - /// Outside tests this is just [`Self::tick`] with an iteration boundary. - pub fn logic(&mut self, ctx: &egui::Context) { - self.begin_host_iteration(); - self.tick(ctx); - #[cfg(test)] - { - let confined = self.synthetic_frame.then(|| self.automation_roots.clone()).flatten(); - let _ = file_access::confine(confined.as_ref(), || { - vectorcraft_engine::guard::catch_panic(|| { - self.ui_setup(ctx); - self.handle_input_once(ctx); - }) - }); - } - self.finish_ime_logic(ctx); - } - - /// First UI-pass setup, in a real `run_ui` phase: adopt the context, install the interface - /// fonts and theme, and the image loaders. 0.37's `set_fonts` applies at once when no text has - /// been laid out, so the same pass can draw; a hidden logic-only iteration never installs them. - fn ui_setup(&mut self, ctx: &egui::Context) { - // Hosts install before their first pass. Installing here covers later passes only: egui - // has already snapshotted this pass's plugin list, so a direct harness that calls `logic` - // inside its first `run_ui` must call `install_ime_reset_hooks` before that `run_ui` - // (as `tests_lifecycle::ime_frame` does). This is not a first-pass bootstrap fallback. - crate::ime::install_hooks(ctx); - self.adopt_context(ctx); - if !self.styled { - // The saved accent, color scheme and canvas color, not the defaults (#4837). - prefs_dialog::reapply(self, ctx); - egui_extras::install_image_loaders(ctx); - self.styled = true; - } - if !self.fonts_ready { - // `set_fonts` applies at once only while no text was laid out in this pass; when it - // defers, the next pass applies it and this leaves input and drawing to that pass. - let fonts = theme::interface_fonts(); - ctx.set_fonts(fonts.clone()); - self.fonts_ready = ctx.fonts(|applied| applied.definitions() == &fonts); - } - } - - /// The canvas panel's body: the document tabs, the canvas (a pane for each document while + /// The canvas panel's body: the document tabs, then the canvas (a pane for each document while /// Window › Arrange › Tile is on) and the isolation bar over it. While the current document is - /// in a floating window, the tab strip's document draws as a pane, which a Selection drag's - /// artwork can be released in ([`canvas::note_drop`]). + /// in a floating window, the tab strip's document draws as a pane. pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui) { - let t = theme::Tokens::get(ui.ctx()); - // Tools may already occupy the left side of this panel. - ui.painter().rect_filled(ui.available_rect_before_wrap(), 0.0, t.pasteboard); self.canvas.windows.strip = None; - self.canvas.windows.drops.clear(); - if self.ui.screen_mode < 3 { - chrome::doc_tabs(self, ui); - } - self.canvas.windows.area = Some(ui.available_rect_before_wrap()); - let floats = crate::doc_windows::current_floats(self); - if !canvas::tiled_area(self, ui) { - if floats { - let rect = ui.available_rect_before_wrap(); - if let Some(w) = crate::doc_windows::tab_window(self) { - let pressed = canvas::pane(self, ui, w, rect); - // A drag from a current window that is an OS window ends in that window. - if !crate::doc_windows::native(self, ui.ctx()) { - canvas::note_drop(self, ui, w, rect); - } - if pressed { - crate::doc_windows::show_window(self, w); + let opening = !self.opening.pending.is_empty(); + let presenting = self.ui.presenting(); + // The tab strip and the document are two closures of one panel: they take the app in + // turn, and a borrow that fails (a closure re-entered) skips its part. + let app = std::cell::RefCell::new(self); + CanvasPanel::new() + .opening(opening) + .tabs(|ui, _cx| { + if !presenting && let Ok(mut app) = app.try_borrow_mut() { + chrome::doc_tabs(&mut app, ui); + } + }) + .show(ui, |ui, _cx| { + let Ok(mut app) = app.try_borrow_mut() else { return }; + let app: &mut VectorcraftApp = &mut app; + app.canvas.windows.area = Some(ui.available_rect_before_wrap()); + let floats = crate::doc_windows::current_floats(app); + if !canvas::tiled_area(app, ui) { + if floats { + let rect = ui.available_rect_before_wrap(); + if let Some(w) = crate::doc_windows::tab_window(app) + && canvas::pane(app, ui, w, rect) + { + crate::doc_windows::show_window(app, w); + } + } else { + canvas::show(app, ui); } } - } else { - canvas::show(self, ui); - } - } - // Over the canvas inside the rulers, so the rulers and scroll bars stay uncovered. - if self.ui.screen_mode < 3 - && !floats - && !menus::home_showing(self) - && let Some(area) = self.canvas_rect - { - chrome::isolation_bar(self, ui, area); - } + // Over the canvas inside the rulers, so the rulers and scroll bars stay uncovered. + if !presenting + && !floats + && !menus::home_showing(app) + && let Some(view) = app.canvas_view() + { + chrome::isolation_bar(app, ui, view.rect); + } + }); } - /// Lay out the whole window: the first UI pass of a host iteration sets the UI up (fonts, - /// theme, image loaders) and takes the input; later passes (a `request_discard` rerun) draw - /// only. + /// Lay out the whole window, once per pass. The guard confines a pass that carries injected + /// input to the automation roots and turns a panic into an error message. pub fn ui(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); - crate::ime::begin_ui(self, &ctx); - let confined = self.synthetic_frame.then(|| self.automation_roots.clone()).flatten(); + self.adopt_context(&ctx); + let confined = self.automation_scope(&ctx); if let Err(msg) = file_access::confine(confined.as_ref(), || { vectorcraft_engine::guard::catch_panic(|| { - self.ui_setup(&ctx); - self.handle_input_once(&ctx); + self.handle_input(&ctx); self.ui_frame(ui); + self.window_keys(&ctx); }) }) { - self.picks.recover(); self.session.set_replaying(false); self.status(format!("Internal error: {msg} (please report this bug)")); } - crate::ime::finish_ui(self, &ctx); } - /// [`Self::ui`]'s work, inside its guard: the bars, panels and canvas, then the dialogs and - /// progress windows over them. + /// [`Self::ui`]'s work, inside its guard: the window's shell with its bars and the panels and + /// canvas, then the windows, dialogs and messages over them. fn ui_frame(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); - if !self.fonts_ready { - // Do not draw (or run the app's input handling) before the interface fonts are the - // context's: a deferred `set_fonts` applies at the start of the next pass. - ctx.request_repaint(); - return; - } - crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); + // A copy made by injected input is not the user's: the clipboard keeps it inside the app. + self.clipboard.set_synthetic(WindowHost::of(&ctx).injected_pass()); // Whether this pass draws the last step of an action playing at Step by Step. let step_held = crate::panels::actions::playback_held(self); - let t0 = now_ms(); - widgets::set_dialog_open(&ctx, self.ui.dialog.is_some()); - // The canvas records this pass's IME caret geometry; a pass that draws no canvas has none. - self.ime_caret_rect = None; - scrub::begin_frame(self, &ctx); - font_menu::end_stale_preview(self, &ctx); - font_menu::apply_preview_size(self, &ctx); - tools_float::track(self, &ctx); - // A selection move released over a panel ends before any panel sees the release (#2826). - canvas::release_over_panel(self, &ctx); - let t = theme::Tokens::get(&ctx); - if self.ui.screen_mode < 2 { - chrome::app_bar(self, ui); - if self.ui.control_bar { - chrome::control_bar(self, ui); - } - } - if self.ui.status_bar && self.ui.screen_mode < 3 { - chrome::status_bar(self, ui); - } - if self.ui.help_bar && self.ui.screen_mode < 3 { - chrome::hint_bar(self, ui); - } - if (self.ui.screen_mode >= 3 || (!self.ui.status_bar && !self.ui.help_bar)) - && !(self.ui.control_bar && self.ui.control_bar_bottom && !self.ui.control_bar_floating && self.ui.screen_mode < 2) - { - // Keeps the previous frame's value valid for menus drawn above, before the bars. A - // Control bar docked at the bottom has set it to the bar's top; a floating one sets none. - widgets::set_menu_floor(&ctx, ctx.content_rect().bottom()); - } - if self.ui.toolbar && self.ui.screen_mode < 3 { - tools_float::set_window_dock_zone(&ctx, ui.available_rect_before_wrap()); - } - // Beside the canvas, docked Tools draws inside the canvas panel (`toolbar::show_beside_canvas`). - // So does Tools docked on the right, left of the panels. - if self.ui.toolbar && self.ui.screen_mode < 3 && ((!self.ui.tools_beside_canvas && !self.ui.toolbar_right) || self.ui.toolbar_pos.is_some()) { - toolbar::show(self, ui); - } else if !self.ui.toolbar && self.ui.screen_mode < 3 && self.ui.tab_hid.is_none() { - // Window › Tools hides the Tools panel alone; Tab hides the toolbars made with New - // Toolbar too. - toolbar::show_custom(self, ui.ctx()); - } - // The lanes along the window's edges where toolbars made with New Toolbar dock. - crate::custom_toolbars::lanes(self, ui); + let t0 = monotonic_ms(); panels::library_panel::tidy(self); - // The canvas and the panels: one docking layout. Tab hides the panels but not the canvas. - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); + let given = self.ui.screen_mode(); + let mut control_bar_place = chrome::control_bar_place(&self.ui); + // PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9). + let window_title = chrome::window_title(self); + let shown = AppShell::new(WindowKey::main()) + .title_bar_if(true, chrome::app_bar) + .options_bar(self.ui.control_bar, |ui, _cx, app: &mut VectorcraftApp| { + chrome::control_bar(app, ui); + }) + .options_place(Bind::bound(&mut control_bar_place)) + .status(self.ui.status_bar, |ui, _cx, app: &mut VectorcraftApp| { + chrome::status_bar(app, ui); + }) + .bottom(Slot::new(chrome::HINT_SLOT).visible(self.ui.help_bar), |ui, _cx, app: &mut VectorcraftApp| { + chrome::hint_bar(app, ui); + }) + .window_title(window_title) + .screen_mode(Bind::given(given)) + .allow_reveal(!self.ui.presenting()) + .body(|ui, _cx, app: &mut VectorcraftApp| { + panel_docking::show(app, ui); + }) + .show(ui, self); + chrome::set_control_bar_place(&mut self.ui, control_bar_place); + if shown.screen_mode != given { + self.ui.follow_screen_mode(shown.screen_mode); + } panels::learn::locate::tidy(self, &ctx); - crate::doc_windows::show(self, &ctx); - dialogs::show(self, &ctx); - updates_ui::show(self, &ctx); - export_progress::show(self, &ctx); - plugin_runs::show(self, &ctx); - trace_runs::show(self, &ctx); - opening::show(self, &ctx); - placing::show(self, &ctx); + crate::doc_windows::show(self, ui); + export_progress::show(self, ui); // After every window this pass may open, and before the palette's field takes the keyboard. panel_docking::close_overlays_for_modal(self, &ctx); - palette::show(self, &ctx); + dialogs::host::pump(self, &ctx); + prefs_dialog::show(self, ui); + credits::open_taken_link(self); + palette::show(self, ui); // A shape drawn on the canvas, in a dialog or by a command in this pass shows the Transform // panel (Show on Shape Creation). panels::transform::show_on_shape_creation(self, &ctx); - crate::toasts::show(self, &ctx); - // After every panel had its chance to draw in this pass. - crate::panels::three_d::end_stale_drag(self, &ctx); - if self.custom_titlebar { - titlebar::resize_zones(ui); + for t in self.session.take_toasts() { + toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32))); } - self.ui_fonts.frame(&ctx); - if self.ui.dialog.is_none() && !self.ui.palette_open { - shortcuts::remember_text_focus(&ctx); - } - scrub::end_frame(self, &ctx); - native_menu::sync(self, &ctx); - // Observe once, after all of this pass's input, dialogs, floating panels, palette and - // commands: the latest completed pass is authoritative for owner, text and cause. - crate::ime::end_of_pass(self, &ctx); + menus::native::sync(self, &ctx); self.drop_formats_after_egui_copy(&ctx); // A command run by a menu, panel or dialog in this pass may have queued its text copy - // after the UI phase's input flush. Publish it now for the same reason as there. - self.flush_clipboard_out(&ctx); + // after the input. Publish it now: an idle web host may have no further frame to run it in. + self.flush_clipboard_out(); if opening::long_operation_busy(self) { - ctx.set_cursor_icon(egui::CursorIcon::Progress); + // PLAN: assumed `crate::cursors::request_busy(&egui::Context)` (canvas-03:143 names the call only; canvas-w25). + crate::cursors::request_busy(&ctx); } // A pass egui will discard and rerun is not a presented frame: it must not become the - // frame-time sample, and it must not issue a capture of what it drew. + // frame-time sample. if !ctx.will_discard() { - self.perf.frame_ms = now_ms() - t0; - self.issue_screenshots(&ctx); + self.perf.frame_ms = monotonic_ms() - t0; // A hidden window's pass shows nothing, so the step waits for a pass the user sees. if step_held && !self.viewport_hidden(&ctx) { crate::panels::actions::playback_drawn(self); } } - let _ = json!(null); + // Last, over everything: the screen colour picker's loupe and capture windows. + screen_color::show(self, ui); + } +} + +/// The root values the preferences give every frame: the theme, the interface scale (UI Scaling +/// over the display's `native_ppp`), Show Tool Tips, the zoom stops and which drags scrub a value +/// (Scrub Numeric Fields: the side label only, or nothing). +pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32) -> RootEnv { + let (theme, mode, accent) = theme::root_theme(prefs); + // A hand-edited preferences file must not scale the interface to nothing. + let scaling = if prefs.ui_scaling.is_finite() && prefs.ui_scaling > 0.0 { prefs.ui_scaling as f32 } else { 1.0 }; + let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); + root.values.set(view::zoom_scheme(prefs, native_ppp)); + root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off }); + root +} + +/// The toast tone of an engine message's level. +fn tone(level: Level) -> Tone { + match level { + Level::Info => Tone::Info, + Level::Success => Tone::Good, + Level::Warning => Tone::Warn, + Level::Error => Tone::Bad, } } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..0e81efd6ae 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -1,5 +1,5 @@ use super::fonts::MAX_RECENT_FONTS; -use super::{Value, VectorcraftApp, canvas, dialogs, fileio, io, menus, panels, picks, toolbar}; +use super::{Value, VectorcraftApp, canvas, dialogs, fileio, io, menus, panels}; use crate::placing; use crate::state::ReplaceFontWarning; @@ -75,13 +75,7 @@ impl VectorcraftApp { pub fn run(&mut self, id: &str, params: Value) -> Result { self.beacon.command(id); let touch_workspace = self.session.prefs.touch_workspace; - // A file dialog it shows off the UI thread runs it again with the path picked. - let result = if self.picks.is_entry_free() { - let entry = picks::Entry::Command(id.to_string(), params.clone()); - picks::as_entry(self, move || entry, |app| app.run_now(id, params)) - } else { - self.run_now(id, params) - }; + let result = self.run_now(id, params); if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } @@ -134,9 +128,8 @@ impl VectorcraftApp { } } - /// [`Self::run`] it, inside what asks for file dialogs. + /// [`Self::run`]'s work. fn run_now(&mut self, id: &str, params: Value) -> Result { - crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); self.run_count = self.run_count.wrapping_add(1); // In debug builds the app's own calls are held to the params descriptions too (#1442): a // panel passing a key its command doesn't read shows up in the tests. Saved steps aren't @@ -238,25 +231,9 @@ impl VectorcraftApp { self.ui.status = e.clone(); return Err(e); } - // A command that changes the edited text is an application edit (undo, a panel or menu - // edit, a control request). Capture the bounded committed context around it so `Other` - // dominates the frame even if an IME receipt follows. Selection/view commands that leave - // the committed text and caret unchanged record nothing. - let ime_view = self.view_info(); - let ime_target = crate::ime::target(&mut self.session, ime_view); - let ime_before = crate::ime::stamp(&mut self.session, ime_view); - let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors); let spot_base = panels::color_guide::before_command(self); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); let r = panels::actions::after_recorded_command(self, r); - if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) { - self.canvas.hover_cursor = None; - } - if r.is_ok() - && let Some(ctx) = self.ui_ctx.clone() - { - crate::ime::note_application_edit(self, &ctx, ime_view, ime_target, ime_before); - } if r.is_ok() && let Some(op) = completed_pathfinder_operation(id, ¶ms) { @@ -276,9 +253,7 @@ impl VectorcraftApp { // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. panels::color_guide::after_command(self, id, ¶ms, v, spot_base); // A renamed color group stays selected in the Swatches panel. - if let Some(ctx) = self.ui_ctx.clone() { - panels::swatches::after_command(&ctx, id, ¶ms, v); - } + panels::swatches::after_command(self, id, ¶ms, v); if id == "file.new" { self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). @@ -464,7 +439,7 @@ impl VectorcraftApp { /// stays as it was. pub(crate) fn try_select_tool(&mut self, id: &str) -> Result<(), String> { let back = self.ui.brush_key_color_pick.as_ref().map(|pick| pick.back.clone()); - crate::dialogs::cancel_brush_key_color(self, false); + crate::dialogs::brush_art_options::end_key_color_pick(self, false); // The tip of a pen whose eraser end selected the Eraser doesn't undo this choice, and // neither does letting go of a held tool shortcut. self.pen_end.forget_tool(); @@ -510,10 +485,6 @@ impl VectorcraftApp { None if fresh => self.session.select_tool(id, v).map_err(|e| e.to_string()), None => self.session.switch_tool(id, v).map_err(|e| e.to_string()), }; - if before != self.session.tool_id() { - // A control gesture cannot resume after another tool has owned the pointer. - self.control_rotate_press = None; - } // A newly chosen Artboard tool starts on the active artboard (the view's). if before != "artboard" && self.session.tool_id() == "artboard" @@ -521,7 +492,6 @@ impl VectorcraftApp { { panels::artboards::select(self, panels::artboards::selected(self, n)); } - self.ui.flyout = None; switched?; crate::panels::image_trace::cancel_ignore_sampler(self, false); if let Some(g) = vectorcraft_tools::catalog::group_of(id) @@ -529,7 +499,6 @@ impl VectorcraftApp { { *slot = id.to_string(); } - toolbar::remember(self, id); Ok(()) } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index ce9aa6bf93..37ae0b7a8f 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -1,26 +1,17 @@ -use super::{GeometryStamp, InputGeneration, VectorcraftApp}; +use super::VectorcraftApp; impl VectorcraftApp { - /// The host iteration count: one increment per `App::logic`/`App::ui` iteration (or a - /// logic-only one), for panel state that asks "was this drawn in the last iteration?". - pub(crate) fn frame_iteration(&self) -> u64 { - self.host_iteration - } - /// The canvas on screen in document coordinates (none before it is laid out). pub fn screen_frame(&self) -> Option { - let (rect, xf) = (self.canvas_rect?, self.canvas_xf()?); - let px = |x: f32, y: f32| xf.delta_to_doc(egui::vec2(x, y)); + let view = self.canvas_view()?; Some(vectorcraft_tools::ScreenFrame { - origin: xf.to_doc(rect.left_top()), - right: px(1.0, 0.0), - down: px(0.0, 1.0), - size: (f64::from(rect.width()), f64::from(rect.height())), + origin: view.to_doc(view.rect.left_top()), + right: view.unmap_vec(egui::vec2(1.0, 0.0)), + down: view.unmap_vec(egui::vec2(0.0, 1.0)), + size: (f64::from(view.rect.width()), f64::from(view.rect.height())), }) } -} -impl VectorcraftApp { /// Is the window minimized or fully occluded (as far as the host reports)? pub(crate) fn viewport_hidden(&self, ctx: &egui::Context) -> bool { ctx.input(|i| { @@ -28,45 +19,4 @@ impl VectorcraftApp { v.minimized == Some(true) || v.occluded == Some(true) }) } - - /// Is there work that only a UI pass can do, so a hidden window must be asked to paint? - pub(super) fn needs_hidden_paint(&self) -> bool { - !self.synthetic.is_empty() - || self.synthetic_injected - || !self.queued_screenshots.is_empty() - || self.pending_screenshots.iter().any(|p| p.slot.is_none()) - } - - /// Capture the viewport identity and geometry (content and inner rectangles, pixels per point and - /// zoom) whose change advances the screenshot epoch. - fn geometry_stamp(ctx: &egui::Context) -> GeometryStamp { - GeometryStamp { - viewport: ctx.viewport_id(), - content: ctx.content_rect(), - inner: ctx.input(|i| i.viewport().inner_rect), - pixels_per_point: ctx.pixels_per_point(), - zoom: ctx.zoom_factor(), - } - } - - /// Advance the capture geometry epoch when any part of the window geometry changed, even back - /// to a previous value: a capture issued before the change must not be saved as if it showed - /// the new one. - pub(super) fn advance_geometry_epoch(&mut self, ctx: &egui::Context) { - let stamp = Self::geometry_stamp(ctx); - if self.geometry_stamp != Some(stamp) { - self.geometry_stamp = Some(stamp); - self.geometry_epoch = self.geometry_epoch.wrapping_add(1); - } - } - - /// Identify the document, modal dialog and focused widget that the current accepted input batch - /// belongs to. - pub(crate) fn input_generation(&self) -> InputGeneration { - InputGeneration { - document: self.session.active().map_or(0, |document| document.uid), - dialog: self.ui.dialog.as_ref().map(|dialog| egui::Id::unique(&dialog.kind)), - focus: self.ui_ctx.as_ref().and_then(|ctx| ctx.memory(|memory| memory.focused())), - } - } } diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 70f5b4e81c..31a4009867 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -1,287 +1,26 @@ -use super::{Arc, Ordering, VectorcraftApp, graphics, native_menu, shortcuts, take_frame_once, tools_float}; -#[cfg(not(target_arch = "wasm32"))] -use super::{fileio, place}; +use super::{VectorcraftApp, menus, shortcuts}; impl VectorcraftApp { - /// The first UI pass of a host iteration takes the host's input, once per context, viewport and - /// frame: clipboard formats, native-menu clicks, shortcuts and dropped files. A later pass - /// (`request_discard` rerun) or an interleaved second viewport pass with the same key draws - /// again but does not replay them; a logic-only iteration never reaches this. - pub(super) fn handle_input_once(&mut self, ctx: &egui::Context) { - let frame = (graphics::context_tag(ctx), ctx.viewport_id(), ctx.cumulative_frame_nr_for(ctx.viewport_id())); - if !take_frame_once(&mut self.input_frames, frame) { - return; - } + /// Each pass, before the UI: the rich clipboard formats a paste into a text field must find + /// written, and the clicks of the native menu bar. egui gives a frame's events to its first + /// pass only, so a second pass of the frame finds no new paste or click and repeats nothing. + pub(super) fn handle_input(&mut self, ctx: &egui::Context) { self.write_formats_before_text_input(ctx); - native_menu::run(self, ctx); - if self.fonts_ready { - tools_float::cancel_move_on_escape(self, ctx); - crate::custom_toolbars::cancel_move_on_escape(self, ctx); - if !crate::menus::handle_keyboard_input(self, ctx) { - shortcuts::handle(self, ctx); - } - } - // A Copy taken in this UI phase (an egui copy event, or a command it runs) is published in - // this same pass: waiting for the next `tick` can leave the command unissued when an idle - // web host has no further frame to run it in. Native rich-format Copy does not use this - // path; it writes through `SystemClipboard` and leaves `clipboard_out` empty. - self.flush_clipboard_out(ctx); - // Native only: the web host reads dropped files asynchronously and feeds the inboxes. - #[cfg(not(target_arch = "wasm32"))] - self.take_dropped_files(ctx); + menus::native::run(self, ctx); + // A Copy taken by the native menu is published in this same pass: an idle web host may + // have no further frame to run it in. + self.flush_clipboard_out(); } - /// Files dropped on the window: documents, libraries, presets, plug-ins and shortcut sets - /// opened, pictures and text placed on the canvas ([`Self::drop_target`]). - #[cfg(not(target_arch = "wasm32"))] - fn take_dropped_files(&mut self, ctx: &egui::Context) { - let (dropped, shift) = ctx.input(|i| (i.raw.dropped_files.clone(), i.modifiers.shift)); - self.open_dropped_files(dropped, place::drag_pos(ctx), shift); - } - - /// Files dropped on the main window or on a floating panel's own OS window, opened or placed - /// by kind; `pos` is the drop point in the main window, where the backend reports one. - #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn open_dropped_files(&mut self, dropped: Vec, pos: Option, shift: bool) { - if dropped.is_empty() { - return; + /// Each pass, last in the UI: the window's keys that no component took. Escape ends one thing + /// (a gesture, a mode, the screen mode), unless the menu bar is open or has the keys; then a + /// tool held by its key goes back once what deferred its return has ended. Both read only the + /// intents of their own pass, so a second pass of a frame applies none of the first's. + pub(super) fn window_keys(&mut self, ctx: &egui::Context) { + // PLAN: assumed `craft::menu::bar::{is_open, is_focused}(&egui::Context) -> bool` (menus-w6's request names them; the framework tree has neither yet). + if !craft::menu::bar::is_open(ctx) && !craft::menu::bar::is_focused(ctx) { + shortcuts::escape(self, ctx); } - let mut files = vec![]; - for f in dropped { - let path = Some(f.path().to_string_lossy().to_string()).filter(|s| !s.is_empty()); - let name = path.as_deref().map_or_else(|| "dropped".into(), vectorcraft_engine::cmd::fileio::file_name); - // Native file drops usually carry a path. Use the same file reader as File → Open - // (and File → Place), even if the drop handle can't supply the bytes itself. - let bytes = if path.is_some() && self.services.read.is_some() { Ok(vec![]) } else { f.bytes() }; - match bytes { - Ok(bytes) => { - // A backend may give bytes without a path or extension. Sniff their format - // before deciding: an SVG opens as a document, a raster image is placed. - let target = if path.is_none() && fileio::detect(&name, &bytes).is_none_or(|f| !f.raster) { - place::DropTarget::Open - } else { - self.drop_target(&name, pos, shift) - }; - files.push((target, (name, path, bytes))); - } - Err(e) => self.status(format!("Couldn't read {name}: {e}")), - } - } - place::drop_files(self, files); - } - - /// Install the end-of-pass observer that tells the next host iteration a settled UI pass took - /// the injected batch (a font-gated or discarded pass does not). The shipped hosts have only - /// the root viewport; a multi-viewport host would need pending batches and settlement keyed - /// per viewport instead of this root-only acknowledgement. - pub(super) fn install_injected_settle_hook(&mut self, ctx: &egui::Context) { - if self.injected_settle_hook { - return; - } - let settled = self.injected_settled.clone(); - ctx.on_end_pass( - "vectorcraft injected input settlement", - Arc::new(move |ui| { - if ui.ctx().viewport_id() == egui::ViewportId::ROOT && !ui.ctx().will_discard() { - settled.store(true, Ordering::Relaxed); - } - }), - ); - self.injected_settle_hook = true; - } - - /// The settled pass took the injected batch: allow the next step at the next host iteration. - fn acknowledge_injected_batch(&mut self) { - self.synthetic_injected = false; - self.injected_events.clear(); - self.synthetic_frame = false; - } - - /// The document, dialog or focus changed before a UI pass took the batch: remove exactly the - /// events we appended (they still live in eframe's pending raw input) so a forced hidden paint - /// cannot replay stale clicks or text into the new state. - fn discard_stale_injected_batch(&mut self, raw: &mut egui::RawInput) { - if !self.synthetic_injected || self.input_generation() == self.injected_generation { - return; - } - let events = std::mem::take(&mut self.injected_events); - let mut removed = false; - if !events.is_empty() - && let Some(start) = raw.events.windows(events.len()).rposition(|window| window == events.as_slice()) - { - raw.events.drain(start..start + events.len()); - removed = true; - } - if !events.is_empty() && !removed { - // The host's raw input no longer contains the batch as we injected it (another - // handler rewrote or interleaved events). We cannot tell stale synthetic input from - // the person's, so fail closed: deliver nothing this pass rather than replay a stale - // click or text into the state that replaced it, and cancel the rest of that - // synthetic sequence instead of injecting its next step after this one. - raw.events.clear(); - self.synthetic.clear(); - } - // The discarded batch may have carried the modifiers it set; the host's modifiers are - // what the next real event has, so do not leave a synthetic latch behind. - self.synthetic_modifiers = false; - self.synthetic_injected = false; - self.synthetic_frame = false; - // The `ui.pointer` requests made after this input, waiting or still on the channel, would - // run without it: `drain_control` answers the ones made before now with an error. - self.synthetic_dropped_before = crate::control::ControlRequest::next_seq(); - } - - /// Release the pointer buttons egui still holds down when the system reports that no mouse - /// button is down (`system_held` is false), at the pointer's last position. egui ends a drag - /// only on a button release or Escape, so a release the window never received leaves a drag, - /// such as a dock column's resize, following the pointer (#4326). Frames that carry a button - /// event, and control-channel input that holds a button between steps, are left alone. - pub fn release_lost_buttons(&self, ctx: &egui::Context, raw: &mut egui::RawInput, system_held: bool) { - if system_held - || self.synthetic_injected - || !self.synthetic.is_empty() - || raw.events.iter().any(|e| matches!(e, egui::Event::PointerButton { .. })) - { - return; - } - let (down, pos, modifiers) = ctx.input_for(raw.viewport_id, |i| { - let p = &i.pointer; - let down: Vec = [ - egui::PointerButton::Primary, - egui::PointerButton::Secondary, - egui::PointerButton::Middle, - egui::PointerButton::Extra1, - egui::PointerButton::Extra2, - ] - .into_iter() - .filter(|b| p.button_down(*b)) - .collect(); - (down, p.latest_pos().or_else(|| p.interact_pos()).or_else(|| p.press_origin()), i.modifiers) - }); - // The releases go after this frame's last pointer movement, at its position, so a pointer - // that moved away from the press does not end it with a click at the press position. - let moved = raw.events.iter().enumerate().rev().find_map(|(i, e)| match e { - egui::Event::PointerMoved(p) => Some((i + 1, *p)), - _ => None, - }); - let (at, pos) = match moved { - Some((at, p)) => (at, Some(p)), - None => (0, pos), - }; - let Some(pos) = pos else { return }; - let releases = down.into_iter().map(|button| egui::Event::PointerButton { pos, button, pressed: false, modifiers }); - raw.events.splice(at..at, releases); - } - - /// Inject synthetic events (one press/release step, wheel turn or short key sequence per host - /// iteration), carrying control provenance until a settled UI pass has taken the batch. The - /// batch belongs to the one root viewport the shipped hosts draw (see - /// `install_injected_settle_hook`); a multi-viewport host would key it by viewport. A - /// hidden logic-only iteration may see this hook run without a UI pass: nothing more is - /// injected until the batch was actually applied, so a burst of hidden ticks cannot queue - /// several steps of a drag or replay them together later. - pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - crate::canvas::capture_pointer_before_input(ctx, raw.viewport_id); - self.fill_raw_input(ctx, raw); - crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id); - crate::font_menu::take_raw_wheel(ctx, raw); - } - - fn fill_raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - // Both hosts call this hook once per host iteration, before deciding whether a UI pass - // follows; it is the iteration boundary, not a UI-phase marker. - self.begin_host_iteration(); - // The observer lives on the context so it also settles a harness that consumes raw input - // without calling `VectorcraftApp::ui`. - self.install_injected_settle_hook(ctx); - // The native menu's key equivalents become the input their keys make, ahead of what came - // after them (see `native_menu`). - let keys = self.services.native_menu.as_mut().map(native_menu::NativeMenu::take_keys).unwrap_or_default(); - // The menu bar does nothing while a file dialog is open (`native_menu`): a key that raced it - // going inert is dropped. - if !keys.is_empty() && !self.file_dialog_open() { - let events: Vec = keys.into_iter().flat_map(|k| native_menu::key_events(k, || self.system_clipboard_text())).collect(); - raw.events.splice(0..0, events); - } - for e in &raw.events { - match e { - egui::Event::ModifiersChanged(m) => self.host_modifiers = *m, - egui::Event::WindowFocused(false) => self.host_modifiers = egui::Modifiers::NONE, - egui::Event::WindowFocused(true) => self.refresh_installed_fonts(true), - _ => {} - } - } - // Keys a floating panel's own OS window left over run here, as if typed in this window, - // under the modifiers held there for this frame only. - if std::mem::take(&mut self.forwarded_modifiers_held) { - raw.events.insert(0, egui::Event::ModifiersChanged(self.host_modifiers)); - } - self.forwarded_frame = !self.forwarded.is_empty(); - self.forwarded_clipboard = self.forwarded.iter().any(|e| matches!(e, egui::Event::Copy | egui::Event::Cut)); - self.forwarded_presses = self.forwarded.iter().filter(|e| matches!(e, egui::Event::Key { pressed: true, .. })).cloned().collect(); - if !self.forwarded.is_empty() { - if let Some(m) = self.forwarded_modifiers.take() { - raw.events.push(egui::Event::ModifiersChanged(m)); - self.forwarded_modifiers_held = true; - } - raw.events.append(&mut self.forwarded); - } - // The previous pass settled: the batch it took is done, so the next step may go. - if self.injected_settled.swap(false, Ordering::Relaxed) { - self.acknowledge_injected_batch(); - } - self.discard_stale_injected_batch(raw); - // While the previous batch is unapplied (it lives in eframe's pending raw input), inject - // nothing more: one step per settled UI pass, not per hidden logic tick. - if self.synthetic_injected { - return; - } - let Some(first) = self.synthetic.first() else { - if std::mem::take(&mut self.synthetic_modifiers) { - raw.events.push(egui::Event::ModifiersChanged(self.host_modifiers)); - } - return; - }; - // Pointer events go one per frame so egui sees presses, drags and releases as real input; - // keyboard sequences go up to the key release. - let n = match first { - egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. } => 1, - _ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1), - }; - let (now, later) = self.synthetic.split_at(n.min(self.synthetic.len())); - let mut batch: Vec = Vec::with_capacity(n + 2); - if let egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } = first { - batch.push(egui::Event::PointerMoved(*p)); - } - // This frame's key or button, else the button a drag holds down (released later). - let held = now - .iter() - .find_map(|e| match e { - egui::Event::Key { modifiers, .. } | egui::Event::PointerButton { modifiers, .. } | egui::Event::MouseWheel { modifiers, .. } => { - Some(*modifiers) - } - _ => None, - }) - .or_else(|| match later.iter().find(|e| matches!(e, egui::Event::PointerButton { .. })) { - Some(egui::Event::PointerButton { pressed: false, modifiers, .. }) => Some(*modifiers), - _ => None, - }); - match held { - Some(m) => { - batch.push(egui::Event::ModifiersChanged(m)); - self.synthetic_modifiers = true; - } - None if std::mem::take(&mut self.synthetic_modifiers) => batch.push(egui::Event::ModifiersChanged(self.host_modifiers)), - None => {} - } - batch.extend(now.iter().cloned()); - // `batch` holds the n drained events plus the pointer/modifier companions that make the - // step read like real input. - self.synthetic.drain(..n); - self.injected_generation = self.input_generation(); - self.injected_events = batch.clone(); - self.synthetic_injected = true; - self.synthetic_frame = true; - raw.events.extend(batch); + shortcuts::follow_holds(self, ctx); } } diff --git a/crates/ui-egui/src/app/tests.rs b/crates/ui-egui/src/app/tests.rs new file mode 100644 index 0000000000..d6abbe6ca1 --- /dev/null +++ b/crates/ui-egui/src/app/tests.rs @@ -0,0 +1,78 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use craft::ui::dialog::UnsavedChangesDialog; +use craft::ui::shell::embed::{self, CloseDecision}; +use craft::ui::testing::Fixture; +use serde_json::json; +use vectorcraft_engine::Session; + +use crate::{Services, VectorcraftApp}; + +/// An app with one Letter document open. +fn app_with_a_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.session.add_document(vectorcraft_doc::Document::new(612.0, 792.0), None); + app.sync_views(); + app +} + +/// The smoke trial: a debug assert or a panic anywhere in the whole frame (the shell, the dock, +/// the canvas, the dialogs and the messages) shows only when the whole window runs, which no +/// component trial does. +#[test] +fn the_whole_window_shows_for_three_frames() { + let app = Rc::new(RefCell::new(app_with_a_document())); + let shown = Rc::clone(&app); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().ui(ui)); + crate::testing::install(fixture.ctx()); + let host = app.borrow().host.clone(); + fixture.room(egui::vec2(1440.0, 900.0)).host(host); + for _ in 0..3 { + app.borrow_mut().tick(fixture.ctx()); + fixture.frame(Vec::new()); + } + let area = app.borrow().canvas.windows.area; + assert!(area.is_some_and(|r| r.width() > 0.0 && r.height() > 0.0), "the document got no room in the window: {area:?}"); +} + +/// One frame in which the OS asks the root window to close: the app draws its pass, then the +/// close path of `embed::logic` asks it what to do. Gives the decision the app made, `None` when +/// the close path did not ask. +fn close_frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option { + let mut raw = egui::RawInput::default(); + raw.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + let mut decision = None; + let _ = ctx.run_ui(raw, |ui| { + app.ui(ui); + embed::logic(ui.ctx(), || { + let answer = app.close_decision(); + decision = Some(answer); + answer + }); + }); + decision +} + +/// Whether the window's dialog host shows the Unsaved Changes question. +// PLAN: assumed shell-w15's `unsaved::close_all` opens `UnsavedChangesDialog` itself on the window's host (the sheet's Tests row names it). +fn asks_about_unsaved(app: &VectorcraftApp) -> bool { + app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some())) +} + +/// The window's close asks about unsaved documents instead of closing the window: with a modified +/// document the window stays while the Unsaved Changes question shows; with nothing to ask it +/// closes. +#[test] +fn the_close_caption_asks_about_unsaved_documents() { + let ctx = crate::testing::ui_context(); + let mut app = app_with_a_document(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + assert_eq!(close_frame(&mut app, &ctx), Some(CloseDecision::Hold)); + assert!(asks_about_unsaved(&app), "the close asks about the modified document"); + + let ctx = crate::testing::ui_context(); + let mut app = app_with_a_document(); + assert_eq!(close_frame(&mut app, &ctx), Some(CloseDecision::Close)); + assert!(!asks_about_unsaved(&app), "nothing unsaved, nothing asked"); +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6e1d229023..e5625418ff 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -1,4 +1,12 @@ -use super::{canvas, cursors, render_worker}; +use std::rc::Rc; +use std::sync::Arc; +use std::time::SystemTime; + +use serde_json::Value; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{Point, Vec2}; + +use super::{canvas, render_worker}; /// Cached canvas raster. pub struct CanvasCache { @@ -52,12 +60,9 @@ pub struct CanvasCache { /// The words Edit › Spelling › Auto Spell Check underlined on each text object in the last /// frame; dropped while it is off. pub spelling: canvas::SpellingMarks, - /// The selected objects' outlines, anchors and handles as drawn in the last frame. A frame that - /// does not draw them drops them ([`canvas::show`]). - pub selection_marks: canvas::SelectionMarks, - /// The meshes the tools' shared paths (a long Blob Brush or Eraser drag's settled outline) were - /// drawn with in the last frame. A frame that does not draw them drops them ([`canvas::show`]). - pub shared_paths: canvas::SharedPaths, + /// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between + /// passes; the tool adapter takes it out for its call and puts it back. + pub momentary: Option, /// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and /// Measure Type by Glyph Bounds). pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, @@ -77,27 +82,100 @@ pub struct CanvasCache { /// [`CacheKey::plugins`] by document uid, with the plug-in revision /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. pub plugin_keys: std::collections::HashMap, - /// [`CacheKey::placed`] by document uid ([`canvas::placed_key`]). + /// [`CacheKey::placed`] by document uid ([`canvas::raster::placed_key`]). pub placed_keys: std::collections::HashMap, - /// The tools' cursors as OS cursor bitmaps. - pub cursors: cursors::Images, /// The view the canvas last drew and when it last changed (egui's input time): while it moves, /// the canvas doesn't hit-test the art under the pointer ([`canvas::hover_wait`], #2452). pub view_moved: Option<(canvas::ViewKey, f64)>, - /// The cursor the active tool last gave over the canvas, with the tool and the modifier keys - /// it was for: kept while the view moves. - pub hover_cursor: Option<(&'static str, vectorcraft_tools::Mods, vectorcraft_tools::Cursor)>, - /// In Presentation Mode, the canvas rect the active artboard was last fitted to: it is fitted - /// again when the rect changes (the window going full screen). - pub presented: Option, - /// The canvas a document's opening view was fitted to, with the view the fit gave. The window's - /// layout can still move the canvas's edges over the next frames, so until the view is moved or - /// the user acts, the opening view is fitted again when the canvas changes ([`canvas::show`]). - pub opening_fit: Option, /// Window › Arrange › Tile: the renders the panes of the other documents draw. pub panes: canvas::Panes, /// Window › Arrange › Float in Window: what the floating document windows keep between frames. pub windows: crate::doc_windows::Windows, + /// Whether the selection holds images beside other art, for (document uid, revision): the + /// Contextual Task Bar reads it every frame. + pub images_with_other_art: Option<((u64, u64), bool)>, + /// Whether the Smooth tool can work on the selection's paths, for (document uid, revision). + pub smooth_paths: Option<((u64, u64), bool)>, + /// Whether the selection mixes colours, for (document uid, revision): the Properties panel's + /// Recolor row reads it. + pub multi_color: Option<((u64, u64), bool)>, + /// How many objects Start Global Edit would edit, for the key the Properties panel builds. + pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>, + /// The selected live shape's angle, for (document uid, revision, kind of shape). + pub shape_angle: Option<((u64, u64, std::mem::Discriminant), Option)>, + /// The Image Trace presets, for the session's preset revision. + pub(crate) trace_presets: Option<(u64, Arc)>, + /// What the Image Trace panel traces, for (document uid, revision). + pub(crate) trace_target: Option<((u64, u64), Arc)>, + /// The Attributes panel's values and whether they apply, for the panel's key. + pub(crate) attributes_info: Option<(crate::panels::attributes::AttrKey, (crate::panels::attributes::AttributesInfo, bool))>, + /// The SVG Interactivity panel's values, for the panel's key. + pub(crate) svg_info: Option<(crate::panels::svg_interactivity::SelKey, crate::panels::svg_interactivity::Info)>, + /// The CSS Properties panel's code, for the panel's key. + pub(crate) css_shown: Option<(crate::panels::css_properties::CssKey, Arc)>, + /// The SVG Options dialog's SVG code, for every input it reads (compared with `==`). + // PLAN: assumed `crate::dialogs::svg_options::SvgCodeKey` (op.A4 names the type, not its module; export-w10). + pub(crate) svg_code: Option<(crate::dialogs::svg_options::SvgCodeKey, Arc)>, + /// The Export for Screens dialog's artboard thumbnails, for (document uid, revision). + pub artboard_thumbs: Option<((u64, u64), Vec>)>, + /// The families the document uses, for the document's fonts key. + pub document_families: Option<(FontsKey, Arc<[String]>)>, + /// The families installed lately: the font generation, when it was asked, the families and + /// the newest install time among them. + pub recently_added: Option<(u64, SystemTime, Arc<[String]>, Option)>, + /// The kerning at the Type tool's caret, for (document uid, revision, text object, byte). + pub caret_kerning: Option<((u64, u64, NodeId, usize), f64)>, + /// The alternates the Glyphs panel found at the selection. + pub(crate) glyphs_found: crate::panels::glyphs::Found, + /// The faces the Glyphs panel's positional forms come from: (document uid, revision, font + /// generation, the selection's object and range, the selected objects). + pub glyph_form_faces: Option<((u64, u64, u64, Option<(NodeId, usize, usize)>, Vec), Vec)>, + /// The selected characters' outlines on the page for the alternates row: (document uid, + /// revision, text object, range) to the quads and whether they are cut. + pub character_quads: Option<((u64, u64, NodeId, usize, usize), (Vec<[Point; 4]>, bool))>, + /// The Tabs panel's guide line, for (document uid, text object, paragraph, revision): layout is + /// too slow to run on every frame of a stop's drag. + // PLAN: assumed the axis `Option<(Point, Point, Vec2)>` of `panels::tabs::guide_axis` (type-w17 note; ty.S18 has no row for it). + pub tabs_guide_axis: Option<((u64, NodeId, usize, u64), Option<(Point, Point, Vec2)>)>, + /// The Appearance panel's summary of the selection, for (document uid, revision). + // PLAN: assumed key (document uid, revision) and `panels::appearance::Summary` (ap.AS1 names the cache, not its key). + pub(crate) appearance_summary: Option<((u64, u64), Option>)>, + /// The Transparency panel's values of the selection, for (document uid, revision). + // PLAN: assumed key (document uid, revision) and `panels::transparency::State` (appearance-w9's request names the field only). + pub(crate) transparency_state: Option<((u64, u64), Arc)>, + /// The Navigator's view region, for (document uid, revision, View Artboard Contents Only). + pub nav_region: Option<((u64, u64, bool), vectorcraft_geom::Rect)>, + /// The Document Info panel's values, for (document uid, revision, selection only, options). + pub doc_info: Option<((u64, u64, bool, Value), Value)>, + /// The Variables panel's rows, for the panel's key. + pub(crate) variable_rows: Option<(crate::panels::variables::RowsKey, Rc)>, + /// The Map Art surfaces of the 3D dialog's object. + pub map_surfaces: Option, + /// The command palette's built rows, for the palette's build key. + pub(crate) palette: Option<(crate::palette::BuildKey, Arc)>, +} + +/// [`CanvasCache::map_surfaces`]: the surfaces and what they were computed for. +pub type MapSurfacesCache = (MapSurfacesKey, Arc>); + +/// What the Map Art surfaces depend on: the document's version, the 3D object and the appearance +/// item, the effect and its parameters. Compared with `==`, never hashed. +#[derive(Clone, Debug, PartialEq)] +pub struct MapSurfacesKey { + /// The document's uid. + pub uid: u64, + /// The document's revision. + pub revision: u64, + /// The 3D object. + pub object: NodeId, + /// The appearance item the effect is on, when not the object's own. + pub item: Option, + /// The effect's index in its list. + pub index: Option, + /// The effect's id. + pub effect: String, + /// The effect's parameters. + pub params: Value, } /// [`CanvasCache::placed_keys`]: a document's [`CacheKey::placed`] and the placed-document bitmap @@ -195,7 +273,7 @@ pub struct CacheKey { /// Type › Highlight Substituted Fonts. pub highlight_substituted_fonts: bool, /// A [`vectorcraft_render::placed_document::generation`] that changes when the frame may show a - /// newly made bitmap of a placed document ([`canvas::placed_key`]). Bitmaps of files that only + /// newly made bitmap of a placed document ([`canvas::raster::placed_key`]). Bitmaps of files that only /// other documents hold leave it as it is, unless more bitmaps were made since the last check /// than are recorded and the document shows a placed document. pub placed: u64, diff --git a/crates/ui-egui/src/clock.rs b/crates/ui-egui/src/clock.rs deleted file mode 100644 index 3d3a504381..0000000000 --- a/crates/ui-egui/src/clock.rs +++ /dev/null @@ -1,25 +0,0 @@ -/// Seconds since the process started, from a monotonic clock (`web_time::Instant`, which maps to -/// `performance.now()` in the browser and `std::time::Instant` natively). Background work, poll -/// pacing and deadlines use this, not egui's `InputState::time`: a logic-only pass replays the -/// last shown frame's time, and a wall clock jumps with the system's. -pub fn now_secs() -> f64 { - #[cfg(not(target_arch = "wasm32"))] - { - use std::sync::LazyLock; - use std::time::Instant; - static START: LazyLock = LazyLock::new(Instant::now); - START.elapsed().as_secs_f64() - } - #[cfg(target_arch = "wasm32")] - { - use std::sync::LazyLock; - use web_time::Instant; - static START: LazyLock = LazyLock::new(Instant::now); - START.elapsed().as_secs_f64() - } -} - -/// [`now_secs`] in milliseconds, for frame timing and capture deadlines. -pub fn now_ms() -> f64 { - now_secs() * 1000.0 -} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..12b39c8438 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,10 +8,10 @@ /// VectorCraft 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.vectorcraft.png")), accent: Some([0xe8, 0x57, 0x3f]), - ..craft_update::suite::VECTORCRAFT + ..craft::update::suite::VECTORCRAFT }; /// Translate a UI string literal into the language the UI is drawn in (see [`i18n`]). @@ -27,7 +27,6 @@ pub mod background; mod brand; pub mod canvas; pub mod chrome; -mod clipboard_probe; pub mod community; pub mod control; pub mod credits; @@ -38,7 +37,10 @@ pub mod display_profile; pub mod doc_windows; pub mod dock; mod edit_toolbar; +mod edits; pub mod export_progress; +mod fields; +mod file_asks; pub mod find_font; pub mod font_menu; mod frame_rate; @@ -48,20 +50,20 @@ pub mod hang_beacon; pub mod i18n; pub mod icon_data; pub mod icons; -pub(crate) mod ime; pub mod io; pub mod keymap; pub mod layout_migration; pub mod menus; -pub mod native_menu; pub mod opening; mod original_editor; #[doc(hidden)] pub use original_editor::Choice as OriginalEditorChoice; +mod page_glyphs; +mod paint_preview; pub mod palette; mod panel_docking; +mod panel_drag; pub mod panels; -pub mod picks; pub mod place; pub mod placing; pub mod plugin_runs; @@ -72,7 +74,7 @@ pub mod render_worker; pub mod screen_color; pub mod script_runs; pub mod scripts_menu; -mod scrub; +mod settings; pub mod shortcut_editor; pub mod shortcut_sheet; pub mod shortcuts; @@ -81,59 +83,52 @@ pub mod stylus; pub mod sysclip; pub mod theme; pub mod thumb_worker; -pub mod titlebar; -pub mod toasts; pub mod toolbar; -mod tools_float; pub mod touch; pub mod trace_runs; pub mod troubleshooting; +mod type_editing; mod ui_fonts; pub mod unsaved; pub mod updates_ui; -pub mod widgets; pub mod workspaces; -mod document_drag; #[cfg(test)] use tests::{ background as tests_background, folder as tests_folder, labels as tests_labels, picks as tests_picks, removeanchors as tests_removeanchors, svg as tests_svg, synthetic as tests_synthetic, sysclip as tests_sysclip, }; #[cfg(test)] +mod testing; +#[cfg(test)] mod tests; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::collections::HashMap; use std::sync::mpsc::Receiver; use std::sync::{Arc, Mutex}; +use craft::automation::{Captures, ControlChannel, ControlRequest}; +use craft::behavior::GestureId; +use craft::host::Host; +use craft::ui::runtime::overlay::{self, OpenFilter}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::file_access::{self, AutomationRoots}; -use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_engine::{Session, UndoScope, ViewInfo}; -pub use control::{ControlRequest, ControlResponse, Ticket as ControlTicket}; +pub use settings::{AppSettings, from_app, parse_legacy}; pub use state::{UiState, View}; -pub use sysclip::{CLIPBOARD_PROBE_STOP_WAIT, ClipboardProbeFactory, ClipboardRead, MakeFlavour, SystemClipboard}; mod app; mod caches; -mod clock; mod services; pub use app::MAX_RECENT_FONTS; pub use caches::{CacheKey, CanvasCache, LivePaintGapsCache, Perf, PlacedKey, PrintTilingCache, SliceCache}; -pub use clock::{now_ms, now_secs}; -pub use craft_ui::docking::Monitor as DockMonitor; #[cfg(test)] pub(crate) use services::browsable_url; -pub use services::{ - DownloadFn, ExistsFn, FileFilter, FilePick, Inbox, NativeInputHook, OpenUrlFn, PickOpen, PickSave, PickedInbox, ReadFn, RevealFn, SaveStreamFn, - SaveWriteFn, Services, WriteFn, -}; -use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; -pub(crate) use state::{InputFrame, take_frame_once}; -pub use ui_fonts::on_missing_glyphs; +pub use services::{DownloadFn, ExistsFn, Inbox, NativeInputHook, ReadFn, SaveStreamFn, SaveWriteFn, Services, WriteFn}; +pub use ui_fonts::ui_fonts; pub struct VectorcraftApp { pub session: Session, @@ -143,14 +138,20 @@ pub struct VectorcraftApp { /// [`VectorcraftApp::sync_views`], which puts the views back with their documents after /// `document.move` reorders them (#5663). pub(crate) view_uids: Vec, - /// The thread that checks the system clipboard for `system_paste` instead - /// ([`Services::clipboard_probe`]). It is declared before `services` so that it is dropped - /// first, waiting up to [`CLIPBOARD_PROBE_STOP_WAIT`] for its thread to let go of its handle: on - /// X11 the last clipboard handle alive hands what the app copied to the clipboard manager, and - /// that should be the app's own handle in `services`, dropped on the UI thread before the - /// process exits. - clipboard_probe: Option, + /// The thread that checks the system clipboard for `system_paste` ([`Services::clipboard_probe`]). + /// It is declared before `clipboard` so that it is dropped first: on X11 the last clipboard + /// handle alive hands what the app copied to the clipboard manager, and that should be the + /// app's own handle in `clipboard`, dropped on the UI thread before the process exits. + clipboard_probe: Option, + /// The system clipboard: the host's backend, or one that keeps copies inside the app. + pub clipboard: craft::platform::clipboard::Clipboard, + /// The host reads the system clipboard's rich formats itself (`Services::clipboard` was given): + /// Copy publishes SVG, PDF and the rest beside the text. + pub(crate) rich_clipboard: bool, pub services: Services, + /// The app's services as the framework reads them (language, catalogs, jobs, files), handed + /// to every frame in [`Self::frame_input`]. + pub host: Arc, pub canvas: CanvasCache, /// The main window's display profile, which the canvas is drawn through /// ([`display_profile`]); the desktop app reports what it reads into it. @@ -165,62 +166,31 @@ pub struct VectorcraftApp { pub last_effect: Option<(String, serde_json::Value)>, /// Last successful destructive Pathfinder operation, repeated on the current selection. pub last_pathfinder: Option, - /// Last confirmed Warp Options (bend, distortion, orientation) for the next new warp dialog. - pub last_warp: Option, /// The Character panel field that takes the keyboard focus when the panel next draws it /// ([`panels::character::highlight`]). pub(crate) character_focus: Option, /// Commands run through [`Self::run`] so far: the native menu bar reads its rows again when it - /// moves ([`native_menu::sync`]). + /// moves ([`menus::native::sync`]). run_count: u64, - control_rx: Option>, - /// A `ui.pointer` request taken from the channel while synthetic input sent before it was not - /// yet applied: it runs, ahead of the channel, on the first frame after that input is applied. - deferred_control: Option, - /// When synthetic input was last dropped before a UI pass took it, the sequence number of the - /// next control request ([`ControlRequest::next_seq`]): a `ui.pointer` request made before it - /// came after that input and is answered with an error. - synthetic_dropped_before: u64, - /// Window captures asked for and not answered yet. - pending_screenshots: Vec, - /// `ui.pointer` replies waiting for their events and the edit the tool computes on another - /// thread ([`control::Outcome::AfterToolEdit`]), with the numbers of those events. - pointer_replies: Vec, - /// Admitted captures whose settled frame has not come yet (issued one at a time). - queued_screenshots: Vec, - screenshot_token: u64, - /// Bytes reserved by admitted captures (checked `width * height * 4`). - screenshot_reserved: usize, - /// Synthetic input events (from the control channel) injected one step per frame. - pub synthetic: Vec, - styled: bool, - fonts_ready: bool, + /// The control channel's requests and their replies, while the host opened one. + // PLAN: an `Option` because `new` has no receiver; shell-w12's `run_control` reads `self.channel` as one. + pub(crate) channel: Option, + /// The window captures the control channel asked for. + pub(crate) captures: Captures, /// The egui context the UI's textures were uploaded to (0: none yet; see /// [`Self::adopt_context`]). context: u64, - /// The current context, for the focus part of an injected batch's generation (set by - /// [`Self::adopt_context`]). + /// The current context (set by [`Self::adopt_context`]): the dialogs, the overlays and the + /// window host are read through it. ui_ctx: Option, - /// Installed fonts added to the UI's for characters its own fonts lack (CJK names…). - ui_fonts: ui_fonts::UiFonts, pub(crate) updates_rt: updates_ui::Runtime, /// The status bar's frame rate ([`frame_rate`]). frame_rate: frame_rate::FrameRate, - /// Canvas rect of the last frame (screen points), for control-channel coordinate mapping. - pub canvas_rect: Option, - /// The UI zoom (egui's zoom factor, set by Preferences › User Interface › UI Scaling) of the - /// frame that laid out [`Self::canvas_rect`]; 1.0 before the first one. [`Self::canvas_xf`] - /// maps the document to that rect with it. - pub(crate) canvas_ui_zoom: f32, - /// An unfinished control-channel Rotate View gesture, kept only for this app instance. - pub(crate) control_rotate_press: Option, /// Hover position in document coordinates. pub hover_doc: Option, - /// System clipboard: SVG to publish next frame, the last SVG we published (so pasting it back - /// uses the lossless internal clipboard) and what came with a paste (a Paste event's text, a - /// picture or file the host read: [`Self::paste_from_host`]). + /// Text to copy to the system clipboard next (`flush_clipboard_out`) and what came with a + /// paste (a Paste event's text, a picture or file the host read: [`Self::paste_from_host`]). clipboard_out: Option, - clipboard_published: Option, pub(crate) clipboard_in: Option, /// The Copy or Cut whose formats go to the system clipboard ([`Self::publish_clipboard`]). clipboard_publishing: sysclip::Publishing, @@ -230,29 +200,11 @@ pub struct VectorcraftApp { /// Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while /// it is set. `false` unless the host sets it. pub titlebar_from_env: bool, - /// Windows and Linux: the window has no OS decorations, so the app bar is the title bar (drag, - /// double-click to maximize, caption buttons) and invisible edge zones resize the window. - pub custom_titlebar: bool, - /// Where the caption buttons go on the app bar while [`Self::custom_titlebar`] is on: the - /// desktop's window-button layout on Linux and the BSDs where the desktop leaves the frame to the - /// app, all three at the right otherwise. - pub caption_layout: titlebar::CaptionLayout, - /// The window has the desktop's own title bar: the OS or the window manager draws its frame, - /// icon and title. Set by the desktop app when it opens the window; `false` for embedders - /// without a window of their own. - pub desktop_frame: bool, /// Linux and the BSDs: `VECTORCRAFT_TITLEBAR` is unset and the desktop would draw the window's /// frame on this session with Preferences › User Interface › System Title Bar on or off while /// VectorCraft Title Bar on Every Desktop is off, so the dialog says so under System Title Bar. - /// It stays `true` while VectorCraft Title Bar on Every Desktop gives the app the frame. Set by - /// the desktop app when it opens the window; `false` elsewhere. + /// Set by the desktop app from the frame decision when it opens the window; `false` elsewhere. pub desktop_keeps_frame: bool, - /// Last window title sent to the OS (`ViewportCommand::Title`, see `chrome::sync_window_title`): - /// sent again only when it changes, so idle frames don't spam the backend. - pub(crate) last_window_title: String, - /// Whether a screen mode put the window full screen (`chrome::sync_fullscreen`), so Normal - /// Screen Mode takes it back out, and leaves a window the user made full screen as it is. - pub(crate) fullscreen_for_mode: bool, /// The graphics adapter the window renders with ("name (backend)"), as the host reports it: /// shown in Help › About and `ui.inspect` for GPU bug reports. `None` when unknown. pub graphics_adapter: Option, @@ -262,8 +214,7 @@ pub struct VectorcraftApp { /// File → Place: picked files, the place cursor's thumbnails, the Control bar's image details. pub place: place::PlaceState, /// The Paste commands can paste from the system clipboard alone: it holds something to paste - /// (SVG without a `system_clipboard`) while the internal clipboard is empty. It enables the - /// Paste menu items. + /// while the internal clipboard is empty. It enables the Paste menu items. pub(crate) system_paste: bool, /// The modifiers held when an egui `PasteImage` asked the rich system clipboard to be read. /// Consumed once by the next `tick`; storing the paste-time chord keeps a later pass's stale @@ -271,22 +222,20 @@ pub struct VectorcraftApp { pub(crate) clipboard_image_request: Option, /// When `system_paste` was last checked in line (app time, s; at most once per frame). system_paste_at: f64, - /// File dialogs shown off the UI thread and what runs again with their answers. - pub(crate) picks: picks::Picks, + /// File dialogs shown off the UI thread, what runs again with their answers, and the replace + /// questions. + pub(crate) file_asks: file_asks::FileAsks, + /// The saves in progress, one flow per document. + pub(crate) saves: io::save::Saves, pub(crate) original_editor: original_editor::Draft, - /// The screen color sampler shown and not answered yet, and where its color goes. - pub(crate) screen_sampler: Option, - /// The look for fonts installed or removed meanwhile, running - /// ([`Self::refresh_installed_fonts`]): whether they were, and whether to wake the app for - /// the answer. - font_check: Option<(std::sync::mpsc::Receiver, bool)>, - /// When installed fonts were last checked in line (app time, s). - #[cfg(not(target_arch = "wasm32"))] - font_install_check_at: f64, - /// Keyboard pastes of something other than text (see [`shortcuts::PasteChord`]). - pub(crate) paste_chord: shortcuts::PasteChord, - /// Runs the frame's key presses against the keymap ([`shortcuts::handle`]). - pub(crate) dispatcher: craft_keymap::egui::Dispatcher, + /// The screen colour picker: the pick in progress and where its colour goes. + pub(crate) screen_pick: craft::color_ui::ui::ScreenPick, + /// The font catalog's watch for fonts installed or removed while the app runs. + pub(crate) font_watch: Option, + /// The font catalog generation the documents' fonts were last scanned again for. + pub(crate) fonts_seen: u64, + /// The font menu whose live preview the canvas shows, while one does. + pub(crate) font_preview_owner: Option, /// Saves and exports running in the background (Preferences → File Handling). pub background: background::Background, /// Documents being read off the UI thread ([`opening`]). @@ -297,66 +246,90 @@ pub struct VectorcraftApp { pub placing: placing::Placing, /// Image Traces running off the UI thread ([`trace_runs`]). pub trace_runs: trace_runs::TraceRuns, - /// The messages shown over the window ([`toasts`]). - pub toasts: toasts::Shown, /// Data Recovery's timer and startup question ([`recovery`]). pub recovery: recovery::Timer, - /// Modifiers the keyboard holds (from the host's input), given back after synthetic input. - host_modifiers: egui::Modifiers, - /// Key, text and clipboard events a floating panel's own OS window forwarded, for the main - /// window's next frame ([`Self::raw_input_hook`]), and the modifiers held in that window. - pub(crate) forwarded: Vec, - pub(crate) forwarded_modifiers: Option, - /// The last frame held the forwarded modifiers: this one goes back to the keyboard's. - forwarded_modifiers_held: bool, - /// This host iteration's input carries forwarded keys: they are the main window's although - /// its OS window doesn't have the keyboard (see `shortcuts::handle`). - pub(crate) forwarded_frame: bool, - /// The forwarded keys of this host iteration hold a Copy or Cut: it copies the art, not text - /// selected in this window's labels (see `shortcuts::handle_clipboard`). - pub(crate) forwarded_clipboard: bool, - /// The key presses among this host iteration's forwarded keys: a Copy or Cut one of them runs - /// (F3 and F2 off macOS) copies the art, not text selected in this window's labels (see - /// `shortcuts::clipboard_key_to_labels`). - pub(crate) forwarded_presses: Vec, - /// Synthetic input set the modifiers egui holds (see [`Self::raw_input_hook`]). - synthetic_modifiers: bool, + /// The Close, Close All or Quit in progress, which asks about each unsaved document in turn. + pub(crate) closing: Option, + /// The Preferences window, while it is open. + pub(crate) prefs: Option>, + /// The preferences the interface last applied, to apply only what changed. + pub(crate) applied_prefs: Option, + /// The menu bar's model and the command states the frame publishes. + pub(crate) menus: menus::model::Menus, + /// The Keyboard Shortcuts dialog, while it is open. + // PLAN: assumed `crate::shortcut_editor::ShortcutsDialogState` (kb.C27 names the type, not its module; shortcuts-w8). + pub(crate) shortcuts_dialog: Option, + /// The bindings the active shortcut set changes, as the key stage takes them: rebuilt from + /// [`UiState::shortcut_sets`] when the set changes. + pub(crate) shortcut_overrides: Arc, + /// Messages waiting for the dialog that shows them. + pub(crate) told: dialogs::Told, + /// The hosted dialogs whose OK the app answers, one record each. + pub(crate) held: dialogs::host::Held, + /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one + /// step however many values it sets. + pub(crate) edit_scopes: HashMap, + /// The parameter dialog of a command, while one is open. + pub(crate) command_dialog: dialogs::command::CommandDialog, + /// The open dialogs of the Effect menu. + pub(crate) effect_dialogs: dialogs::effect::EffectDialogs, + /// The 3D and Materials dialog, while it is open. + pub(crate) three_d_dialog: Option, + /// The 3D and Materials panel's model. + pub(crate) three_d: panels::three_d::Model, + /// The open export option dialogs and what runs after each. + pub(crate) export_dialogs: dialogs::export_host::ExportDialogs, + /// Save for Web's renders and colour table. + pub(crate) web_export: dialogs::save_for_web::WebExport, + /// The Flattener Preview panel's model. + pub(crate) flattener_preview: panels::flattener_preview::FlattenerPreviewModel, + /// The Flatten Transparency dialog's record. + pub(crate) flatten_dialog: dialogs::flatten::FlattenDialog, + /// The Print dialogs' records. + pub(crate) print_dialog: dialogs::print::PrintDialogs, + // PLAN: export-w17 asks for the open Save PDF record's field (ex.A12), but no row in this set's bundle gives its name or type; export-w17 adds it. + /// The open dialogs of the Object menu. + pub(crate) object_dialogs: dialogs::object_dialogs::ObjectDialogs, + /// The open tool option dialogs. + // PLAN: assumed `crate::dialogs::tools::ToolDialogs` (sheet note 5 names the field only; object-dialogs-w5 owns dialogs/tools.rs). + pub(crate) tool_dialogs: dialogs::tools::ToolDialogs, + /// The open dialogs of the colour area. + pub(crate) color_dialogs: dialogs::color_picker::ColorDialogs, + /// The plug-in dialog, while one is open. + pub(crate) plugin_dialog: Option, + /// The add-on panels' session state. + pub(crate) addon_panels: addons::Panels, + /// The add-on dialogs' records. + pub(crate) addon_dialogs: addons::dialogs::AddonDialogs, + /// Check Spelling's walk through the documents' type, while its dialog is open. + pub(crate) spelling: Option, + /// The Character Style Options dialog's live preview. + pub(crate) char_style_preview: dialogs::preview::LivePreview, + /// The Paragraph Style Options dialog's live preview. + pub(crate) para_style_preview: dialogs::preview::LivePreview, + /// The Justification dialog, while it is open. + pub(crate) justification: Option, + /// The Bullets and Numbering dialog's live preview. + pub(crate) bullets_preview: dialogs::preview::LivePreview, + /// The paste that waits for the answer to its colour profile question. + // PLAN: assumed `crate::dialogs::profile_mismatch::PasteAsk` (fl.A16 names the type, not its module; files-w11). + pub(crate) pending_paste: Option, + /// The missing links' questions, while they are asked. + pub(crate) link_asks: Option, /// The marked text the system IME last sent (`None` once it commits or clears). When the Type /// tool stops composing on its own (a click, a tool switch), the IME is told to drop it. pub(crate) ime_marked: Option, /// Owner/generation/change-cause bookkeeping for the outgoing IME surrounding-text producer - /// (one tracker serves every viewport; see the crate's IME producer module). + /// (one tracker serves every viewport). pub(crate) ime_context: egui::ime_context::ImeContextTracker, - /// Incoming composition ownership is separate from outgoing receipt/generation bookkeeping. - /// Interrupted input stays stale until the exact request-bound native fence arrives. - pub(crate) ime_compositions: egui::ViewportIdMap, - pub(crate) ime_resets: egui::ViewportIdMap, - /// The Type tool's IME caret geometry for this pass, recorded by the canvas. The descriptor - /// itself is written at the end of the pass ([`ime::end_of_pass`]), after dialogs, floating - /// panels and the palette, because any of them can move the owner, edit the text or cover the - /// canvas after the canvas drew. - pub(crate) ime_caret_rect: Option<(egui::Rect, egui::Rect)>, - /// The IME must drop its marked text (see [`Self::take_ime_discard`]). - pub(crate) ime_discard: bool, /// Preferences were confirmed (see [`Self::take_prefs_changed`]). pub(crate) prefs_changed: bool, - /// The export presets the Asset Export panel lists (`document.exportPresets.list`'s rows), built - /// again when the saved presets change ([`dialogs::screen_preset_list`]). - pub(crate) asset_export_presets: Value, /// Whether the last frame's input reported a touch screen (Preferences › Devices › Touch Workspace). pub touch_screen: bool, - /// A numeric field is being scrubbed: the document's edits meanwhile are one undo step - /// ([`scrub::begin_frame`]). - scrub_group: bool, - /// The undo step of the scrub in progress ([`vectorcraft_engine::Session::begin_undo_scope`]). - scrub_scope: Option, /// The folders control requests, and the input they inject, may read and write /// (`--automation-read-root`, `--automation-write-root`); `None`: anywhere. See /// [`Self::with_automation_roots`]. automation_roots: Option>, - /// This frame carries input the control channel injected ([`Self::raw_input_hook`]): it runs - /// confined to [`Self::automation_roots`]. - synthetic_frame: bool, /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, @@ -366,53 +339,37 @@ pub struct VectorcraftApp { /// Files File › Open read while another one's profile question was open, each asking its own /// question in turn. pub(crate) queued_profile_opens: std::collections::VecDeque, - /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which - /// `ui.dialog.set` writes. - pub(crate) script_picked: Vec, - /// Choose… left out files past the most a script is given. - pub(crate) script_picked_left_out: bool, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, - /// Host iterations (full or logic-only), advanced once in [`Self::begin_host_iteration`]. - pub(crate) host_iteration: u64, - /// A test's clock for [`Self::tick`], replacing the monotonic [`now_secs`] so idle scheduling - /// can be driven one simulated frame at a time (production always leaves this `None`). + /// A test's clock for [`Self::tick`], replacing the monotonic clock so idle scheduling can be + /// driven one simulated frame at a time (production always leaves this `None`). #[cfg(test)] pub(crate) now_override: Option, /// An error the next tool choice returns before the engine sees it ([`Self::try_select_tool`]), /// so tests can drive a failed switch (production has no such field). #[cfg(test)] pub(crate) fail_next_tool_choice: Option, - /// The host iteration [`Self::tick`] ran in (`None`: never): once per iteration, never per pass. - tick_iteration: Option, - /// The context, viewport and frame whose UI-phase input was already taken in this host - /// iteration: a discarded rerun and a second viewport pass must not replay a frame's events. - input_frames: Vec, - /// The context, viewport and frame `shortcuts::handle` already took in this host iteration. - /// Interleaving root and auxiliary viewport passes cannot make an older frame look new again. - pub(crate) shortcuts_frames: Vec, /// The single-key tool shortcuts held down, the last held last, and the tool each goes back to /// when it is let go ([`shortcuts::HeldTool`]). pub(crate) held_tool: Vec, - /// Alt held down on its own since a frame saw it go down ([`shortcuts::AltTap`]). - pub(crate) alt_tap: shortcuts::AltTap, - /// A key with a hold shortcut that waits for its release, and the keys whose repeats are held - /// back until they are let go ([`shortcuts::HoldKeys`]). - pub(crate) hold_keys: shortcuts::HoldKeys, - /// A synthetic batch is in the host's raw input and no settled UI pass has taken it yet. - synthetic_injected: bool, - /// The exact events of [`Self::synthetic_injected`], to remove them if the state they belong - /// to changed before a UI pass could take them. - injected_events: Vec, - /// The document, dialog and focus an injected batch belongs to. - injected_generation: InputGeneration, - /// The end-of-pass observer was installed on the context. - injected_settle_hook: bool, - /// A settled UI pass consumed the injected batch (read by the next host iteration). - injected_settled: Arc, - /// A change of the window's content geometry (resize, DPI, zoom or surface), even back again. - geometry_epoch: u64, - /// The geometry stamp [`Self::geometry_epoch`] was last advanced for. - geometry_stamp: Option, +} + +impl VectorcraftApp { + /// Whether a layer that takes the keys (a modal dialog, a popup) showed in the last pass: a + /// command or a canvas gesture waits while one does. A modeless dialog blocks nothing, and the + /// job progress window does not count (its layer has the progress role). False before the app + /// has a context. + pub(crate) fn any_dialog_open(&self) -> bool { + self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, OpenFilter::Keys)) + } + + /// The background job service: the one the window's host installed, or jobs that run in line + /// before the app has a window (unit tests, the CLI). + pub(crate) fn jobs(&self) -> Arc { + match self.ui_ctx.as_ref().and_then(Host::try_of_ctx) { + Some(host) => host.jobs_shared().clone(), + None => Arc::new(craft::host::InlineJobs), + } + } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..59b819b34a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,5 +1,12 @@ //! Serializable UI state (read and driven by the control channel). +use std::collections::{BTreeSet, HashMap, HashSet}; + +use craft::behavior::canvas::{CanvasView, ZoomScheme}; +use craft::behavior::selection::Selection; +use craft::ui::canvas::ViewRequest; +use craft::ui::dialog::DialogId; +use craft::ui::shell::{RecentSort, RecentView, ScreenMode}; use serde::{Deserialize, Serialize}; use serde_json::Value; use vectorcraft_geom::Point; @@ -7,7 +14,7 @@ use vectorcraft_geom::Point; use crate::theme::Brightness; /// A one-shot Image Trace Ignore Color sampler, bound to the unchanged selected source. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct TraceIgnoreSampler { pub doc: u64, pub target: vectorcraft_doc::NodeId, @@ -16,11 +23,21 @@ pub struct TraceIgnoreSampler { } /// A Brush Options Key Color click, owned by its dialog and document until release or cancel. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct BrushKeyColorPick { pub doc: u64, pub back: String, - pub press: Option, + /// The Brush Options dialog the picked colour goes back to. + pub dialog: DialogId, +} + +/// How the canvas moves to a view the app set: eased from where it was, or at once. +#[derive(Clone, Copy, Debug)] +pub enum ViewMove { + /// The canvas eases from this view to the new one (Animated Zoom). + Ease(CanvasView), + /// The canvas jumps to the new view. + Jump, } /// Per-document view (camera). @@ -28,7 +45,7 @@ pub struct BrushKeyColorPick { pub struct View { /// The zoom (1.0 = 100%): points of the screen per document point, counted before /// Preferences › User Interface › UI Scaling, which scales the interface and not the art. - /// [`Self::screen_zoom`] is the zoom in the interface's points. + /// [`Self::canvas`] gives the zoom in the interface's points. pub zoom: f64, /// Document point at the centre of the canvas. pub center: Point, @@ -44,11 +61,31 @@ pub struct View { /// document opens in Preview. #[serde(default)] pub outline: bool, + /// The canvas on screen, inside the rulers, as the last pass laid it out (screen points). + #[serde(skip)] + pub rect: egui::Rect, + /// A view command or placement the canvas runs on its next pass, with the document area it + /// fits when the command fits one. + #[serde(skip)] + pub request: Option<(ViewRequest, Option)>, + /// How the canvas reaches the view the app last set ([`Self::set_canvas`] callers). + #[serde(skip)] + pub moved: Option, } impl Default for View { fn default() -> Self { - Self { zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, rotation: 0.0, artboard: 0, outline: false } + Self { + zoom: 1.0, + center: Point::new(306.0, 396.0), + fitted: false, + rotation: 0.0, + artboard: 0, + outline: false, + rect: egui::Rect::NOTHING, + request: None, + moved: None, + } } } @@ -70,22 +107,23 @@ impl View { center: v.center, fitted: true, rotation: if v.rotation.is_finite() { v.rotation } else { 0.0 }, - artboard: 0, - outline: false, + ..Self::default() }) } - /// The interface's points per document point when the interface is zoomed by `ui_zoom` (egui's - /// zoom factor, which Preferences › User Interface › UI Scaling sets). A document point then - /// covers the same device pixels at every UI Scaling. - pub fn screen_zoom(&self, ui_zoom: f32) -> f64 { - self.zoom / f64::from(ui_zoom) + /// The view as the canvas shows it in `area` while the interface is zoomed by `ui_scaling` + /// (Preferences › User Interface › UI Scaling): the zoom counts the interface's points, so a + /// document point covers the same device pixels at every UI Scaling. + pub fn canvas(&self, ui_scaling: f32, area: egui::Rect) -> CanvasView { + CanvasView::new(area, self.center, self.zoom / f64::from(ui_scaling)).rotation(self.rotation) } - /// This view with its zoom in the interface's points ([`Self::screen_zoom`]), as the canvas - /// renders it. - pub(crate) fn on_screen(&self, ui_zoom: f32) -> Self { - Self { zoom: self.screen_zoom(ui_zoom), ..*self } + /// Takes the view the canvas reports back, the inverse of [`Self::canvas`]. + pub fn set_canvas(&mut self, view: &CanvasView, ui_scaling: f32) { + self.center = view.center; + self.zoom = view.zoom * f64::from(ui_scaling); + self.rotation = view.rotation; + self.rect = view.rect; } } @@ -106,50 +144,32 @@ pub const ROTATE_VIEW_ANGLES: [(&str, f64); 12] = [ ("-90°", -90.0), ]; -use super::ControlResponse; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::Sender; - -/// Zoom stop stepping reads this (set each UI frame and before commands) so canvas wheel zoom -/// matches the status bar when Display Print Size at 100% Zoom is on. -static ZOOM_STOPS_PRINT_SIZE: AtomicBool = AtomicBool::new(false); - -pub fn sync_zoom_stops_display_print_size(v: bool) { - ZOOM_STOPS_PRINT_SIZE.store(v, Ordering::Relaxed); -} - -/// The preset zoom stops, in percent. -pub const ZOOM_STOPS: [f64; 26] = [ - 3.13, 4.17, 6.25, 8.33, 12.5, 16.67, 25.0, 33.33, 50.0, 66.67, 100.0, 150.0, 200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0, - 4800.0, 6400.0, 12800.0, 25600.0, 64000.0, -]; - /// Document zoom at 100% in the status bar: one screen point per document point, or with /// Preferences › General › Display Print Size at 100% Zoom, one document inch in 96 screen points. pub fn zoom_baseline(display_print_size: bool) -> f64 { if display_print_size { 96.0 / 72.0 } else { 1.0 } } +/// The zoom stops with 100% at [`zoom_baseline`]: the one scheme the status bar, the zoom +/// commands and the canvas step through. +fn zoom_stops(display_print_size: bool) -> ZoomScheme { + ZoomScheme::ILLUSTRATOR.with_hundred(zoom_baseline(display_print_size)) +} + +/// The zoom `z` as the status bar shows it, in percent of [`zoom_baseline`]. pub fn zoom_display_percent(z: f64, display_print_size: bool) -> f64 { - z / zoom_baseline(display_print_size) * 100.0 + zoom_stops(display_print_size).percent(z) } +/// The zoom the status bar's `pct` stands for. pub fn zoom_from_display_percent(pct: f64, display_print_size: bool) -> f64 { - pct / 100.0 * zoom_baseline(display_print_size) + zoom_stops(display_print_size).device(pct) } -pub fn next_zoom(z: f64, up: bool) -> f64 { - next_zoom_with_display(z, up, ZOOM_STOPS_PRINT_SIZE.load(Ordering::Relaxed)) -} - -pub fn next_zoom_with_display(z: f64, up: bool, display_print_size: bool) -> f64 { - let pct = zoom_display_percent(z, display_print_size); - let stop = if up { - ZOOM_STOPS.iter().find(|s| **s > pct + 0.01).copied().unwrap_or(64000.0) - } else { - ZOOM_STOPS.iter().rev().find(|s| **s < pct - 0.01).copied().unwrap_or(3.13) - }; - zoom_from_display_percent(stop, display_print_size) +/// The zoom stop after `z`, up or down, within the zoom range. The range has a fixed floor, so +/// the document's size does not enter. +pub fn next_zoom(z: f64, up: bool, display_print_size: bool) -> f64 { + zoom_stops(display_print_size).step(z, if up { 1 } else { -1 }, vectorcraft_geom::Size::ZERO) } /// Format for the tab/zoom field: up to 2 decimals, no trailing zeros. @@ -272,7 +292,7 @@ pub const ICON_PANEL_GROUPS: &[&[&str]] = &[ &["variables"], ]; -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ViewFlags { pub rulers: bool, /// View › Rulers › Show Video Rulers: while the rulers show, they count the active artboard in @@ -362,41 +382,9 @@ impl ViewFlags { } } -/// An open modal dialog. `fields` are string-valued so agents can set them uniformly. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Dialog { - pub kind: String, - pub fields: serde_json::Map, -} - -impl Dialog { - pub fn new(kind: &str, fields: Value) -> Self { - Self { kind: kind.to_string(), fields: fields.as_object().cloned().unwrap_or_default() } - } - pub fn f64(&self, k: &str, d: f64) -> f64 { - match self.fields.get(k) { - Some(Value::Number(n)) => n.as_f64().unwrap_or(d), - Some(Value::String(s)) => vectorcraft_doc::Unit::Points.parse(s).unwrap_or(d), - _ => d, - } - } - /// Field `k` as text: a string as it is, another value as JSON, empty when missing. - pub fn str(&self, k: &str) -> String { - match self.fields.get(k) { - Some(Value::String(s)) => s.clone(), - Some(v) => v.to_string(), - None => String::new(), - } - } - /// Field `k` as a bool; `false` when it is missing or not a bool. - pub fn bool(&self, k: &str) -> bool { - self.fields.get(k).and_then(Value::as_bool).unwrap_or(false) - } -} - /// The last Replace Font request whose warning the status bar shows, to refresh it as the /// document changes. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct ReplaceFontWarning { pub document_uid: u64, pub revision: u64, @@ -421,7 +409,7 @@ pub struct ContextSpelling { pub suggestions: Vec, } -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct UiState { /// The interface language older versions saved here (`ja`, `cs`…). It now lives in the @@ -430,30 +418,65 @@ pub struct UiState { #[serde(rename = "language", skip_serializing)] pub legacy_language: Option, pub brightness: Brightness, - /// The Print dialog's opt-in direct-PDF transport. UI-only and not serialized: the control - /// channel cannot enable a print that bypasses the printer driver. - #[serde(skip)] - pub print_direct_pdf: bool, - pub dock_tab: DockTab, - /// Tab order in the dock's tabbed group when it differs from [`DockTab::ALL`]. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub dock_tab_order: Vec, - /// The dock's tabbed group (Properties | Layers | Libraries) is collapsed to icons at the top of - /// the icon column (the dock's double arrow, `window.collapseDock`). - #[serde(default)] - pub dock_collapsed: bool, + /// The panel arrangement: docks, floating windows, closed panels and where each goes back. + #[serde(rename = "dock")] + pub dock_workspace: craft::behavior::dock::Workspace, + /// The tool each slot of the Tools panel showed last. + pub tools_last_used: craft::ui::rails::LastUsed, + /// The saved workspaces, the current one and the changes made in each since it was saved. + pub workspaces: crate::workspaces::Workspaces, + /// The panel fields of files from before the shared dock: read once to build + /// [`Self::dock_workspace`] ([`crate::layout_migration::migrate_ui`]), never written. + #[serde(flatten)] + pub legacy: LegacyDock, /// Icon panel currently popped out of the collapsed column (also `properties`, `layers` or /// `libraries` while the dock is collapsed). pub open_panel: Option, /// The panel a row's link opened as a popup (the Appearance panel's Stroke:, Character:, /// Opacity:…): it shows beside the Appearance panel at the clicked row until a press outside - /// it, Escape, or the panel showing elsewhere puts it away - /// ([`crate::panels::appearance::row_popup`]). + /// it, Escape, or the panel showing elsewhere puts it away. #[serde(skip)] pub transient_panel: Option, - /// That popup's first text field is still to take the keyboard. + /// The Appearance panel's rows and selection, kept while the app runs. #[serde(skip)] - pub transient_focus: bool, + pub appearance_panel: crate::panels::appearance::AppearancePanel, + /// The Stroke panel's state, kept while the app runs. + #[serde(skip)] + pub stroke_panel: crate::panels::stroke::StrokePanel, + /// The Transparency panel's state, kept while the app runs. + #[serde(skip)] + pub transparency_panel: crate::panels::transparency::TransparencyPanel, + /// The Graphic Styles panel's state, kept while the app runs. + #[serde(skip)] + // PLAN: assumed `crate::panels::graphic_styles::GraphicStylesPanel` (ap.AS17 names no type; appearance-w10). + pub graphic_styles_panel: crate::panels::graphic_styles::GraphicStylesPanel, + /// The symbols the Symbols panel has picked (Select All Unused, a click), by name. + #[serde(skip)] + // PLAN: assumed `Vec` (ap.AS17 names no type; appearance-w11 replaces the `sym-unused` key with it). + pub symbol_picks: Vec, + /// The Brushes panel's multi-selection and the click it belongs to: another document, other + /// objects or another current brush ends it. + #[serde(skip)] + pub brush_selection: Option<(crate::panels::brushes::ClickKey, Selection)>, + /// The Brushes panel's view choices, kept while the app runs. + #[serde(skip)] + pub brushes_view: crate::panels::brushes::BrushesView, + /// The Brush Options dialog that is open, while it is. + #[serde(skip)] + pub brush_options: Option, + /// The selection of each open library panel, by panel id. Not saved. + #[serde(skip)] + // PLAN: assumed `HashMap>` (ap.AS17 names no type; appearance-w17 indexes it by panel). + pub library_selection: HashMap>, + /// The Libraries panel lists its items (on) instead of showing icons (off). + #[serde(skip)] + pub libraries_list_view: bool, + /// The Libraries panel's groups that are closed, as (library id, group name). + #[serde(skip)] + pub library_groups_closed: HashSet<(String, String)>, + /// The Libraries panel's search text. + #[serde(skip)] + pub library_search: String, /// The Separations Preview panel is still to scroll its Color Settings section into view: /// Edit › Color Settings… and Assign Profile… show the panel for it, and the section sits below /// the plates and Proof Setup, out of sight in a short window (#6419). @@ -494,15 +517,13 @@ pub struct UiState { #[serde(default)] pub control_bar_floating: bool, /// The top-left corner of the floating Control bar in window points, kept while the bar is - /// docked; none: `chrome::CONTROL_BAR_FLOAT_AT`. + /// docked; none: the bar's first floating place. #[serde(default, skip_serializing_if = "Option::is_none")] pub control_bar_float_pos: Option<[f32; 2]>, /// The groups of the Control bar's options (`chrome::CONTROL_BAR_GROUPS`) that its panel menu /// has off (`window.control.options`); none: every group shows. #[serde(deserialize_with = "crate::chrome::read_hidden_groups")] - pub control_bar_hidden_groups: std::collections::BTreeSet, - pub toolbar: bool, - pub toolbar_double: bool, + pub control_bar_hidden_groups: BTreeSet, /// Smaller cells and panel width for the main Tools panel, independent of its column count. #[serde(default)] pub toolbar_compact: bool, @@ -511,22 +532,22 @@ pub struct UiState { pub toolbar_advanced: bool, #[serde(default = "yes")] pub task_bar: bool, - /// Where the Contextual Task Bar was dragged or pinned. Not saved: the bar - /// starts under the selection at every launch. + /// Where the Contextual Task Bar was dragged or pinned, and the document it was moved in. Not + /// saved: the bar starts under the selection at every launch. #[serde(skip)] - pub task_bar_place: TaskBarPlace, + pub task_bar_place: crate::canvas::bar_place::KeyedPlace, /// The Contextual Task Bar's actions (`canvas::TASK_BAR_ACTIONS`) that More Options › Bar /// Actions has off (`window.taskBar.actions`); none: the bar shows every action it offers. #[serde(deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] - pub task_bar_hidden_actions: std::collections::BTreeSet, + pub task_bar_hidden_actions: BTreeSet, /// Window › Quick Pen Toolbar: the Quick Pen tool shows its toolbar on the canvas. Hide Toolbar /// turns it off until the tool is selected again. Not saved. #[serde(skip, default = "yes")] pub quick_pen_bar: bool, - /// Where the Quick Pen toolbar was dragged or pinned. Not saved: the toolbar starts beside the - /// drawing at every launch. + /// Where the Quick Pen toolbar was dragged or pinned, and the document and kind of place it + /// was moved in. Not saved: the toolbar starts beside the drawing at every launch. #[serde(skip)] - pub quick_pen_bar_place: QuickPenBarPlace, + pub quick_pen_bar_place: crate::canvas::bar_place::KeyedPlace, /// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the /// permanent Pathfinder result on Alt-click (off, the default: the other way round). #[serde(default)] @@ -556,12 +577,6 @@ pub struct UiState { /// [`crate::addons::select::link_status::refresh`]). Not saved. #[serde(skip)] pub link_statuses: crate::addons::select::link_status::Present, - /// Last tool shown in each toolbar slot (keyed by the slot's first tool id). - #[serde(default)] - pub slot_tool: std::collections::BTreeMap, - /// Tool flyouts torn off the toolbar into floating panels. - #[serde(default)] - pub floating_flyouts: Vec, /// The Basic and Advanced toolbars as Edit Toolbar left them (none: as they ship). #[serde(default)] pub toolbar_edits: ToolbarEdits, @@ -579,73 +594,22 @@ pub struct UiState { /// panel's toolbar). #[serde(skip)] pub drawer_toolbar: Option, - /// Floating panel groups as files from before the canvas joined [`Self::docking`] saved - /// them. Read only to convert those files ([`crate::layout_migration`]), never written. - #[serde(default, skip_serializing)] - pub floating_panels: Vec, - /// Shared panel membership and placement; older preferences use the legacy dock. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub docking: Option>, - #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub docking_hidden: std::collections::BTreeMap>, /// Tabs closed together by panel shortcuts, kept with their workspace return locations. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub docking_hidden_groups: Vec>, - /// Panels dropped on the icon column, in older files (read only, like [`Self::floating_panels`]). - #[serde(default, skip_serializing)] - pub docking_icons: std::collections::BTreeSet, - /// The panels shown by dock groups collapsed to their tabs, in older files (read only, like - /// [`Self::floating_panels`]); a group showing another of its panels was expanded. - #[serde(default, skip_serializing)] - pub docking_collapsed: std::collections::BTreeSet, - /// Invalidates in-flight gestures when a workspace is replaced. - #[serde(skip)] - pub docking_generation: u64, - /// The main dock column's width in screen points while the workspace has no layout of its - /// own (`docking` is none); a customized layout keeps its widths in it. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub dock_width: Option, - /// The Tools panel floats with its top-left corner here (dragged out by its title bar); `None`: - /// docked at the window's left edge, or beside the canvas with [`Self::tools_beside_canvas`]. - #[serde(default)] - pub toolbar_pos: Option<[f32; 2]>, - /// The docked Tools panel sits between the left-side panels and the canvas instead of at the - /// window's left edge (Window › Toolbars › Keep Tools Beside the Canvas, - /// `window.toolsBesideCanvas`). Dropping Tools on the canvas's left edge, right of panels docked - /// on the left, turns it on, and on the window's left edge turns it off; with no panels docked on - /// the left, a drop leaves it as it is. Off by default, and off in state saved without it. - #[serde(default)] - pub tools_beside_canvas: bool, - /// The docked Tools panel stands on the right, between the canvas and the panels, instead of on - /// the left (dropped there, or `window.panel.dock {panel: "tools", side: "right"}`). Off by - /// default, and off in state saved without it. - #[serde(default)] - pub toolbar_right: bool, pub status_bar: bool, /// What the status bar's info field shows (its Show menu, `view.statusBarShow`): Current Tool by /// default and in state saved without it ([`crate::chrome::deserialize_status_bar_show`]). #[serde(default, deserialize_with = "crate::chrome::deserialize_status_bar_show")] pub status_bar_show: crate::chrome::StatusBarShow, pub help_bar: bool, - pub dock: bool, - /// The bars that Tab (`window.dock`) hid, which the next Tab shows again; none when Tab has not - /// hidden them since it last showed them, or a workspace was applied since. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tab_hid: Option, pub view: ViewFlags, - pub dialog: Option, #[serde(skip)] pub brush_key_color_pick: Option, - /// Messages to show in a dialog once the open one is closed (`dialogs::confirm::tell`), in - /// the order they came. - #[serde(skip)] - pub told: Vec, /// A control request is being answered: its caller gets what fails as its reply, so no /// dialog says it too (`io::report_write_error`). #[serde(skip)] pub answering_control: bool, - /// Toolbar group whose flyout is open. - pub flyout: Option, /// Last tool shown for each toolbar group (flyout selection sticks). pub group_tool: Vec, /// The drawing tool last chosen in this window, which a two-finger tap in the Touch workspace @@ -661,8 +625,8 @@ pub struct UiState { #[serde(skip)] pub replace_font_warning: Option, /// The last Find and Replace search ([`crate::dialogs::find_replace`]): the dialog's Find and - /// Replace With text, its options and the place the search reached, which Edit › Find Next - /// goes on from while the dialog is closed. Not saved. + /// Replace With text, its options and the place the search reached (the walk, `found`), which + /// Edit › Find Next goes on from while the dialog is closed. Not saved. #[serde(skip)] pub last_find: Option, /// The notes of the last open that gave any, or of the last save or export, with the status @@ -677,9 +641,10 @@ pub struct UiState { /// and opened again before then. Not saved. #[serde(skip)] pub palette_toggled: bool, - /// Screen mode: 0 normal, 1 full screen with menu, 2 full screen, 3 presentation. Not saved: - /// the app always starts in Normal Screen Mode, with its menus and panels (#472: a saved - /// Presentation Mode came back on restart with no way out). + /// Screen mode: 0 normal, 1 full screen with menu, 2 full screen, 3 presentation + /// ([`Self::screen_mode`] maps it to the shell's mode). Not saved: the app always starts in + /// Normal Screen Mode, with its menus and panels (#472: a saved Presentation Mode came back on + /// restart with no way out). #[serde(skip)] pub screen_mode: u8, /// Window › Arrange › Tile: the open documents share the document area, one pane each, until @@ -701,34 +666,36 @@ pub struct UiState { pub tab_document: Option<(u64, u32)>, /// Draw Normal / Behind / Inside. pub draw_mode: u8, - pub about: bool, - /// Recorded actions (Actions panel), persisted with the UI preferences. - #[serde(default = "crate::panels::actions::default_sets")] - pub action_sets: Vec, - /// The current set of the Actions panel (its name clicked, one of its actions clicked, or made - /// with New Set): a recording goes into it and Set Options renames it. Saved as an index into - /// [`UiState::action_sets`], so the same set is current after a restart - /// ([`crate::panels::actions::deserialize_current_set`]). - #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::panels::actions::deserialize_current_set")] - pub action_set: Option, - /// The sets selected in the Actions panel, in index order: the current set and the sets a - /// Shift-click on a set's name added. Delete Selection deletes them. Not saved. + /// The Home screen's recent files as cards or a list. Not saved. #[serde(skip)] - pub action_sets_selected: Vec, - /// The Actions panel shows its actions as buttons (panel menu › Button Mode, - /// [`crate::panels::actions::button_mode`]) instead of its list; kept with the UI preferences, - /// and off in preferences saved without it. - #[serde(default)] - pub action_button_mode: bool, + pub home_view: RecentView, + /// The Home screen's recent files' order. Not saved. + #[serde(skip)] + pub home_sort: RecentSort, + /// Recorded actions (Actions panel), persisted with the UI preferences under their old key. + #[serde(rename = "action_sets", default = "crate::panels::actions::default_list", with = "crate::panels::actions::prefs")] + pub actions: craft::automation::actions::ActionList, + /// The current set of the Actions panel by name (its name clicked, one of its actions clicked, + /// or made with New Set): a recording goes into it and Set Options renames it. An index saved + /// by older versions is turned into the name when the file is read + /// ([`crate::settings::parse_legacy`]). + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::panels::actions::deserialize_current_set")] + pub action_set: Option, + /// The Actions panel's view: its selection, open rows and Button Mode. Button Mode is kept + /// with the UI preferences under its old key; the rest lasts the session. + #[serde(rename = "action_button_mode", default, with = "crate::panels::actions::prefs::button_mode")] + pub actions_panel: craft::automation::ui::actions::ActionsPanelState, + /// The Script Console's selected entries. Not saved. + #[serde(skip)] + pub script_console_selection: Selection, /// Recording in progress: (set index, action name, journal length when recording started). #[serde(skip)] pub recording: Option<(usize, String, usize)>, - /// The id of the action the recording in progress records into, the one New Action made or the - /// one selected when Begin Recording started it ([`crate::panels::actions::Action::id`]): Stop - /// gives it the recorded steps. None when Stop adds a new action, as after Begin Recording with - /// no action selected. + /// The name of the action the recording in progress records into, the one New Action made or + /// the one selected when Begin Recording started it: Stop gives it the recorded steps. None + /// when Stop adds a new action, as after Begin Recording with no action selected. #[serde(skip)] - pub recording_into: Option, + pub recording_into: Option, /// Where in the action [`UiState::recording_into`] names Stop puts the recorded steps: before /// the step at this index, or None after its last step. #[serde(skip)] @@ -753,41 +720,25 @@ pub struct UiState { /// The playback at Step by Step or Pause For in progress, if any. Not saved. #[serde(skip)] pub action_playing: Option, - /// Keyboard shortcut overrides: command id, `tool:` or `panel:` → chord ("" = none), - /// stored in the form every earlier version reads. - #[serde(default, with = "crate::keymap::stored")] - pub shortcut_overrides: craft_keymap::Overrides, - /// Hold shortcuts: command id, `tool:` or `panel:` → a character key, alone or with - /// Shift ("X", "Shift+X", "."). Holding the key for the Hold Shortcut Delay runs the entry; a - /// quick press runs the key's own shortcut when it is let go. Kept apart from - /// `shortcut_overrides`, so earlier versions read the settings without them. - #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] - pub shortcut_holds: std::collections::BTreeMap, - /// Name of the shortcut set (preset or "Custom"). - #[serde(default = "default_shortcut_set", deserialize_with = "crate::shortcut_editor::deserialize_set_name")] - pub shortcut_set: String, - /// Current workspace (Window → Workspace). - #[serde(default = "default_workspace")] - pub workspace: String, + /// The keyboard shortcut sets and which one is active (Edit › Keyboard Shortcuts). + #[serde(default, with = "crate::keymap::stored::profiles")] + pub shortcut_sets: craft::keymap::Profiles, + /// The shortcut keys of files from before [`Self::shortcut_sets`]: read once into it + /// ([`Self::sanitized`]), never written. + #[serde(flatten)] + pub legacy_shortcuts: LegacyShortcuts, /// Workspace before Preferences › Devices › Enable Touch Workspace switched to Touch (#394). #[serde(default, skip_serializing_if = "Option::is_none")] pub touch_workspace_restore: Option, - /// User-saved workspaces (New Workspace…). - #[serde(default)] - pub custom_workspaces: Vec, - /// Layout changes made in a workspace since it was saved (or last reset), by workspace name: - /// switching back to it brings them back; Reset drops them. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub workspace_changes: Vec, /// File → Open Recent Files, most recent first. #[serde(default)] pub recent_files: Vec, /// Type → Recent Fonts, most recent first. #[serde(default)] pub recent_fonts: Vec, - /// Help › Search Commands' Recent Commands list: the ids of the last picks, most recent first. - #[serde(default)] - pub recent_commands: Vec, + /// Help › Search Commands' Recent Commands list: the last picks, most recent first. + #[serde(default, deserialize_with = "deserialize_recent_commands")] + pub recent_commands: Vec, /// How many times each command was picked in Help › Search Commands, which ranks the commands /// picked most often first among results that match as well. #[serde(default, deserialize_with = "crate::palette::deserialize_command_uses")] @@ -838,30 +789,40 @@ pub struct UiState { /// guide ([`crate::panels::align::run_button`]). Not saved. #[serde(skip)] pub align_spacing: f64, - /// Color panel: the mode picked last from its menu (`None`: never picked), in which the panel - /// shows the defaults for new art ([`crate::panels::color::deserialize_mode`]). - #[serde(default, deserialize_with = "crate::panels::color::deserialize_mode")] - pub color_mode: Option, - /// Color panel: Hide Options, which leaves just the proxy and the spectrum (`ui.colorPanel`, - /// [`crate::panels::color::deserialize_hide_options`]). - #[serde(default, deserialize_with = "crate::panels::color::deserialize_hide_options")] - pub color_hide_options: bool, - /// Color panel: Show Recent Colors, which draws its Recent Colors row while the options show - /// (`ui.colorPanel`, [`crate::panels::color::deserialize_show_recent_colors`]). The list of - /// recent colors keeps filling while the row is hidden. - #[serde(default = "yes", deserialize_with = "crate::panels::color::deserialize_show_recent_colors")] - pub color_show_recent_colors: bool, - /// Color panel: RGB mode shows R, G and B in percent instead of 0 to 255 (a double-click right - /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). - #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] - pub color_rgb_percent: bool, + /// Color panel: its layout, ramp, Hide Options, Show Recent Colors and RGB in percent + /// (`ui.colorPanel`); a value that does not read gives the defaults + /// ([`crate::panels::color::deserialize_panel_state`]). + #[serde(default, deserialize_with = "crate::panels::color::deserialize_panel_state")] + pub color_panel: craft::color_ui::ui::ColorPanelState, + /// The Color Wheel panel's session state. Not saved. + #[serde(skip)] + pub color_wheel_panel: crate::panels::color_wheel::WheelUi, + /// The Color Themes panel's session state. Not saved. + #[serde(skip)] + pub color_themes_panel: crate::panels::color_themes::ThemesUi, + /// The Color Guide panel's session state. Not saved. + #[serde(skip)] + pub color_guide_panel: crate::panels::color_guide::Model, + /// The Gradient panel's session state. Not saved. + #[serde(skip)] + pub gradient_panel: crate::panels::gradient::GradientUi, + /// The Swatches panel's selection, kept swatch and focus. Not saved. + #[serde(skip)] + // PLAN: assumed `crate::panels::swatches::SwatchesPanel` (co.A3 names the model but not its type; color-w10). + pub swatches_panel: crate::panels::swatches::SwatchesPanel, + /// The open Swatch Options dialog's record. Not saved. + #[serde(skip)] + pub swatch_options: Option, + /// The open New Swatch dialog's record. Not saved. + #[serde(skip)] + pub new_swatch: Option, /// Color Wheel panel: the wheel or the box, the box's channel, the slider rows, the /// out-of-gamut shading and the color vision row /// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]). #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] pub color_wheel: crate::panels::color_wheel::Settings, /// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors - /// row (#6617; read as [`Self::color_show_recent_colors`] is). Separate from the Color panel's. + /// row (#6617). Separate from the Color panel's. #[serde(default = "yes", deserialize_with = "crate::panels::color::deserialize_show_recent_colors")] pub swatches_show_recent_colors: bool, /// The SVG Options chosen last (`svg` object of the export/save commands; null: never used). @@ -878,32 +839,18 @@ pub struct UiState { /// The Text Import Options confirmed last (`file.place`'s `text` options; null: never used). #[serde(default)] pub text_import: Value, - /// The file the open dialog reads, kept out of its JSON fields (Import PDF); dropped when no - /// dialog is open. - #[serde(skip)] - pub dialog_file: Option>, - /// Pending new style highlights: document uid, paragraph-style flag, and name. Each document - /// and style kind has at most one pending highlight. - #[serde(skip)] - pub made_text_style: Vec<(u64, bool, String)>, /// The documents (uids) whose Missing Fonts dialog waits until no dialog is open, the next one to - /// show first ([`crate::dialogs::settle`]). + /// show first. #[serde(skip)] pub pending_fonts: Vec, - /// The document (uid) whose Missing Fonts dialog is on show. When another dialog takes its - /// place, [`crate::dialogs::settle`] puts the document back at the front of `pending_fonts`. - #[serde(skip)] - pub fonts_dialog: Option, /// The plug-in (`{id, file, name, label}`) the last launch was loading when it stopped, while - /// the user has not chosen what to do about it. When another dialog takes the choice's place, - /// [`crate::dialogs::settle`] opens the choice again once no dialog is open. + /// the user has not chosen what to do about it. #[serde(skip)] pub stopped_plugin: Option, - /// The proof view the Proof Setup dialog found, and the view its preview shows on the canvas, - /// while the preview shows. When another dialog takes its place, [`crate::dialogs::settle`] - /// puts the first view back, unless the view has changed from the preview since. + /// The open Proof Setup dialog's record: the proof view it found and the one its preview + /// shows on the canvas. #[serde(skip)] - pub proof_preview: Option<(Value, vectorcraft_render::proof::ProofView)>, + pub proof_setup: Option, /// The search the Missing Fonts dialog started (`text.findFontFiles`'s `id`), stopped once the /// dialog is gone. #[serde(skip)] @@ -921,43 +868,10 @@ pub struct UiState { /// The HP-GL Options chosen last (`document.export` HP-GL options; null: never used). #[serde(default)] pub hpgl_options: Value, - /// The Offset Path fields confirmed last (offset, joins, miterLimit; null: never used): its - /// dialog opens on them (#1152). - #[serde(default)] - pub offset_path: Value, - /// The Smart Punctuation fields confirmed last (null: never used): its dialog opens on them. - #[serde(default)] - pub smart_punctuation: Value, - /// The Average & Join fields confirmed last (`to`; null: never used): its dialog opens on them. - #[serde(default)] - pub average_join: Value, /// The Recolor Artwork Preserve checkboxes confirmed last (`preserveWhite`, `preserveBlack`, /// `preserveGrays`; null: never used): its dialog opens with them (#2960). #[serde(default)] pub recolor_preserve: Value, - /// The open Recolor Artwork dialog's own history of color edits (Undo Changes and Redo - /// Changes), empty again each time the dialog opens. - #[serde(skip)] - pub recolor_history: crate::dialogs::recolor::History, - /// The Simplify dialog's fields confirmed last with "Open this dialog with these settings next - /// time" ticked (null: not ticked): Object › Path › Simplify opens the dialog on them instead - /// of the Simplify slider. - #[serde(default)] - pub simplify: Value, - /// The Move dialog's checkboxes as it was last confirmed with (copy, objects, preview; null: - /// never used): it opens with them. - #[serde(default)] - pub move_options: Value, - /// The Transform Each fields it was last confirmed with (scale, move, rotate, reflect, random, - /// reference point, Transform Objects and Preview, not Copy; null: never used): it opens on - /// them (#1732). - #[serde(default)] - pub transform_each: Value, - /// The Expand choices OK last expanded with in this run of the app (object, fill, stroke, - /// gradient, steps; null: none yet): the Expand dialog opens on them, and Object › Expand… - /// chosen with Alt (Option) expands with them at once. They are not kept across launches. - #[serde(skip)] - pub expand_options: Value, /// The spacing used the last time Rearrange All Artboards was confirmed. #[serde(default)] pub rearrange_artboards_spacing: Value, @@ -990,10 +904,22 @@ pub struct UiState { /// Attributes panel › Panel Options… (how many recent URLs the URL menu lists). #[serde(default)] pub attributes_panel: crate::panels::attributes::PanelOptions, - /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the - /// Search All text does. + /// The Layers panel's session state: its Filter (`ui.layersFilter`), selection and open rows. + /// It is not saved and lasts the session, as the Search All text does. #[serde(skip)] - pub layers_filter: crate::panels::layers::Filter, + pub layers_ui: crate::panels::layers::LayersUi, + /// The Artboards panel's session state. Not saved. + #[serde(skip)] + pub artboards_ui: crate::panels::artboards::ArtboardsUi, + /// The Info panel's Hide Options. Not saved. + #[serde(skip)] + pub info_hide_options: bool, + /// The Document Info panel's view. Not saved. + #[serde(skip)] + pub doc_info: crate::panels::doc_info::DocInfoView, + /// The Links panel's options, selection and scroll. Not saved. + #[serde(skip)] + pub links: crate::panels::links::LinksModel, /// The Swatches, Graphic Styles and Symbols panels' views, chosen in their panel menus /// (`ui.panelView`). They are not saved and last the session. #[serde(skip)] @@ -1009,28 +935,162 @@ pub struct UiState { /// Trace object again at once. Off, the changes wait in the panel until Trace applies them. #[serde(default = "yes")] pub image_trace_preview: bool, - /// Glyphs panel preview step, kept with the other panel choices. `0` is the default 30 pt - /// cell; `1`..=`7` is a step from smallest to largest (`crates/ui-egui/src/panels/glyphs.rs`). - #[serde(default, skip_serializing_if = "is_zero_u8")] - pub glyphs_preview: u8, - /// The desktop window's size, position and maximized state, saved when the app quits and - /// restored at the next launch (the desktop host reads and writes it; none on the web). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub window: Option, + /// The Glyphs panel's category, zoom and recent glyphs. + #[serde(default)] + pub glyphs_panel: craft::font_manager::glyphs::GlyphsPanelSettings, + /// The family and style the Glyphs panel shows when it does not follow the selection. Not saved. + #[serde(skip)] + pub glyphs_font: Option<(String, String)>, + /// The glyph the Glyphs panel marked last. Not saved. + #[serde(skip)] + pub glyphs_marked: Option, + /// The font menus' filters (class, favourites, similar, script). Not saved. + #[serde(skip)] + pub font_filters: craft::font_manager::picker::FontFilters, + /// The Character panel's Hide Options. Not saved. + #[serde(skip)] + pub character_hide_options: bool, + /// The Character panel's font height reference. Not saved. + #[serde(skip)] + pub character_font_height: bool, + /// The Snap to Glyph options show in the Character panel. Not saved. + #[serde(skip)] + pub snap_to_glyph_options: bool, + /// The Snap to Glyph options are still to scroll into view. Not saved. + #[serde(skip)] + pub snap_to_glyph_reveal: bool, + /// The Paragraph panel's Hide Options. Not saved. + #[serde(skip)] + pub paragraph_hide_options: bool, + /// The Tabs panel's session state. Not saved. + #[serde(skip)] + pub tabs_panel: crate::panels::tabs::TabsPanel, + /// The Character and Paragraph Styles panels' session state. Not saved. + #[serde(skip)] + pub text_styles: crate::panels::text_styles::StylesPanels, + /// The Properties panel's open sections. Not saved. + #[serde(skip)] + pub properties_panel: crate::panels::properties::PropertiesUi, + /// The Transform panel's reference point and popover. Not saved. + #[serde(skip)] + pub transform_panel: crate::panels::transform::TransformUi, + /// The panel parts a panel menu's Hide Options turned off. Not saved. + #[serde(skip)] + pub hidden_parts: BTreeSet<&'static str>, + /// The Image Trace panel's shown settings and preset picker. Not saved. + #[serde(skip)] + pub image_trace_panel: crate::panels::image_trace::ImageTraceUi, + /// The Asset Export panel's selection, applied preset and Save As name, per document. Not saved. + #[serde(skip)] + pub asset_export_panel: crate::panels::asset_export::AssetExportPanel, + /// The Pattern Options panel's chosen pattern. Not saved. + #[serde(skip)] + pub pattern_options_panel: crate::panels::pattern_options::PatternOptionsPanel, + /// The SVG Interactivity panel's chosen event. Not saved. + #[serde(skip)] + pub svg_interactivity_panel: crate::panels::svg_interactivity::SvgInteractivityPanel, + /// The CSS Properties panel's options. Not saved. + #[serde(skip)] + pub css_properties_panel: crate::panels::css_properties::CssPropertiesPanel, + /// The Production Preflight panel's options and recheck cache. Not saved. + #[serde(skip)] + pub preflight_panel: crate::panels::preflight::PreflightPanel, + /// How many clicks the Image Trace pick has taken, which offsets the next pick. Not saved. + #[serde(skip)] + pub trace_pick_clicks: u32, + /// Where the canvas's context menu opened (screen points), while it is open. Not saved. + #[serde(skip)] + pub context_menu_at: Option, } -/// The desktop window's geometry, kept across launches. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct WindowGeometry { - /// Top-left corner of the window frame, in physical pixels on the desktop (none where the - /// system doesn't tell windows where they are). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pos: Option<[i32; 2]>, - /// Size of the window's contents in logical pixels (points at 100% UI scaling). - pub size: [f32; 2], - /// The window was maximized; `pos` and `size` are where un-maximizing puts it. - #[serde(default)] - pub maximized: bool, +/// The panel fields older files saved before the shared dock: read through aliases (a workspace +/// record spells them in camelCase) and never written. [`crate::layout_migration::migrate_ui`] +/// turns them into [`UiState::dock_workspace`] and [`UiState::tools_last_used`]. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct LegacyDock { + /// The arrangement once the canvas joined the dock. + #[serde(skip_serializing)] + pub docking: Option>, + /// Closed panels and floating panels, with the place each goes back to. + #[serde(skip_serializing, alias = "dockingHidden")] + pub docking_hidden: std::collections::BTreeMap>, + /// Panels dropped on the icon column. + #[serde(skip_serializing, alias = "dockingIcons")] + pub docking_icons: BTreeSet, + /// The panels shown by dock groups collapsed to their tabs. + #[serde(skip_serializing, alias = "dockingCollapsed")] + pub docking_collapsed: BTreeSet, + /// Floating panel groups from before the canvas joined the dock. + #[serde(skip_serializing, alias = "floatingPanels")] + pub floating_panels: Vec, + /// The tab in front in the dock's tabbed group. + #[serde(skip_serializing, alias = "dockTab")] + pub dock_tab: DockTab, + /// Tab order in the dock's tabbed group when it differs from [`DockTab::ALL`]. + #[serde(skip_serializing, alias = "dockTabOrder")] + pub dock_tab_order: Vec, + /// The dock's tabbed group was collapsed to icons. + #[serde(skip_serializing, alias = "dockCollapsed")] + pub dock_collapsed: bool, + /// The main dock column's width in screen points. + #[serde(skip_serializing, alias = "dockWidth")] + pub dock_width: Option, + /// The Tools panel floated with its top-left corner here. + #[serde(skip_serializing, alias = "toolbarPos")] + pub toolbar_pos: Option<[f32; 2]>, + /// The docked Tools panel stood on the right. + #[serde(skip_serializing, alias = "toolbarRight")] + pub toolbar_right: bool, + /// The docked Tools panel stood between the left-side panels and the canvas. + #[serde(skip_serializing, alias = "toolsBesideCanvas")] + pub tools_beside_canvas: bool, + /// The Tools panel showed two columns. + #[serde(skip_serializing, alias = "toolbarDouble")] + pub toolbar_double: bool, + /// Tool flyouts torn off the toolbar into floating strips. + #[serde(skip_serializing, alias = "floatingFlyouts")] + pub floating_flyouts: Vec, + /// The tool each toolbar slot showed last, keyed by the slot's first tool id. + #[serde(skip_serializing, alias = "slotTool")] + pub slot_tool: std::collections::BTreeMap, +} + +/// The shortcut keys older files saved: the overrides, the set's name and the hold shortcuts. Read +/// once into [`UiState::shortcut_sets`] and never written. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct LegacyShortcuts { + /// Command id, `tool:` or `panel:` → chord text, as earlier versions wrote them. + #[serde(rename = "shortcut_overrides", skip_serializing)] + pub overrides: Value, + /// The shortcut set's name. + #[serde(rename = "shortcut_set", skip_serializing)] + pub set: Option, + /// Hold shortcuts: command id, `tool:` or `panel:` → a character key. + #[serde(rename = "shortcut_holds", skip_serializing)] + pub holds: Value, +} + +impl LegacyShortcuts { + /// Whether the file had none of the old keys. + fn is_empty(&self) -> bool { + self.overrides.is_null() && self.set.is_none() && self.holds.is_null() + } +} + +/// Reads the Recent Commands list: a command with its parameters, or a command id as older +/// versions saved it. Search Commands itself is never listed. +fn deserialize_recent_commands<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let values = Vec::::deserialize(d)?; + Ok(values + .into_iter() + .filter_map(|value| match value { + Value::String(id) => Some(crate::keymap::command_of(&id)), + other => serde_json::from_value(other).ok(), + }) + .filter(|command| command.id != "help.commandPalette") + .collect()) } /// A tool group's flyout torn off the toolbar: it floats as its own panel until its × puts it back. @@ -1053,39 +1113,45 @@ impl FloatingFlyout { } } -/// A toolbar made with Window › Toolbars › New Toolbar (`window.toolbar.new`): it floats on its -/// own or docks along the window's left or right edge, filled with tools from the All Tools drawer, -/// and is kept with the workspace it was made in. -/// The groups torn off it are kept with it (`floating`), so the Tools panel's strips -/// (`UiState::floating_flyouts`) hold none of them. +/// A toolbar made with Window › Toolbars › New Toolbar (`window.toolbar.new`), filled with tools +/// from the All Tools drawer and kept with the workspace it was made in. Where it shows is the +/// dock's: its panel is `toolbar:` in [`UiState::dock_workspace`]. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomToolbar { + /// Names its panel (`toolbar:`); 0 in files saved before toolbars had ids, until the + /// conversion gives it one. + #[serde(default)] + pub id: u32, /// The name it is listed under in Window › Toolbars. pub name: String, /// Its slots, each a tool group (the first tool is the slot's default). #[serde(default)] pub slots: Vec>, - /// It shows (Window › Toolbars › its name toggles it). - #[serde(default = "yes")] + /// The tool each slot showed last. + #[serde(default)] + pub last_used: craft::ui::rails::LastUsed, + /// Older files: it showed. Read by the conversion, never written. + #[serde(default = "yes", skip_serializing)] pub shown: bool, - /// Top-left corner in screen points while it floats; while it is docked, where it floated last. + /// Older files: its top-left corner while it floated. Read by the conversion, never written. + #[serde(default, skip_serializing)] pub pos: [f32; 2], - /// Its place in the stack of toolbars docked along one of the window's edges (0 at the top), - /// while it is docked there; none while it floats at `pos`. - #[serde(default, skip_serializing_if = "Option::is_none")] + /// Older files: its place in the stack of toolbars docked along an edge. Read by the + /// conversion, never written. + #[serde(default, skip_serializing)] pub dock: Option, - /// It docks along the window's right edge, not the left: the edge it is docked at, or while it - /// floats the edge it docked at last. - #[serde(default, skip_serializing_if = "std::ops::Not::not")] + /// Older files: it docked along the right edge. Read by the conversion, never written. + #[serde(default, skip_serializing)] pub dock_right: bool, - /// The tool each slot of several tools shows, chosen last (keyed by the slot's first tool). - #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + /// Older files: the tool each slot showed, keyed by the slot's first tool. Read by the + /// conversion, never written. + #[serde(default, skip_serializing)] pub slot_tool: std::collections::BTreeMap, - /// Its tools show in two columns (the double arrow on its title bar toggles it). - #[serde(default, skip_serializing_if = "std::ops::Not::not")] + /// Older files: its tools showed in two columns. Read by the conversion, never written. + #[serde(default, skip_serializing)] pub double: bool, - /// The groups torn off it, each floating as its own strip; they show while it does. - #[serde(default, skip_serializing_if = "Vec::is_empty")] + /// Older files: the groups torn off it. Read by the conversion, never written. + #[serde(default, skip_serializing)] pub floating: Vec, } @@ -1159,52 +1225,6 @@ pub struct ToolbarEdits { pub advanced: Option>, } -/// Where the Quick Pen toolbar sits once its handle has moved it (`window.quickPenToolbar.pin`, -/// `window.quickPenToolbar.reset`). -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct QuickPenBarPlace { - /// More Options › Pin Toolbar Position: the toolbar stays where it is on the canvas instead of - /// following the drawing. - pub pinned: bool, - /// Where a pinned toolbar's top-left corner sits from the canvas's top-left (none when it was - /// pinned before it ever showed, until it is drawn). Unpinning leaves it for the next frame to - /// turn into `offset`. - pub pin_at: Option, - /// Where the toolbar was last drawn, from the canvas's top-left: where pinning holds it. - pub shown_at: Option, - /// How far an unpinned toolbar was dragged from its place, the document (`DocState::uid`) it - /// was moved in, and whether it was beside a path being drawn then (false: resting with no path - /// being drawn). It applies only in that document and that kind of place. - pub offset: Option<(u64, bool, egui::Vec2)>, -} - -/// Where the Contextual Task Bar sits once its handle has moved it (`window.taskBar.pin`, -/// `window.taskBar.reset`). -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct TaskBarPlace { - /// More Options › Pin Bar Position: the bar stays where it is instead of following the selection. - pub pinned: bool, - /// Where a pinned bar's top-left corner sits from the canvas's top-left (none when it was - /// pinned before it ever showed, until it is drawn). Unpinning leaves it for the next frame - /// to turn into `offset`. - pub pin_at: Option, - /// Where the bar was last drawn, from the canvas's top-left: where pinning holds it. - pub shown_at: Option, - /// How far an unpinned bar was dragged from its place under the selection, which it keeps while - /// it follows the selection, and the document (`DocState::uid`) it was moved in: in another - /// document the bar starts under the selection again. - pub offset: Option<(u64, egui::Vec2)>, -} - -/// Which of the panels, the toolbar and the Control bar showed when Tab (`window.dock`) hid them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct TabHid { - pub dock: bool, - pub toolbar: bool, - pub control_bar: bool, -} - /// A group of panels dragged out of the dock, as files from before the canvas joined the panel /// layout saved it: it floated as a stack of tabs, one panel shown. /// @@ -1234,8 +1254,8 @@ pub struct FloatingPanels { pub docked: Option, } -/// Drop a floating position of the Tools panel or the Control bar that isn't a number (a -/// hand-edited preferences file or workspace). +/// Drop a floating position of the Control bar that isn't a number (a hand-edited preferences +/// file or workspace). pub fn sanitize_toolbar_pos(toolbar_pos: &mut Option<[f32; 2]>) { if toolbar_pos.is_some_and(|p| !p.iter().all(|v| v.is_finite())) { *toolbar_pos = None; @@ -1245,50 +1265,54 @@ pub fn sanitize_toolbar_pos(toolbar_pos: &mut Option<[f32; 2]>) { impl UiState { /// Clear transient state after loading saved preferences. pub fn sanitized(mut self) -> Self { - self.dialog = None; - self.flyout = None; self.tools_drawer = false; self.drawer_toolbar = None; crate::custom_toolbars::sanitize(&mut self.custom_toolbars); self.palette_open = false; self.status.clear(); - self.about = false; self.open_panel = None; if self.group_tool.len() != vectorcraft_tools::TOOL_GROUPS.len() { self.group_tool = UiState::default().group_tool; } - FloatingFlyout::sanitize(&mut self.floating_flyouts); - sanitize_toolbar_pos(&mut self.toolbar_pos); sanitize_toolbar_pos(&mut self.control_bar_float_pos); crate::edit_toolbar::sanitize(&mut self.toolbar_edits); // `read_preferences` converted the file's older layouts already; this covers a state read // any other way. What it reports lost was dropped there. let _ = crate::layout_migration::migrate_ui(&mut self); - self.docking = self.docking.filter(crate::panel_docking::valid); - // Changes kept for workspaces that still exist, under their saved spelling and one per - // workspace whatever the case (a hand-edited file). - let mut seen = std::collections::BTreeSet::new(); - let saved: Vec = - self.custom_workspaces.iter().map(|w| w.name.clone()).chain(crate::workspaces::builtins().into_iter().map(|w| w.name)).collect(); - self.workspace_changes.retain_mut(|w| { - let Some(name) = saved.iter().find(|n| n.eq_ignore_ascii_case(&w.name)) else { return false }; - w.name = name.clone(); - seen.insert(name.to_ascii_lowercase()) - }); - self.workspace_changes.truncate(64); - // Overrides that can't fire (modifier-only chords recorded by older versions, #487) give - // the default back. - let unusable: Vec = self - .shortcut_overrides - .iter() - .filter(|(_, texts)| !texts.iter().all(|t| craft_keymap::Binding::parse(t).is_ok())) - .map(|(k, _)| k.to_string()) - .collect(); - for k in unusable { - self.shortcut_overrides.remove(&k); + crate::panel_docking::reconcile(&mut self.dock_workspace); + self.workspaces.sanitize(); + // A file from before the shortcut sets: its overrides, set name and holds become the sets. + let legacy = std::mem::take(&mut self.legacy_shortcuts); + if !legacy.is_empty() { + self.shortcut_sets = crate::keymap::stored::legacy(&legacy.overrides, legacy.set.as_deref(), &legacy.holds); } self } + + /// The shell's screen mode for [`Self::screen_mode`]'s number: Presentation (3) is full screen + /// with the reveal off, which the frame passes to the shell beside this. + pub fn screen_mode(&self) -> ScreenMode { + match self.screen_mode { + 0 => ScreenMode::Standard, + 1 => ScreenMode::FullScreenWithMenuBar, + _ => ScreenMode::FullScreen, + } + } + + /// Whether the screen mode is Presentation Mode: the body only, and Tab reveals nothing. + pub fn presenting(&self) -> bool { + self.screen_mode >= 3 + } + + /// Takes the mode the shell moved to (its screen-mode commands, a reveal's end); a move also + /// leaves Presentation Mode, which the shell knows only as full screen. + pub fn follow_screen_mode(&mut self, mode: ScreenMode) { + self.screen_mode = match mode { + ScreenMode::Standard => 0, + ScreenMode::FullScreenWithMenuBar => 1, + _ => 2, + }; + } } impl Default for UiState { @@ -1297,13 +1321,24 @@ impl Default for UiState { Self { legacy_language: None, brightness: Brightness::MediumDark, - print_direct_pdf: false, - dock_tab: DockTab::Properties, - dock_tab_order: Vec::new(), - dock_collapsed: false, + dock_workspace: Default::default(), + tools_last_used: Default::default(), + workspaces: Default::default(), + legacy: LegacyDock::default(), open_panel: None, transient_panel: None, - transient_focus: false, + appearance_panel: Default::default(), + stroke_panel: Default::default(), + transparency_panel: Default::default(), + graphic_styles_panel: Default::default(), + symbol_picks: Vec::new(), + brush_selection: None, + brushes_view: Default::default(), + brush_options: None, + library_selection: HashMap::new(), + libraries_list_view: false, + library_groups_closed: HashSet::new(), + library_search: String::new(), color_settings_scroll: false, find_font_in: String::new(), constrain_pie_angle: false, @@ -1318,50 +1353,31 @@ impl Default for UiState { control_bar_floating: false, control_bar_float_pos: None, control_bar_hidden_groups: Default::default(), - toolbar: true, - toolbar_double: false, toolbar_compact: false, toolbar_advanced: false, task_bar: true, - task_bar_place: TaskBarPlace::default(), + task_bar_place: Default::default(), task_bar_hidden_actions: Default::default(), quick_pen_bar: true, - quick_pen_bar_place: QuickPenBarPlace::default(), + quick_pen_bar_place: Default::default(), shape_modes_compound: false, context_locked: None, context_intertwine: None, context_artboards: None, context_spelling: None, link_statuses: Default::default(), - slot_tool: Default::default(), - floating_flyouts: vec![], toolbar_edits: ToolbarEdits::default(), toolbar_show: ToolbarShow::default(), tools_drawer: false, custom_toolbars: vec![], drawer_toolbar: None, - floating_panels: vec![], - docking: None, - docking_hidden: Default::default(), docking_hidden_groups: Vec::new(), - docking_icons: Default::default(), - docking_collapsed: Default::default(), - docking_generation: 0, - dock_width: None, - toolbar_pos: None, - tools_beside_canvas: false, - toolbar_right: false, status_bar: true, status_bar_show: crate::chrome::StatusBarShow::CurrentTool, help_bar: true, - dock: true, - tab_hid: None, view: ViewFlags::default(), - dialog: None, brush_key_color_pick: None, - told: vec![], answering_control: false, - flyout: None, group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), touch_drawing_tool: None, status: String::new(), @@ -1378,11 +1394,12 @@ impl Default for UiState { floating: Vec::new(), tab_document: None, draw_mode: 0, - about: false, - action_sets: crate::panels::actions::default_sets(), + home_view: RecentView::default(), + home_sort: RecentSort::default(), + actions: crate::panels::actions::default_list(), action_set: None, - action_sets_selected: vec![], - action_button_mode: false, + actions_panel: Default::default(), + script_console_selection: Selection::default(), recording: None, recording_into: None, recording_at: None, @@ -1391,13 +1408,9 @@ impl Default for UiState { recording_checked: None, action_playback: Default::default(), action_playing: None, - shortcut_overrides: Default::default(), - shortcut_holds: Default::default(), - shortcut_set: default_shortcut_set(), - workspace: default_workspace(), + shortcut_sets: Default::default(), + legacy_shortcuts: LegacyShortcuts::default(), touch_workspace_restore: None, - custom_workspaces: vec![], - workspace_changes: vec![], recent_files: vec![], recent_fonts: vec![], recent_commands: vec![], @@ -1414,36 +1427,29 @@ impl Default for UiState { color_guide_spot: None, align_to: Default::default(), align_spacing: 0.0, - color_mode: None, - color_hide_options: false, - color_show_recent_colors: true, - color_rgb_percent: false, + color_panel: Default::default(), + color_wheel_panel: Default::default(), + color_themes_panel: Default::default(), + color_guide_panel: Default::default(), + gradient_panel: Default::default(), + swatches_panel: Default::default(), + swatch_options: None, + new_swatch: None, color_wheel: Default::default(), swatches_show_recent_colors: true, svg_options: Value::Null, place_link: true, place_import_options: true, text_import: Value::Null, - dialog_file: None, - made_text_style: vec![], pending_fonts: vec![], - fonts_dialog: None, stopped_plugin: None, - proof_preview: None, + proof_setup: None, dialog_search: None, links_search: None, dxf_options: Value::Null, eps_options: Value::Null, hpgl_options: Value::Null, - offset_path: Value::Null, - smart_punctuation: Value::Null, - average_join: Value::Null, recolor_preserve: Value::Null, - recolor_history: Default::default(), - simplify: Value::Null, - move_options: Value::Null, - transform_each: Value::Null, - expand_options: Value::Null, rearrange_artboards_spacing: Value::Null, dxf_import: Value::Null, psd_import: Value::Null, @@ -1453,14 +1459,38 @@ impl Default for UiState { layers_panel: Default::default(), navigator_panel: Default::default(), attributes_panel: Default::default(), - layers_filter: Default::default(), + layers_ui: Default::default(), + artboards_ui: Default::default(), + info_hide_options: false, + doc_info: Default::default(), + links: Default::default(), swatches_view: Default::default(), graphic_styles_view: Default::default(), symbols_view: Default::default(), image_trace_advanced: true, image_trace_preview: true, - glyphs_preview: 0, - window: None, + glyphs_panel: Default::default(), + glyphs_font: None, + glyphs_marked: None, + font_filters: Default::default(), + character_hide_options: false, + character_font_height: false, + snap_to_glyph_options: false, + snap_to_glyph_reveal: false, + paragraph_hide_options: false, + tabs_panel: Default::default(), + text_styles: Default::default(), + properties_panel: Default::default(), + transform_panel: Default::default(), + hidden_parts: BTreeSet::new(), + image_trace_panel: Default::default(), + asset_export_panel: Default::default(), + pattern_options_panel: Default::default(), + svg_interactivity_panel: Default::default(), + css_properties_panel: Default::default(), + preflight_panel: Default::default(), + trace_pick_clicks: 0, + context_menu_at: None, } } } @@ -1469,143 +1499,32 @@ fn yes() -> bool { true } -fn is_zero_u8(v: &u8) -> bool { - *v == 0 -} - -fn default_shortcut_set() -> String { - crate::shortcut_editor::PRESETS[0].to_string() -} - -fn default_workspace() -> String { - crate::workspaces::ESSENTIALS.to_string() -} - -/// One UI pass key: the context identity, the viewport and that viewport's cumulative frame. -pub(crate) type InputFrame = (u64, egui::ViewportId, u64); - -/// Record `frame` unless this host iteration already took it. A discarded rerun and any -/// interleaved pass order stay exact-once because the key, not the last-seen slot, is compared. -/// The list is cleared at every host-iteration boundary, so it stays as small as that iteration's -/// pass count. -pub(crate) fn take_frame_once(frames: &mut Vec, frame: InputFrame) -> bool { - if frames.contains(&frame) { - return false; - } - frames.push(frame); - true -} - -/// The document, dialog and focus an injected batch belongs to: if any changed before a UI pass -/// took the batch, the clicks or text no longer belong to the new state and are dropped. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct InputGeneration { - pub(crate) document: u64, - pub(crate) dialog: Option, - pub(crate) focus: Option, -} - -/// The window geometry a capture belongs to (logical and screen bounds, DPI and zoom). -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct GeometryStamp { - pub(crate) viewport: egui::ViewportId, - pub(crate) content: egui::Rect, - pub(crate) inner: Option, - pub(crate) pixels_per_point: f32, - pub(crate) zoom: f32, -} - -/// What the issued capture must still match when it completes. -#[derive(Clone, Copy, Debug)] -pub(crate) struct CaptureEpoch { - pub(crate) geometry: u64, - pub(crate) viewport: egui::ViewportId, - /// The active document (uid, revision) at issuance: a screenshot never answers with pixels of - /// a document, undo state or selection that replaced it while the capture was in flight. - pub(crate) document: Option<(u64, u64)>, - /// The image size the issuing geometry predicts (`width * height`, checked). - pub(crate) width: usize, - pub(crate) height: usize, -} - -/// An admitted capture waiting for its settled frame (`frames`) and animation delay (`due_ms`). -pub(crate) struct QueuedScreenshot { - pub(crate) id: u64, - pub(crate) due_ms: f64, - pub(crate) frames: u32, -} - -/// A window capture asked for through the control channel (`ui.screenshot`), answered once a -/// frame is presented; a window that isn't presented never delivers one, hence the deadline. -pub(crate) struct PendingScreenshot { - pub(crate) id: u64, - pub(crate) path: Option, - /// Send the PNG back as `pngBase64`. - pub(crate) data: bool, - pub(crate) reply: Sender, - /// When to give up (ms, as [`now_ms`], monotonic). - pub(crate) deadline_ms: f64, - /// The checked bytes this request reserved before it was admitted. - pub(crate) reserved_bytes: usize, - /// The active document at admission: switching documents before issuance fails the request - /// rather than capturing a different document. - pub(crate) document: Option<(u64, u64)>, - /// The live one-shot completion slot while the command is outstanding. - pub(crate) slot: Option, - /// The geometry and expected image size at issuance. - pub(crate) issued: Option, - /// Fresh slots made after a geometry change (a resize while the capture was in flight). - pub(crate) attempts: u8, -} - -/// At most this many captures admitted (pending or queued) at once. -pub(crate) const MAX_PENDING_SCREENSHOTS: usize = 4; - -/// The largest single capture admitted (128 MiB: a 4K viewport at 2x). -pub(crate) const MAX_SCREENSHOT_BYTES: usize = 128 * 1024 * 1024; - -/// The aggregate budget of admitted captures (256 MiB). -pub(crate) const MAX_SCREENSHOT_TOTAL_BYTES: usize = 256 * 1024 * 1024; - -/// Settle frames a capture waits for after a control request (and the animation time). -pub(crate) const SCREENSHOT_SETTLE_FRAMES: u32 = 3; - -/// How long after settling an issued capture may take (ms). -pub(crate) const SCREENSHOT_TIMEOUT_MS: f64 = 8000.0; - -/// The timeout's answer: no file, no second reply. -pub(crate) const SCREENSHOT_TIMEOUT_ERROR: &str = - "no frame was presented (screen locked, window minimized or fully covered); ui.render still renders the artboard"; - -/// Seconds between two looks at the system clipboard for [`VectorcraftApp::system_paste`]. +/// Seconds between two in-line looks at the system clipboard for `VectorcraftApp::system_paste`, +/// where no probe thread looks for the app. pub(crate) const SYSTEM_CLIPBOARD_POLL: f64 = 0.25; -/// Seconds between looks for fonts a font manager activated while the app stays in front (#2576). -#[cfg(not(target_arch = "wasm32"))] -pub(crate) const FONT_INSTALL_POLL: f64 = 2.0; +/// How often the font catalog looks for fonts a font manager activated while the app stays in +/// front (#2576). +pub(crate) const FONT_INSTALL_POLL: std::time::Duration = std::time::Duration::from_secs(2); #[cfg(test)] mod tests { use super::*; - #[test] - fn zoom_steps() { - assert_eq!(next_zoom_with_display(1.0, true, false), 1.5); - assert!((next_zoom_with_display(1.0, false, false) - 0.6667).abs() < 1e-9); - assert_eq!(next_zoom_with_display(640.0, true, false), 640.0); - assert_eq!(zoom_label(0.6667, false), "66.67%"); - assert_eq!(zoom_label(1.0, false), "100%"); - assert_eq!(zoom_label(0.125, false), "12.5%"); - } - /// storytold/vectorcraft#2719: 100% in the zoom field matches Actual Size when Display Print Size is on. #[test] fn zoom_percent_honors_display_print_size_baseline() { - let b = zoom_baseline(true); - assert!((zoom_from_display_percent(100.0, true) - b).abs() < 1e-12); - assert_eq!(zoom_from_display_percent(100.0, false), 1.0); - assert_eq!(zoom_label(b, true), "100%"); - assert_eq!(next_zoom_with_display(b, true, true), zoom_from_display_percent(150.0, true)); + let print = zoom_baseline(true); + assert!(print > zoom_baseline(false), "an inch in 96 points zooms in past one point per point"); + for display_print_size in [false, true] { + let baseline = zoom_baseline(display_print_size); + assert!((zoom_display_percent(baseline, display_print_size) - 100.0).abs() < 1e-9, "{display_print_size}"); + assert!((zoom_from_display_percent(100.0, display_print_size) - baseline).abs() < 1e-9, "{display_print_size}"); + let up = next_zoom(baseline, true, display_print_size); + let down = next_zoom(baseline, false, display_print_size); + assert!(up > baseline && down < baseline, "{display_print_size}: {down} < {baseline} < {up}"); + assert!(zoom_display_percent(up, display_print_size) > 100.0, "{display_print_size}"); + } } #[test] @@ -1631,11 +1550,4 @@ mod tests { app.sync_views(); assert_eq!(app.view().map(|v| (v.artboard, v.zoom)), Some((1, 2.0))); } - - #[test] - fn dialog_fields() { - let d = Dialog::new("rectangle", serde_json::json!({"width": "1in", "height": 50})); - assert_eq!(d.f64("width", 0.0), 72.0); - assert_eq!(d.f64("height", 0.0), 50.0); - } } diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs new file mode 100644 index 0000000000..dd28fe0289 --- /dev/null +++ b/crates/ui-egui/src/testing.rs @@ -0,0 +1,24 @@ +//! The app's own interface install for tests: the runtime, the fonts and the root theme the app +//! gives a real window, so a test lays text out and paints in the app's look. + +use craft::ui::runtime::frame::{FrameInput, set_input}; +use craft::ui::shell::embed; + +/// Installs the runtime with a window system that has no OS services, the app's interface fonts +/// ([`crate::ui_fonts`]) and its root values from the default preferences on `ctx`, as the hosts +/// and [`crate::VectorcraftApp::frame_input`] do. A fixture's context has the runtime already and +/// gets the fonts alone. +pub(crate) fn install(ctx: &egui::Context) { + let fonts = crate::ui_fonts(); + if embed::install(ctx, craft::ui::testing::install_spec(), &fonts).is_err() { + fonts.install(ctx); + } + set_input(ctx, FrameInput::new(crate::app::root_env(&vectorcraft_engine::Prefs::default(), 1.0))); +} + +/// A context with the runtime, the app's interface fonts and its root theme installed. +pub(crate) fn ui_context() -> egui::Context { + let ctx = egui::Context::default(); + install(&ctx); + ctx +} diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs deleted file mode 100644 index 665099cf81..0000000000 --- a/crates/ui-egui/src/titlebar.rs +++ /dev/null @@ -1,517 +0,0 @@ -//! The window's own title bar on Windows and Linux, where the window has no OS decorations -//! ([`VectorcraftApp::custom_titlebar`]): empty space in the app bar drags the window and a -//! double-click there maximizes it, caption buttons at the ends that [`CaptionLayout`] names (all three -//! at the far right by default) minimize, maximize/restore and close, and thin invisible zones along -//! the window's edges resize it. On macOS the app bar sits under the system's transparent title bar -//! and only its [`drag_area`] is used. - -use egui::{CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2}; -use serde_json::json; - -use crate::VectorcraftApp; -use crate::theme::Tokens; - -/// One caption button: as wide as the native Windows ones. -pub const BUTTON_WIDTH: f32 = 46.0; -/// The three caption buttons together. -pub const WIDTH: f32 = 3.0 * BUTTON_WIDTH; -/// Resize zone thickness along an edge, and the side of a corner zone. -const EDGE: f32 = 5.0; -const CORNER: f32 = 12.0; - -/// A caption button. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Caption { - Minimize, - Maximize, - Close, -} - -/// The default order, left to right. -const CAPTIONS: [Caption; 3] = [Caption::Minimize, Caption::Maximize, Caption::Close]; - -/// Which caption buttons the app bar draws at its left end and at its right end, each list left to -/// right. The desktop app sets it from the desktop's window-button layout on Linux and the BSDs -/// ([`VectorcraftApp::caption_layout`]). The default has Minimize, Maximize and Close at the right. -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct CaptionLayout { - pub left: Vec, - pub right: Vec, -} - -impl Default for CaptionLayout { - fn default() -> Self { - Self { left: Vec::new(), right: CAPTIONS.to_vec() } - } -} - -impl CaptionLayout { - /// The width the buttons at the left end take. - pub fn left_width(&self) -> f32 { - self.left.len() as f32 * BUTTON_WIDTH - } - - /// The width the buttons at the right end take. - pub fn right_width(&self) -> f32 { - self.right.len() as f32 * BUTTON_WIDTH - } -} - -/// Caption button ids (stable, so tests and agents can find them). -fn caption_id(c: Caption) -> Id { - Id::unique(("titlebar-caption", c as u8)) -} - -fn maximized(ctx: &egui::Context) -> bool { - ctx.input(|i| i.viewport().maximized.unwrap_or(false)) -} - -fn toggle_maximize(ctx: &egui::Context) { - ctx.send_viewport_cmd(ViewportCommand::Maximized(!maximized(ctx))); -} - -/// The bar's background: a press-and-drag on empty space moves the window, a double-click toggles -/// maximize. Call it before laying out the bar so its widgets, registered later, take the clicks. -pub fn drag_area(ui: &Ui, rect: Rect) { - let ctx = ui.ctx(); - // Not focusable (`click_and_drag` is): Tab goes through the bar's widgets, not its background. - let resp = ui.interact(rect, Id::unique("titlebar-drag"), Sense::CLICK | Sense::DRAG); - // egui hands a drag that starts on a click-only widget (a menu title) to the drag-sensing - // background below it, so remember whether the press itself landed on bare background. - if ctx.input(|i| i.pointer.any_pressed()) { - let bare = ctx.viewport(|v| v.hits.click.is_some_and(|w| w.id == resp.id)); - ctx.data_mut(|d| d.insert_temp(resp.id, bare)); - } - if resp.double_clicked() { - toggle_maximize(ctx); - } else if resp.drag_started_by(PointerButton::Primary) && ctx.data(|d| d.get_temp(resp.id).unwrap_or(false)) { - ctx.send_viewport_cmd(ViewportCommand::StartDrag); - handed_to_os(ctx); - } -} - -/// The window manager runs the move or resize from here, and on X11 and Wayland it keeps the -/// button release: egui would hold the drag and the button until the next press, and that press -/// would start no drag on the bar or a resize zone (emilk/egui#7959). End both now. On Windows -/// winit hands the release back, which then ends nothing. -fn handed_to_os(ctx: &egui::Context) { - ctx.stop_dragging(); - ctx.input_mut(|i| i.pointer = Default::default()); -} - -/// The buttons of [`VectorcraftApp::caption_layout`] at the left and right ends of `bar` (the app -/// bar's outer rect), full bar height down to its bottom border, flush with the window's edges so a -/// maximized window's corner hits the outermost button. Close runs `app.quit`, which asks about -/// unsaved documents first. -pub fn caption_buttons(app: &mut VectorcraftApp, ui: &mut Ui, bar: Rect) { - let t = Tokens::get(ui.ctx()); - let max = maximized(ui.ctx()); - let mut clicked = None; - let layout = &app.caption_layout; - let left = layout.left.iter().enumerate().map(|(i, c)| (*c, bar.left() + i as f32 * BUTTON_WIDTH)); - let right_start = bar.right() - layout.right_width(); - let right = layout.right.iter().enumerate().map(|(i, c)| (*c, right_start + i as f32 * BUTTON_WIDTH)); - let placed: Vec<(Caption, f32)> = left.chain(right).collect(); - for (c, x) in placed { - let r = Rect::from_min_size(pos2(x, bar.top()), vec2(BUTTON_WIDTH, bar.height() - 1.0)); - let resp = ui.interact(r, caption_id(c), Sense::click()); - let close = c == Caption::Close; - let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) { - (true, _) if close => t.caption_close.gamma_multiply(0.8), - (_, true) if close => t.caption_close, - (true, _) => t.tool_active, - (_, true) => t.hover, - _ => egui::Color32::TRANSPARENT, - }; - ui.painter().rect_filled(r, 0.0, fill); - let ink = if close && resp.hovered() { t.caption_close_text } else { t.icon }; - paint_glyph(ui, c, max, r.center(), Stroke::new(1.0, ink)); - let tip = match c { - Caption::Minimize => tl!("Minimize"), - Caption::Maximize if max => tl!("Restore"), - Caption::Maximize => tl!("Maximize"), - Caption::Close => tl!("Close"), - }; - if resp.on_hover_text(tip).clicked() { - clicked = Some(c); - } - } - match clicked { - Some(Caption::Minimize) => ui.ctx().send_viewport_cmd(ViewportCommand::Minimized(true)), - Some(Caption::Maximize) => toggle_maximize(ui.ctx()), - Some(Caption::Close) => { - app.run("app.quit", json!({})).ok(); - } - None => {} - } -} - -/// The 10 pt line glyphs of the caption buttons. -fn paint_glyph(ui: &Ui, c: Caption, maximized: bool, at: egui::Pos2, s: Stroke) { - let p = ui.painter(); - let g = Rect::from_center_size(at, vec2(10.0, 10.0)); - match c { - Caption::Minimize => { - p.line_segment([g.left_center(), g.right_center()], s); - } - // Restore: a front square with the corner of the one behind it. - Caption::Maximize if maximized => { - let front = Rect::from_min_max(g.min + vec2(0.0, 2.0), g.max - vec2(2.0, 0.0)); - p.rect_stroke(front, 0.0, s, egui::StrokeKind::Middle); - p.line(vec![g.min + vec2(2.0, 2.0), g.min + vec2(2.0, 0.0), g.right_top(), g.max - vec2(0.0, 2.0), g.max - vec2(2.0, 2.0)], s); - } - Caption::Maximize => { - p.rect_stroke(g, 0.0, s, egui::StrokeKind::Middle); - } - Caption::Close => { - p.line_segment([g.left_top(), g.right_bottom()], s); - p.line_segment([g.right_top(), g.left_bottom()], s); - } - } -} - -/// The edge and corner zones of a window with content rect `w`: (zone, direction, cursor). Corners -/// come last so they win where they overlap the edges. -fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] { - use ResizeDirection::*; - let (e, c) = (EDGE, CORNER); - [ - (Rect::from_min_max(w.left_top(), pos2(w.right(), w.top() + e)), North, CursorIcon::ResizeVertical), - (Rect::from_min_max(pos2(w.left(), w.bottom() - e), w.right_bottom()), South, CursorIcon::ResizeVertical), - (Rect::from_min_max(w.left_top(), pos2(w.left() + e, w.bottom())), West, CursorIcon::ResizeHorizontal), - (Rect::from_min_max(pos2(w.right() - e, w.top()), w.right_bottom()), East, CursorIcon::ResizeHorizontal), - (Rect::from_min_size(w.left_top(), vec2(c, c)), NorthWest, CursorIcon::ResizeNwSe), - (Rect::from_min_size(w.right_top() - vec2(c, 0.0), vec2(c, c)), NorthEast, CursorIcon::ResizeNeSw), - (Rect::from_min_size(w.left_bottom() - vec2(0.0, c), vec2(c, c)), SouthWest, CursorIcon::ResizeNeSw), - (Rect::from_min_size(w.right_bottom() - vec2(c, c), vec2(c, c)), SouthEast, CursorIcon::ResizeNwSe), - ] -} - -/// Invisible resize zones along the window's edges, above everything else; a press in one starts -/// an OS resize in that direction. None while the window is maximized or fullscreen. -pub fn resize_zones(ui: &mut Ui) { - let ctx = ui.ctx().clone(); - if maximized(&ctx) || ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) { - return; - } - let w = ctx.content_rect(); - let layer = LayerId::new(Order::Foreground, Id::unique("titlebar-resize")); - let zui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(w)); - for (i, (r, dir, cursor)) in zones(w).into_iter().enumerate() { - // Not focusable (`Sense::drag()` is): Tab does not stop on the zones. - let resp = zui.interact(r, Id::unique(("titlebar-resize", i)), Sense::DRAG).on_hover_cursor(cursor); - if resp.drag_started_by(PointerButton::Primary) { - ctx.send_viewport_cmd(ViewportCommand::BeginResize(dir)); - handed_to_os(&ctx); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use egui::{Event, Pos2, RawInput, ViewportId}; - use vectorcraft_engine::Session; - - /// A headless window `width` pt wide showing the app bar (as the title bar) and the resize zones. - struct Win { - ctx: egui::Context, - app: VectorcraftApp, - width: f32, - time: f64, - maximized: bool, - } - - impl Win { - fn new(width: f32) -> Self { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, Default::default()); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - app.custom_titlebar = true; - Self { ctx, app, width, time: 0.0, maximized: false } - } - - fn frame(&mut self, events: Vec) -> egui::FullOutput { - self.time += 0.05; - let mut input = RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), - time: Some(self.time), - events, - ..Default::default() - }; - if let Some(v) = input.viewports.get_mut(&ViewportId::ROOT) { - v.maximized = Some(self.maximized); - } - let app = &mut self.app; - let mut out = self.ctx.run_ui(input, |ui| { - crate::chrome::app_bar(app, ui); - resize_zones(ui); - }); - out.textures_delta.clear(); - out - } - } - - fn texts(out: &egui::FullOutput) -> Vec<(String, Rect)> { - fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { - match s { - egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), - egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), - _ => {} - } - } - let mut v = vec![]; - out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); - v - } - - fn button(p: Pos2, pressed: bool) -> Event { - Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } - } - - impl Win { - /// Frames for a pointer gesture: move to `path[0]`, press, move along `path`, release. The - /// viewport commands the frames sent. - fn gesture(&mut self, path: &[Pos2]) -> Vec { - let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true)]]; - events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); - events.push(vec![button(*path.last().unwrap_or(&path[0]), false)]); - events.into_iter().flat_map(|e| self.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()).collect() - } - - fn click(&mut self, p: Pos2) -> Vec { - self.gesture(&[p]) - } - - fn caption(&self, c: Caption) -> Rect { - self.ctx.read_response(caption_id(c)).map(|r| r.rect).unwrap_or(Rect::NOTHING) - } - - /// The bar's clickable widgets other than its background and the caption buttons. - fn bar_widgets(&self) -> Vec { - let skip: Vec = std::iter::once(Id::unique("titlebar-drag")).chain(CAPTIONS.map(caption_id)).collect(); - self.ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .filter(|(l, _)| l.order != Order::Foreground) - .flat_map(|(_, ws)| ws.iter()) - .filter(|w| w.sense.senses_click() && w.rect.top() < 32.0 && !skip.contains(&w.id)) - .map(|w| w.rect) - .collect() - }) - } - } - - #[test] - fn caption_buttons_take_the_right_end_and_nothing_overlaps_down_to_800_pt() { - for width in [800.0, 1100.0, 1440.0] { - let mut w = Win::new(width); - w.frame(vec![]); - let out = w.frame(vec![]); - let [min, max, close] = CAPTIONS.map(|c| w.caption(c)); - assert_eq!((close.right(), close.top()), (width, 0.0), "Close sits in the window's corner at {width}"); - assert!(close.height() >= 30.0 && [min, max, close].iter().all(|r| r.width() == BUTTON_WIDTH)); - assert_eq!((min.right(), max.right()), (max.left(), close.left())); - let widgets = w.bar_widgets(); - assert!(widgets.len() >= 11, "home, eight menus, workspace switcher, search: {widgets:?}"); - for (i, a) in widgets.iter().enumerate() { - assert!(a.right() <= min.left() - 8.0, "{a:?} runs into the caption buttons at {width}"); - for b in &widgets[i + 1..] { - assert!(!a.shrink(0.5).intersects(b.shrink(0.5)), "{a:?} overlaps {b:?} at {width}"); - } - } - // Wide windows show the whole group, the search field included; narrow ones drop the - // community button first, and the search field goes before the search icon. - let texts: Vec = texts(&out).into_iter().map(|(t, _)| t).collect(); - let has = |s: &str| texts.iter().any(|t| t == s); - assert_eq!(has("Discord"), width > 1000.0, "{width}: {texts:?}"); - if width > 1000.0 { - assert!(has("Search commands"), "the search field shows at {width}: {texts:?}"); - } - // The search's tooltip text is not painted in the bar. - assert!(!has("Search commands, tools, panels and effects"), "{width}: {texts:?}"); - } - } - - /// The caption layout decides which buttons the bar draws and at which end, each end in its - /// listed order: Close alone at the right, all three at the left with Close outermost, and a - /// split. The bar's other controls stay between the two groups, and Close works at either end. - #[test] - fn caption_buttons_follow_the_caption_layout() { - use Caption::*; - let width = 1100.0; - for (left, right) in [(vec![], vec![Close]), (vec![Close, Minimize, Maximize], vec![]), (vec![Close], vec![Minimize, Maximize])] { - let label = format!("{left:?} : {right:?}"); - let mut w = Win::new(width); - w.app.caption_layout = CaptionLayout { left: left.clone(), right: right.clone() }; - w.frame(vec![]); - w.frame(vec![]); - for (i, c) in left.iter().enumerate() { - let r = w.caption(*c); - assert_eq!((r.left(), r.top(), r.width()), (i as f32 * BUTTON_WIDTH, 0.0, BUTTON_WIDTH), "{c:?} in {label}"); - } - for (i, c) in right.iter().enumerate() { - let r = w.caption(*c); - let right_edge = width - (right.len() - 1 - i) as f32 * BUTTON_WIDTH; - assert_eq!((r.right(), r.top(), r.width()), (right_edge, 0.0, BUTTON_WIDTH), "{c:?} in {label}"); - } - for c in CAPTIONS.into_iter().filter(|c| !left.contains(c) && !right.contains(c)) { - assert_eq!(w.caption(c), Rect::NOTHING, "{c:?} is not drawn in {label}"); - } - let (start, end) = (left.len() as f32 * BUTTON_WIDTH, width - right.len() as f32 * BUTTON_WIDTH); - let widgets = w.bar_widgets(); - assert!(widgets.len() >= 11, "home, eight menus, workspace switcher, search in {label}: {widgets:?}"); - for r in &widgets { - assert!(r.left() >= start + 8.0 && r.right() <= end - 8.0, "{r:?} runs into the caption buttons in {label}"); - } - let close = w.caption(Close).center(); - w.click(close); - assert_eq!(w.app.ui.status, "quit", "Close in {label}"); - } - } - - #[test] - fn close_runs_the_quit_flow_instead_of_closing_the_window() { - let mut w = Win::new(1000.0); - w.app.run("file.new", serde_json::json!({"width": 100, "height": 100})).unwrap(); - w.app.run("shape.rectangle", serde_json::json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - w.frame(vec![]); - let close = w.caption(Caption::Close).center(); - let cmds = w.click(close); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::Close)), "{cmds:?}"); - let dialog = w.app.ui.dialog.as_ref().map(|d| d.kind.clone()); - assert_eq!(dialog.as_deref(), Some(crate::unsaved::KIND), "a modified document asks first"); - assert_ne!(w.app.ui.status, "quit"); - // Nothing to save: the host is told to quit. - w.app.ui.dialog = None; - w.app.session.doc_mut().unwrap().mark_saved(); - w.click(close); - assert_eq!(w.app.ui.status, "quit"); - } - - #[test] - fn minimize_and_maximize_follow_the_window_state() { - let mut w = Win::new(1000.0); - w.frame(vec![]); - let (min, max) = (w.caption(Caption::Minimize).center(), w.caption(Caption::Maximize).center()); - assert!(w.click(min).contains(&ViewportCommand::Minimized(true))); - assert!(w.click(max).contains(&ViewportCommand::Maximized(true))); - w.maximized = true; - assert!(w.click(max).contains(&ViewportCommand::Maximized(false)), "Restore"); - } - - #[test] - fn empty_bar_space_drags_and_double_click_maximizes() { - let mut w = Win::new(1440.0); - w.frame(vec![]); - let empty = pos2(700.0, 16.0); - assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); - let cmds = w.gesture(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]); - assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); - // Double-click toggles maximize. - let mut cmds = w.click(empty); - cmds.extend(w.click(empty)); - assert!(cmds.contains(&ViewportCommand::Maximized(true)), "{cmds:?}"); - w.maximized = true; - w.time += 1.0; - let mut cmds = w.click(empty); - cmds.extend(w.click(empty)); - assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}"); - // Widgets keep their clicks: dragging from a menu title doesn't move the window. - let file = texts(&w.frame(vec![])).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r.center()); - let file = file.expect("the File menu title"); - let cmds = w.gesture(&[file, file + vec2(12.0, 4.0), file + vec2(30.0, 8.0)]); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); - } - - #[test] - fn a_double_click_on_the_macos_app_bar_zooms_the_window() { - // macOS keeps the system decorations, with the app bar under its transparent title bar - // (#1932); Windows and Linux with the system title bar leave it to the OS's bar. - let mut w = Win::new(1440.0); - w.app.custom_titlebar = false; - w.frame(vec![]); - let empty = pos2(700.0, 16.0); - assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); - let mut cmds = w.click(empty); - cmds.extend(w.click(empty)); - assert_eq!(cmds.contains(&ViewportCommand::Maximized(true)), cfg!(target_os = "macos"), "{cmds:?}"); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::Maximized(false))), "{cmds:?}"); - } - - #[test] - fn edge_zones_resize_unless_maximized() { - use ResizeDirection::*; - let mut w = Win::new(1000.0); - w.frame(vec![]); - for (p, dir) in [ - (pos2(1.0, 300.0), West), - (pos2(998.0, 300.0), East), - (pos2(500.0, 1.0), North), - (pos2(500.0, 598.0), South), - (pos2(2.0, 2.0), NorthWest), - (pos2(997.0, 3.0), NorthEast), - (pos2(3.0, 597.0), SouthWest), - (pos2(998.0, 598.0), SouthEast), - ] { - let cmds = w.gesture(&[p, p + vec2(6.0, 6.0)]); - assert_eq!(cmds, vec![ViewportCommand::BeginResize(dir)], "at {p:?}"); - } - let out = w.frame(vec![Event::PointerMoved(pos2(1.0, 300.0))]); - assert_eq!(out.platform_output.cursor_icon, CursorIcon::ResizeHorizontal); - // Maximized: no zones, and the window's top-right corner is Close. - w.maximized = true; - let cmds = w.gesture(&[pos2(1.0, 300.0), pos2(8.0, 300.0)]); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}"); - assert!(w.click(pos2(999.5, 0.5)).is_empty()); - assert_eq!(w.app.ui.status, "quit"); - } - - /// Tab goes through the bar's controls and does not stop on the bar's background or on the - /// resize zones, which only the pointer uses. - #[test] - fn tab_skips_the_bar_background_and_the_resize_zones() { - let mut w = Win::new(1000.0); - w.frame(vec![]); - let ctx = w.ctx.clone(); - let stops = crate::widgets::accessibility_tests::tab_stops(&ctx, 40, |events| { - w.frame(events); - }); - for c in CAPTIONS { - assert!(stops.contains(&caption_id(c)), "Tab reaches the {c:?} button: {stops:?}"); - } - let regions: Vec = std::iter::once(Id::unique("titlebar-drag")).chain((0..8usize).map(|i| Id::unique(("titlebar-resize", i)))).collect(); - assert!(!stops.iter().any(|id| regions.contains(id)), "{stops:?}"); - } - - #[test] - fn a_move_or_resize_the_window_manager_finished_does_not_block_the_next_resize() { - use ResizeDirection::*; - fn sent(mut out: egui::FullOutput) -> Vec { - out.viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default() - } - // After BeginResize or StartDrag the window manager owns the pointer and, on X11 and - // Wayland, keeps the release: the app sees the press and the pointer leaving, nothing else. - fn handed_off(w: &mut Win, path: &[Pos2]) -> Vec { - let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true)]]; - events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); - events.push(vec![Event::PointerGone]); - events.into_iter().flat_map(|e| sent(w.frame(e))).collect() - } - let (zone, out) = (pos2(1.0, 300.0), pos2(-39.0, 300.0)); - let mut w = Win::new(1440.0); - w.frame(vec![]); - assert_eq!(handed_off(&mut w, &[zone]), vec![ViewportCommand::BeginResize(West)]); - assert_eq!(w.gesture(&[zone, out]), vec![ViewportCommand::BeginResize(West)], "the next resize"); - let (empty, moved) = (pos2(700.0, 16.0), pos2(712.0, 20.0)); - assert_eq!(handed_off(&mut w, &[empty, moved]), vec![ViewportCommand::StartDrag]); - assert_eq!(w.gesture(&[zone, out]), vec![ViewportCommand::BeginResize(West)], "a resize after a move"); - // Windows hands the release back: it ends nothing, and a click right after it stays a single one. - assert_eq!(handed_off(&mut w, &[empty, moved]), vec![ViewportCommand::StartDrag]); - let mut cmds = sent(w.frame(vec![button(moved, false)])); - cmds.extend(w.click(moved)); - assert!(cmds.is_empty(), "{cmds:?}"); - } -}