hub-w1: net change of 1 commits

- hub-w1: written by an agent
This commit is contained in:
bflatastic
2026-11-21 23:21:59 +07:00
parent 06c380da5c
commit d4d0d51d7c
13 changed files with 1234 additions and 2108 deletions
+3
View File
@@ -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" }
+23 -9
View File
@@ -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 }
+319 -375
View File
@@ -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<dyn ClipboardBackend>` needs the framework's `impl ClipboardBackend for Box<dyn ClipboardBackend>` (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<ControlRequest>) -> 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<Arc<AutomationRoots>> {
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,
}
}
+5 -36
View File
@@ -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<Value, String> {
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<Value, String> {
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, &params).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, &params)
{
@@ -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, &params, 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, &params, v);
}
panels::swatches::after_command(self, id, &params, 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(())
}
+6 -56
View File
@@ -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<vectorcraft_tools::ScreenFrame> {
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())),
}
}
}
+18 -279
View File
@@ -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<egui::DroppedFileHandle>, pos: Option<egui::Pos2>, 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> = [
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<egui::Event> = 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<egui::Event> = 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);
}
}
+78
View File
@@ -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<CloseDecision> {
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::<UnsavedChangesDialog>().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");
}
+99 -21
View File
@@ -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<craft::ui::canvas::Momentary>,
/// [`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<vectorcraft_doc::OrientedBox>)>,
@@ -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<u64, (u64, u64)>,
/// [`CacheKey::placed`] by document uid ([`canvas::placed_key`]).
/// [`CacheKey::placed`] by document uid ([`canvas::raster::placed_key`]).
pub placed_keys: std::collections::HashMap<u64, PlacedKey>,
/// 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<egui::Rect>,
/// 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<canvas::ViewKey>,
/// 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<craft::draw::ui::shape::LiveShape>), Option<f64>)>,
/// The Image Trace presets, for the session's preset revision.
pub(crate) trace_presets: Option<(u64, Arc<crate::panels::image_trace::PresetList>)>,
/// What the Image Trace panel traces, for (document uid, revision).
pub(crate) trace_target: Option<((u64, u64), Arc<crate::panels::image_trace::Target>)>,
/// 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<crate::panels::css_properties::Shown>)>,
/// 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<str>)>,
/// The Export for Screens dialog's artboard thumbnails, for (document uid, revision).
pub artboard_thumbs: Option<((u64, u64), Vec<Option<egui::TextureHandle>>)>,
/// 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<SystemTime>)>,
/// 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<NodeId>), Vec<u32>)>,
/// 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<Arc<crate::panels::appearance::Summary>>)>,
/// 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<crate::panels::transparency::State>)>,
/// 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<crate::panels::variables::Rows>)>,
/// The Map Art surfaces of the 3D dialog's object.
pub map_surfaces: Option<MapSurfacesCache>,
/// The command palette's built rows, for the palette's build key.
pub(crate) palette: Option<(crate::palette::BuildKey, Arc<crate::palette::Built>)>,
}
/// [`CanvasCache::map_surfaces`]: the surfaces and what they were computed for.
pub type MapSurfacesCache = (MapSurfacesKey, Arc<Vec<vectorcraft_effects::MapSurface>>);
/// 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<usize>,
/// The effect's index in its list.
pub index: Option<usize>,
/// 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,
-25
View File
@@ -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<Instant> = LazyLock::new(Instant::now);
START.elapsed().as_secs_f64()
}
#[cfg(target_arch = "wasm32")]
{
use std::sync::LazyLock;
use web_time::Instant;
static START: LazyLock<Instant> = 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
}
+149 -192
View File
@@ -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<u64>,
/// 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<clipboard_probe::Probe>,
/// 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<craft::platform::clipboard::ClipboardProbe>,
/// 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<Host>,
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<String>,
/// Last confirmed Warp Options (bend, distortion, orientation) for the next new warp dialog.
pub last_warp: Option<serde_json::Value>,
/// The Character panel field that takes the keyboard focus when the panel next draws it
/// ([`panels::character::highlight`]).
pub(crate) character_focus: Option<panels::character::Field>,
/// 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<Receiver<ControlRequest>>,
/// 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<ControlRequest>,
/// 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<PendingScreenshot>,
/// `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<control::PendingPointerReply>,
/// Admitted captures whose settled frame has not come yet (issued one at a time).
queued_screenshots: Vec<QueuedScreenshot>,
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<egui::Event>,
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<ControlChannel>,
/// 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<egui::Context>,
/// 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<egui::Rect>,
/// 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<control::RotateViewPress>,
/// Hover position in document coordinates.
pub hover_doc: Option<vectorcraft_geom::Point>,
/// 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<String>,
clipboard_published: Option<String>,
pub(crate) clipboard_in: Option<vectorcraft_engine::cmd::clipboard::Flavour>,
/// 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<String>,
@@ -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<egui::Modifiers>,
/// 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<screen_color::Waiting>,
/// 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>, 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<craft::font_catalog::Watch>,
/// 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<egui::Id>,
/// 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<egui::Event>,
pub(crate) forwarded_modifiers: Option<egui::Modifiers>,
/// 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<egui::Event>,
/// 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<unsaved::Closing>,
/// The Preferences window, while it is open.
pub(crate) prefs: Option<Box<prefs_dialog::PrefsWindow>>,
/// The preferences the interface last applied, to apply only what changed.
pub(crate) applied_prefs: Option<prefs_dialog::Applied>,
/// 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<shortcut_editor::ShortcutsDialogState>,
/// 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<craft::keymap::Overrides>,
/// 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<GestureId, UndoScope>,
/// 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<dialogs::three_d::Session>,
/// 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<dialogs::plugin::PluginDialog>,
/// 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<dialogs::check_spelling::SpellingWalk>,
/// 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<dialogs::justification::Open>,
/// 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<dialogs::profile_mismatch::PasteAsk>,
/// The missing links' questions, while they are asked.
pub(crate) link_asks: Option<dialogs::missing_links::LinkAsk>,
/// 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<String>,
/// 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<ime::IncomingComposition>,
pub(crate) ime_resets: egui::ViewportIdMap<ime::ResetGuard>,
/// 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<vectorcraft_engine::UndoScope>,
/// 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<Arc<AutomationRoots>>,
/// 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<dialogs::plugin::PendingInstall>,
@@ -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<dialogs::profile_mismatch::PendingOpen>,
/// 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<String>,
/// 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<f64>,
/// 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<String>,
/// The host iteration [`Self::tick`] ran in (`None`: never): once per iteration, never per pass.
tick_iteration: Option<u64>,
/// 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<InputFrame>,
/// 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<InputFrame>,
/// 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<shortcuts::HeldTool>,
/// 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<egui::Event>,
/// 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<AtomicBool>,
/// 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<GeometryStamp>,
}
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<dyn craft::host::Jobs> {
match self.ui_ctx.as_ref().and_then(Host::try_of_ctx) {
Some(host) => host.jobs_shared().clone(),
None => Arc::new(craft::host::InlineJobs),
}
}
}
File diff suppressed because it is too large Load Diff
+24
View File
@@ -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
}
-517
View File
@@ -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<Caption>,
pub right: Vec<Caption>,
}
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<Event>) -> 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<ViewportCommand> {
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<ViewportCommand> {
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<Rect> {
let skip: Vec<Id> = 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<String> = 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<Id> = 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<ViewportCommand> {
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<ViewportCommand> {
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:?}");
}
}