diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..66cf378999 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -20,13 +20,15 @@ vectorcraft-ui-egui = { workspace = true } craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } +craft = { workspace = true, features = ["ui", "keymap"] } egui = { workspace = true } +egui_extras = { workspace = true } log = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } -rfd = { workspace = true, features = ["file-handle-inner"] } + wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 6d9e0cadd5..eb62910fe1 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -5,19 +5,21 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::{Arc, Mutex}; +// PLAN: assumed `craft::host` re-exports `Files`, `FileError`, `PendingPick`, `PickAnswer`, `PickId`, `PickKind`, `PickRequest`, `Picked`, `Wake`, `AppInfo`, `InlineJobs`; `craft::window` re-exports `SystemWindows`; `craft::ui::runtime` re-exports `PenSource` +use craft::host::target::ShellInfo; +use craft::host::{AppInfo, FileError, Files, InlineJobs, PendingPick, PickAnswer, PickId, PickKind, PickRequest, Picked, Wake}; +use craft::ui::InstallSpec; +use craft::ui::shell::embed; +use craft::window::SystemWindows; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore}; -use vectorcraft_engine::cmd::scripts::RUN_EXTS; -use vectorcraft_engine::script::MAX_SOURCE_BYTES; -use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox; use vectorcraft_ui_egui::graphics::GraphicsLoss; use vectorcraft_ui_egui::i18n; use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox}; use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; -use vectorcraft_ui_egui::stylus::StylusFeed; -use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp}; +use vectorcraft_ui_egui::{Services, VectorcraftApp}; use wasm_bindgen::JsCast as _; use crate::locks::WebLocks; @@ -25,14 +27,12 @@ use crate::pencil::SharedPointers; pub(crate) type Inbox = Arc)>>>; -/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and -/// `page_inbox`). +/// The files waiting to open, by where they came from (`Services::inbox` and `page_inbox`). The +/// browser's file chooser answers through [`WebFiles`], not here. #[derive(Clone, Default)] struct OpenInboxes { /// Dropped on the page. dropped: Inbox, - /// The open picker's answers. - picked: PickedInbox, /// Handed over by the page's script (`window.vectorcraft.openFile`). page: Inbox, } @@ -62,7 +62,6 @@ struct Host { runner: eframe::WebRunner, inbox: OpenInboxes, place_inbox: PlaceInbox, - script_inbox: ScriptInbox, drag: DragPos, pasted: Rc>, /// Pen and finger input read from the page's Pointer Events (`crate::pencil`). @@ -84,7 +83,7 @@ pub fn start() { // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the // startup fonts, without holding up the start. Text in those scripts painted later (a saved // interface language, another one chosen, a layer or file name) has its face fetched then. - vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + // PLAN: the served-face fetcher (B2) replaces `on_missing_glyphs`; its `UiFonts` wiring is shell-w10's (`fonts.rs`). crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. @@ -96,7 +95,6 @@ pub fn start() { runner: eframe::WebRunner::new(), inbox: OpenInboxes::default(), place_inbox: Arc::default(), - script_inbox: Arc::default(), drag: DragPos::default(), pasted: Rc::default(), pointers: SharedPointers::default(), @@ -130,7 +128,6 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option PenSource` (shell-w13's `pencil.rs`), in place of `stylus()`. + let pen = host.pointers.borrow().pen(); + let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen); + embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + let wake = { + let ctx = ctx.clone(); + Wake::new(move || ctx.request_repaint()) + }; + // The web saves no preferences: the host keeps its default in-memory sections. + craft::host::Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") }) + // PLAN: assumed `vectorcraft_ui_egui::i18n::shared() -> Arc` + .i18n(i18n::shared()) + .jobs(Arc::new(InlineJobs)) + .files(Arc::new(WebFiles::new(wake))) + .install(ctx); + let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone()); let app = match taken.borrow_mut().take() { Some(mut app) => { // The old services asked the old context for frames. @@ -393,7 +404,7 @@ impl eframe::App for WebShell { } let Some(app) = &mut self.app else { return }; app.tick(ctx); - app.finish_ime_logic(ctx); + embed::logic(ctx, || app.close_decision()); } /// Forward host-gathered pointer events into this frame's raw input, then let the app apply its @@ -403,15 +414,16 @@ impl eframe::App for WebShell { // A Cmd+V comes as its key and as a Paste: one paste (#5555). crate::keys::drop_paste_key_presses(&mut raw.events); if let Some(app) = &mut self.app { - app.raw_input_hook(ctx, raw); + embed::before_input(ctx, |out| app.frame_input(out)); } } /// Read host paste and drop input once in the UI phase, hand files to the app's drop targets, run /// the app UI, then poll control replies. - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); if let Some(app) = &mut self.app { + embed::before_ui(&ctx, frame); // DOM paste and drop are host input: read them in the UI phase, once per pass, not in // `logic` where a hidden tab replays the last shown frame's input. let pasted = self.host.pasted.borrow_mut().flavour.take(); @@ -448,121 +460,145 @@ impl eframe::App for WebShell { } } -fn services( - inbox: OpenInboxes, - place_inbox: PlaceInbox, - script_inbox: ScriptInbox, - ctx: egui::Context, - locks: Option, - stylus: StylusFeed, -) -> Services { - let open_inbox = inbox.picked.clone(); - let picked = place_inbox.clone(); - let place_ctx = ctx.clone(); - let screen_color = eye_dropper(ctx.clone()); - let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone()); +fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option) -> Services { Services { - // File › Scripts › Other Script…: the picked file goes to the warning before it runs. - script_async: Some(Box::new(move || { - let inbox = script_picked.clone(); - let ctx = script_ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts"); - let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else { - return; - }; - let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) }; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes)); - ctx.request_repaint(); - }); - })), - script_inbox: Some(script_inbox), - // File → Place…: the picked files go to the Place dialog. - place_async: Some(Box::new(move || { - let inbox = picked.clone(); - let ctx = place_ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let dialog = - fileio::place_filters().fold(rfd::AsyncFileDialog::new().set_title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { - d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); - let Some(files) = dialog.pick_files().await else { - return; - }; - let mut arrived = vec![]; - for f in files { - arrived.push(PlaceArrival { name: f.file_name(), bytes: f.read().await, drop: None }); - } - inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(arrived); - ctx.request_repaint(); - }); - })), - place_inbox: Some(place_inbox), - open_async: Some(Box::new(move || { - let inbox = open_inbox.clone(); - let ctx = ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| { - d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts) - }); - // A canceled pick answers `None`. - let answer = match dialog.pick_file().await { - Some(file) => Some((file.file_name(), file.read().await)), - None => None, - }; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer); - ctx.request_repaint(); - }); - })), - // Sample Color from Screen: the browser's EyeDropper, where it has one. - screen_color, // A download that couldn't be started fails the save or export it is for (#1693). download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))), inbox: Some(inbox.dropped), - picked_inbox: Some(inbox.picked), page_inbox: Some(inbox.page), + // Files dropped on the canvas to place. + place_inbox: Some(place_inbox), recovery_store: Some(Arc::new(BrowserStore { locks })), // File → Print: the browser's print dialog. print: Some(Box::new(BrowserPrint)), - // The pen's end, from the page's Pointer Events (`crate::pencil`). - stylus: Some(stylus), ..Default::default() } } -/// Sample Color from Screen in the browser: the EyeDropper API -/// (), which only some browsers have, -/// on secure (HTTPS) pages; `None` without it, and the command is then gray. `open()` needs a -/// transient user activation (otherwise it fails with a `NotAllowedError`) and resolves with the -/// picked color's `sRGBHex`; Escape rejects it with an `AbortError`. -fn eye_dropper(ctx: egui::Context) -> Option { - use js_sys::{Function, Promise, Reflect}; - use wasm_bindgen::JsValue; - let window = web_sys::window()?; - let constructor = Reflect::get(&window, &JsValue::from_str("EyeDropper")).ok()?.dyn_into::().ok()?; - Some(Box::new(move || { - let eye = Reflect::construct(&constructor, &js_sys::Array::new()).map_err(js_err)?; - let open = Reflect::get(&eye, &JsValue::from_str("open")).map_err(js_err)?.dyn_into::().map_err(js_err)?; - let promise = open.call0(&eye).map_err(js_err)?.dyn_into::().map_err(js_err)?; - let (tx, rx) = std::sync::mpsc::channel(); - let ctx = ctx.clone(); - wasm_bindgen_futures::spawn_local(async move { - let answer = match wasm_bindgen_futures::JsFuture::from(promise).await { - Ok(result) => Reflect::get(&result, &JsValue::from_str("sRGBHex")) - .ok() - .and_then(|hex| hex.as_string()) - .and_then(|hex| vectorcraft_ui_egui::screen_color::srgb_from_hex(&hex)) - .map(Some) - .ok_or_else(|| "the browser's EyeDropper answered no color".to_string()), - Err(e) if Reflect::get(&e, &JsValue::from_str("name")).ok().and_then(|n| n.as_string()).as_deref() == Some("AbortError") => Ok(None), - Err(e) => Err(js_err(e)), - }; - // The UI may be gone (the page closing): nothing waits for the color then. - let _ = tx.send(answer); - ctx.request_repaint(); +/// The browser's file chooser behind the host's [`Files`]: an Open pick reads the chosen files and +/// answers their contents. The web saves by downloading (`io::save`), so Save and Folder picks have +/// no chooser and answer `Unavailable`. +#[derive(Clone)] +struct WebFiles { + picks: Arc>, + wake: Wake, +} + +/// The picks [`WebFiles`] has asked the browser for and those answered, in order. +#[derive(Default)] +struct WebPicks { + next: u64, + waiting: Vec<(PickId, PickRequest)>, + answered: Vec, +} + +impl WebFiles { + fn new(wake: Wake) -> Self { + Self { picks: Arc::default(), wake } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, WebPicks> { + self.picks.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Settles pick `id` with `picked`; a pick forgotten meanwhile has no use for it. + fn answer(&self, id: PickId, picked: Picked) { + { + let mut picks = self.lock(); + let Some(at) = picks.waiting.iter().position(|(waiting, _)| *waiting == id) else { return }; + let (_, request) = picks.waiting.remove(at); + picks.answered.push(PickAnswer { id, request, picked }); + } + self.wake.wake(); + } + + /// Opens the browser's file chooser for `request`. The browser opens it only from the user's own + /// click, which is where an Open pick is asked for. + fn choose(&self, id: PickId, request: &PickRequest) -> Result<(), String> { + let document = web_sys::window().and_then(|w| w.document()).ok_or("no document")?; + let input: web_sys::HtmlInputElement = document.create_element("input").map_err(js_err)?.dyn_into().map_err(|_| "not an input")?; + input.set_type("file"); + input.set_multiple(request.kind == PickKind::OpenMany); + let accept: Vec = request.filters.iter().flat_map(|f| f.extensions.iter().map(|e| format!(".{e}"))).collect(); + if !accept.is_empty() { + input.set_accept(&accept.join(",")); + } + let (chosen, source) = (self.clone(), input.clone()); + let on_change = wasm_bindgen::closure::Closure::once_into_js(move || { + let files: Vec = source.files().map(|list| (0..list.length()).filter_map(|i| list.get(i)).collect()).unwrap_or_default(); + wasm_bindgen_futures::spawn_local(async move { + let mut read = Vec::new(); + for file in files { + match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await { + Ok(buf) => read.push((file.name(), js_sys::Uint8Array::new(&buf).to_vec())), + Err(e) => log::error!("couldn't read the chosen file {}: {}", file.name(), js_err(e)), + } + } + chosen.answer(id, if read.is_empty() { Picked::Cancelled } else { Picked::Contents(read) }); + }); }); - Ok(rx) - })) + let cancelled = self.clone(); + let on_cancel = wasm_bindgen::closure::Closure::once_into_js(move || cancelled.answer(id, Picked::Cancelled)); + for (kind, listener) in [("change", &on_change), ("cancel", &on_cancel)] { + input.add_event_listener_with_callback(kind, listener.unchecked_ref()).map_err(js_err)?; + } + input.click(); + Ok(()) + } +} + +impl Files for WebFiles { + fn pick(&self, request: PickRequest) -> PickId { + let id = { + let mut picks = self.lock(); + picks.next += 1; + let id = PickId(picks.next); + picks.waiting.push((id, request.clone())); + id + }; + let picked = if matches!(request.kind, PickKind::Open | PickKind::OpenMany) { + match self.choose(id, &request) { + Ok(()) => return id, + Err(e) => Picked::Unavailable(e), + } + } else { + Picked::Unavailable("the browser downloads what is saved and has no folders".into()) + }; + self.answer(id, picked); + id + } + + fn take_answer(&self, id: PickId) -> Option { + let mut picks = self.lock(); + let at = picks.answered.iter().position(|a| a.id == id)?; + Some(picks.answered.remove(at).picked) + } + + fn forget(&self, id: PickId) { + let mut picks = self.lock(); + picks.waiting.retain(|(waiting, _)| *waiting != id); + picks.answered.retain(|a| a.id != id); + } + + fn pick_pending(&self) -> bool { + !self.lock().waiting.is_empty() + } + + fn pending_pick(&self) -> Option { + self.lock().waiting.first().map(|(_, request)| PendingPick { request: request.clone(), sheet: false }) + } + + fn read(&self, _path: &std::path::Path) -> Result, FileError> { + Err(FileError::Unsupported) + } + + fn write(&self, _path: &std::path::Path, _bytes: &[u8]) -> Result<(), FileError> { + Err(FileError::Unsupported) + } + + fn last_folder(&self, _purpose: &str) -> Option { + None + } } /// Data Recovery's store on the web: the browser's local storage (kept across visits and shared by diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 0fe5804a16..d34ebe3a41 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -18,27 +18,25 @@ accessibility = ["eframe/accesskit"] vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } vectorcraft-text = { workspace = true } -# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app) -# so VectorCraft matches the rest on Linux. `egui` adds `craft_window::decorate`. See #217. -craft-window = { workspace = true } +# Shared across the Craft suite: the UI runtime, settings, control server, file dialogs, the window +# frame policy and placement store (so VectorCraft matches the rest on Linux, see #217), printing and +# the update client. +craft = { workspace = true, features = ["ui", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } egui = { workspace = true } +egui_extras = { workspace = true } serde_json = { workspace = true } log = { workspace = true } chrono = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -rfd = { workspace = true } # wayland-data-control: native Wayland clipboard (Linux; X11 through XWayland only sees what X11 apps copied). arboard = { workspace = true, features = ["image-data", "wayland-data-control"] } image = { workspace = true } -webbrowser = { workspace = true } # The window's monitors, size and position (the same winit eframe runs on). winit = { version = "0.30", default-features = false } -craft-print = { workspace = true } [target.'cfg(windows)'.dependencies] -craft-update = { workspace = true } clipboard-win = { workspace = true } # Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs). # MIT, already in the build through the update client. @@ -46,8 +44,7 @@ winreg = "0.55" # Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the # GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter. -# It also lists each monitor's work area for floating panels (src/window.rs), so a build without -# the `wgpu` feature keeps the panels to the monitors' whole rects. + winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true } # Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR # Apache-2.0, already in the build through eframe. @@ -60,8 +57,7 @@ pollster = "1" # read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has # `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down. # Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the -# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which -# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`, +# cores the process may run on. Win32_System_Registry has `RegGetValueW`, # which src/host_services.rs uses to read the path PhotoCraft registers under App Paths. # Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and # Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the @@ -71,12 +67,9 @@ windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Founda vectorcraft-render = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] -# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK -# with default features off). Pinned exactly: review the diff before bumping. -muda = { version = "=0.21.2", default-features = false } objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } -# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd. +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] } +# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit. objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] } block2 = "0.6" # The window's AppKit view, to centre its buttons on the app bar (src/mac_window.rs). MIT OR @@ -100,9 +93,10 @@ pollster = "1" winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } # A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a # second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build -# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs). +# through winit with the `xinput` feature. # RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs). -x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] } +x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput"] } +craft = { workspace = true, features = ["wayland"] } # Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs), # so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's @@ -111,24 +105,17 @@ x11rb = { version = "0.13", default-features = false, features = ["randr", "xinp # through winit. wayland-client = "0.31" wayland-protocols = { version = "0.32", features = ["client", "unstable"] } -# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in -# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build -# through winit and rfd. +# The window's own Wayland connection (src/clipboard.rs). MIT, already in the build through winit. wayland-backend = { version = "0.3", features = ["client_system"] } # The Wayland clipboard's pipes (src/clipboard.rs): `poll` and the nonblocking flag give up a read # or send when the other app moves no data for a while. Apache-2.0 WITH LLVM-exception OR # Apache-2.0 OR MIT, already in the build through the workspace. rustix = { workspace = true, features = ["std", "event", "fs"] } -# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the -# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned -# exactly: review the diff before bumping. +# The display's color profile over D-Bus (src/display_profile.rs). MIT, already in the build through +# accesskit. Pinned exactly: review the diff before bumping. [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies] zbus = "=5.19.0" -# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal -# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build -# through zbus. -futures-lite = "2" # Tells whether arboard reads through the compositor's data-control protocol or through X11, the # same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through # arboard. @@ -142,5 +129,3 @@ winresource = "0.1" tempfile = "3" # Bound socket buffers in real loopback transport deadline regressions. socket2 = { workspace = true } -# src/portal_save.rs's tests build and read the portal's D-Bus values on every system. -zbus = "=5.19.0" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index a40eb0c92f..1f10e50f26 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,31 +1,27 @@ #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] use super::gpu; -use super::prefs::{save_prefs, save_prefs_soon}; +use super::prefs::{flush, save_tick}; #[cfg(not(target_os = "macos"))] use super::single_instance; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; -use super::{App, VectorcraftApp, file_access, window}; +use super::{App, VectorcraftApp, file_access}; #[cfg(target_os = "macos")] -use super::{mac_menu, mac_window, open_documents}; +use super::{mac_window, open_documents}; +// PLAN: assumed `craft::ui::shell::embed` path (`craft_ui_shell::shell::embed`) +use craft::ui::shell::embed; use vectorcraft_ui_egui::dialogs::safe_mode; use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage}; /// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating -/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel -/// button's secondary click on Windows. The control channel's input and the native menu's keys -/// go to the main window only. -#[cfg(target_os = "macos")] -pub(crate) fn native_input_hook(app: &VectorcraftApp) -> Option { - app.services.native_menu.is_some().then(|| std::sync::Arc::new(mac_menu::raw_input_hook) as vectorcraft_ui_egui::NativeInputHook) -} - +/// panels: the pen barrel button's secondary click on Windows. The control channel's input goes to +/// the main window only. #[cfg(windows)] pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option { Some(std::sync::Arc::new(windows_stylus::raw_input_hook)) } -#[cfg(not(any(target_os = "macos", windows)))] +#[cfg(not(windows))] pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option { None } @@ -36,8 +32,10 @@ impl eframe::App for App { // (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process. fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { let _timed = BEACON.enter_timed(Stage::Logic); - file_access::unconfined(|| self.logic_frame(ctx, frame)); - self.app.finish_ime_logic(ctx); + file_access::unconfined(|| { + self.logic_frame(ctx, frame); + embed::logic(ctx, || self.app.close_decision()); + }); BEACON.enter(Stage::Idle); } /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the @@ -60,25 +58,18 @@ impl eframe::App for App { if let Some(window_frame) = self.window_frame.as_mut() { window_frame(); } - #[cfg(target_os = "macos")] - if self.app.services.native_menu.is_some() { - mac_menu::raw_input_hook(raw); - } // A pen contact with the barrel button held presses the secondary button (Windows Ink). #[cfg(windows)] windows_stylus::raw_input_hook(raw); // The characters Alt + keypad codes typed (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); - file_access::unconfined(|| self.app.raw_input_hook(ctx, raw)); - // A mouse-up that never reached the window (#4326) is delivered once AppKit reports - // that no mouse button is down. - #[cfg(target_os = "macos")] - self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0); + file_access::unconfined(|| embed::before_input(ctx, |out| self.app.frame_input(out))); BEACON.enter(Stage::Idle); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let _timed = BEACON.enter_timed(Stage::Interface); + embed::before_ui(ui.ctx(), frame); #[cfg(target_os = "macos")] { let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT; @@ -88,22 +79,16 @@ impl eframe::App for App { // macOS converts the frame from sRGB to the display's profile (#2249). #[cfg(all(target_os = "macos", feature = "wgpu"))] super::mac_color_space::tag(ui); - if let Some(on) = self.host_caps_lock.read_transition() { - self.app.set_caps_lock(on); - } file_access::unconfined(|| self.app.ui(ui)); // Preferences are written when confirmed, not only at exit: a session ended any other way // (the system shutting down, the process ended or crashing) used to lose them (#1747). - if self.app.take_prefs_changed() { - file_access::unconfined(|| save_prefs(&self.app)); - } else { - // The workspace, panels and other UI settings change without the dialog (#4625). - file_access::unconfined(|| save_prefs_soon(&self.app)); - } - // Not while a file dialog's sheet has the keyboard: its name field's composition would go. - #[cfg(target_os = "macos")] - if !self.app.file_dialog_open() && self.app.take_ime_discard() { - discard_marked_text(); + file_access::unconfined(|| save_tick(&mut self.app, &self.settings, std::time::Instant::now())); + // The native dialogs the app asked for in this frame show now, over the window. + // PLAN: assumed `VectorcraftApp::window_dialogs: craft::ui::dialog::DialogHost` and `UiState::last_folders: HashMap` (hub-w1) + self.file_panels.pump_with(&mut self.app.window_dialogs, Some(&*frame)); + let folders = self.files.last_folders(); + if folders != self.app.ui.last_folders { + self.app.ui.last_folders = folders; } self.end_frame(ui.ctx(), frame); } @@ -112,12 +97,10 @@ impl eframe::App for App { // of a stall the interface came back from is removed. let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled()); super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON); - file_access::unconfined(|| save_prefs(&self.app)); + file_access::unconfined(|| flush(&self.settings)); // A ready update installs once the process has exited. The macOS exit below skips // dropping the app, so the helper is started here. self.app.start_pending_update(); - #[cfg(target_os = "macos")] - super::mac_cursor::release(); // Dropping the app can wait for the clipboard handles to let go: the windows leave the // screen first (`quit_windows`). #[cfg(not(any(target_os = "macos", windows)))] @@ -157,10 +140,6 @@ impl App { } fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - #[cfg(target_os = "macos")] - if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) { - super::mac_cursor::release(); - } self.frames = ctx.cumulative_frame_nr(); if let Some(why) = self.graphics_loss.take() { // eframe can't give a window a new device: the user saves and starts again. @@ -199,26 +178,11 @@ impl App { open_files(&mut self.app, held); open_files(&mut self.app, files); } - let (now, zoom) = (ctx.input(|i| i.time), ctx.zoom_factor()); - if let Some(w) = &self.winit_window - && window::monitors_due(self.monitors_listed, now, zoom) - { - self.app.services.dock_monitors = window::dock_monitors(w, zoom); - self.monitors_listed = Some((now, zoom)); - } + let now = ctx.input(|i| i.time); if let Some(w) = &self.winit_window { self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx); } self.app.tick(ctx); - if self.pending_maximize { - if let Some(w) = &self.winit_window { - self.pending_maximize = window::apply_pending_maximize(w, true, &mut self.maximize_tries); - } else { - self.pending_maximize = false; - } - } - let host_maximized = self.winit_window.as_ref().map(|w| w.is_maximized()); - window::track(ctx, &mut self.app.ui.window, host_maximized); if self.app.ui.status == "quit" { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } diff --git a/apps/vectorcraft/src/caps_lock.rs b/apps/vectorcraft/src/caps_lock.rs deleted file mode 100644 index 231a37e037..0000000000 --- a/apps/vectorcraft/src/caps_lock.rs +++ /dev/null @@ -1,216 +0,0 @@ -//! Read the host's Caps Lock state, which gives the drawing tools the precise crosshair while it is on. - -/// Only host transitions replace a value set by a script through `view.capsLock`. -#[derive(Default)] -pub struct HostCapsLock { - previous: Option, - #[cfg(target_os = "linux")] - x11: Option, -} - -#[cfg(target_os = "linux")] -struct X11CapsLock { - connection: x11rb::rust_connection::RustConnection, - locked: bool, - initial_sequence: u16, -} - -impl HostCapsLock { - pub fn new(window: Option<&winit::window::Window>) -> Self { - #[cfg(target_os = "linux")] - let x11 = window.and_then(x11_connection); - #[cfg(not(target_os = "linux"))] - let _ = window; - Self { - previous: None, - #[cfg(target_os = "linux")] - x11, - } - } - - pub fn read_transition(&mut self) -> Option { - #[cfg(target_os = "linux")] - let current = match self.x11.as_mut() { - Some(state) => match state.poll() { - Some(locked) => Some(locked), - None => { - self.x11 = None; - None - } - }, - None => { - // Native Wayland does not expose the seat's XKB lock bit through winit or egui. - None - } - }; - #[cfg(any(target_os = "macos", windows))] - let current = Some(read()); - // This platform has no lock-state reader. - #[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] - let current = None; - self.transition(current) - } - - fn transition(&mut self, reading: Option) -> Option { - reading.and_then(|current| self.observe(current)) - } - - fn observe(&mut self, current: bool) -> Option { - if self.previous.replace(current) == Some(current) { None } else { Some(current) } - } -} - -#[cfg(target_os = "linux")] -fn x11_connection(window: &winit::window::Window) -> Option { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - use x11rb::protocol::xkb; - if !matches!(window.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) { - return None; - } - let (connection, _) = x11rb::connect(None).ok()?; - let supported = x11rb::protocol::xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported; - if !supported { - return None; - } - // Subscribe before the initial read so changes during setup remain queued. - xkb::select_events( - &connection, - xkb::ID::USE_CORE_KBD.into(), - xkb::EventType::default(), - xkb::EventType::default(), - xkb::MapPart::default(), - xkb::MapPart::default(), - &xkb::SelectEventsAux { - state_notify: Some(xkb::SelectEventsAuxStateNotify { - affect_state: xkb::StatePart::MODIFIER_LOCK, - state_details: xkb::StatePart::MODIFIER_LOCK, - }), - ..Default::default() - }, - ) - .ok()? - .check() - .ok()?; - let (locked, initial_sequence) = read_x11(&connection)?; - Some(X11CapsLock { connection, locked, initial_sequence }) -} - -#[cfg(target_os = "linux")] -impl X11CapsLock { - fn poll(&mut self) -> Option { - use x11rb::connection::Connection as _; - use x11rb::protocol::Event; - while let Some(event) = self.connection.poll_for_event().ok()? { - if let Event::XkbStateNotify(state) = event - // Events queued before the initial GetState reply must not replace that newer snapshot. - && state.sequence.wrapping_sub(self.initial_sequence) < 0x8000 - { - self.locked = lock_modifier_is_set(state.locked_mods); - } - } - Some(self.locked) - } -} - -#[cfg(target_os = "linux")] -fn read_x11(connection: &x11rb::rust_connection::RustConnection) -> Option<(bool, u16)> { - use x11rb::protocol::xkb; - let state = xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into()).ok()?.reply().ok()?; - Some((lock_modifier_is_set(state.locked_mods), state.sequence)) -} - -#[cfg(target_os = "linux")] -fn lock_modifier_is_set(modifiers: x11rb::protocol::xproto::ModMask) -> bool { - use x11rb::protocol::xproto::ModMask; - u16::from(modifiers) & u16::from(ModMask::LOCK) != 0 -} - -#[cfg(target_os = "macos")] -const MAC_CAPS_LOCK: usize = 1 << 16; - -#[cfg(target_os = "macos")] -fn mac_flags_have_caps_lock(flags: usize) -> bool { - flags & MAC_CAPS_LOCK != 0 -} - -#[cfg(target_os = "macos")] -pub fn read() -> bool { - mac_flags_have_caps_lock(objc2_app_kit::NSEvent::modifierFlags_class().bits()) -} - -#[cfg(windows)] -fn windows_state_has_caps_lock(state: i16) -> bool { - state & 1 != 0 -} - -#[cfg(windows)] -#[allow(unsafe_code)] -pub fn read() -> bool { - // GetKeyState reports the toggle bit for the calling UI thread's keyboard state. - use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL}; - // SAFETY: `GetKeyState` takes a virtual-key code by value and reads no caller memory. - windows_state_has_caps_lock(unsafe { GetKeyState(i32::from(VK_CAPITAL.0)) }) -} - -// Querying XWayland for a native Wayland window would read a different keyboard. - -#[cfg(test)] -mod tests { - #[test] - fn no_host_reader_preserves_scripted_value_and_next_reading_transitions() { - let mut host = super::HostCapsLock::default(); - let mut session = vectorcraft_engine::Session::new(); - session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); - if let Some(on) = host.transition(None) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(session.caps_lock); - assert_eq!(host.transition(Some(false)), Some(false)); - } - - #[cfg(target_os = "linux")] - #[test] - fn no_x11_reader_has_no_transition() { - assert_eq!(super::HostCapsLock::default().read_transition(), None); - } - - #[test] - fn scripted_value_survives_unchanged_host_until_transition() { - let mut host = super::HostCapsLock::default(); - let mut session = vectorcraft_engine::Session::new(); - if let Some(on) = host.observe(false) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap(); - if let Some(on) = host.observe(false) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(session.caps_lock); - session.execute("view.capsLock", &serde_json::json!({"on": false})).unwrap(); - if let Some(on) = host.observe(true) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(session.caps_lock); - if let Some(on) = host.observe(false) { - session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap(); - } - assert!(!session.caps_lock); - } - - #[cfg(target_os = "macos")] - #[test] - fn mac_modifier_flags_map_caps_lock() { - assert!(!super::mac_flags_have_caps_lock(0)); - assert!(!super::mac_flags_have_caps_lock(1 << 17)); - assert!(super::mac_flags_have_caps_lock(1 << 16)); - assert!(super::mac_flags_have_caps_lock((1 << 16) | (1 << 17))); - } - - #[cfg(windows)] - #[test] - fn windows_key_state_maps_toggle_bit() { - assert!(!super::windows_state_has_caps_lock(0)); - assert!(!super::windows_state_has_caps_lock(i16::MIN)); - assert!(super::windows_state_has_caps_lock(1)); - } -} diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 3efdb9f93f..d5127401b7 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -1,229 +1,80 @@ -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -use super::portal_save; -#[cfg(windows)] -use super::windows_screen_color; +use std::collections::HashMap; +use std::path::PathBuf; + +use craft::dialogs::{ExtensionPolicy, FilePanels, FileService, ShowHook}; +use craft::host::Wake; +use craft::ui::runtime::PenSource; +use vectorcraft_ui_egui::hang_beacon::{Activity, BEACON, Beacon}; + +use super::{Services, fileio, printing}; +#[cfg(target_os = "linux")] +use super::tablet; +#[cfg(target_os = "macos")] +use super::mac_tablet; #[cfg(all(windows, not(target_vendor = "win7")))] use super::windows_stylus; -use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing}; -#[cfg(target_os = "linux")] -use super::{linux_screen_color, tablet}; -#[cfg(target_os = "macos")] -use super::{mac_save_format, mac_screen_color, mac_tablet}; -/// The window file dialogs belong to. +/// The main window, which the pen reader looks at to tell an X11 window from a Wayland one. pub(crate) type Parent = Option>; -/// What rfd's blocking and asynchronous file dialogs are both set up with. -trait DialogSettings: Sized { - fn parent(self, window: &winit::window::Window) -> Self; - fn title(self, title: &str) -> Self; - fn filter(self, name: &str, exts: &[impl ToString]) -> Self; - fn folder(self, folder: &str) -> Self; - fn file_name(self, name: &str) -> Self; +/// The native file service and the panels that show its dialogs. `folders` are the folders the last +/// session's picks chose, so a pick of this one starts where that ended. +pub(crate) fn file_service(wake: Wake, folders: HashMap) -> (FileService, FilePanels) { + let (service, panels) = FileService::new(wake); + let panels = panels + .extension_policy(ExtensionPolicy::AS_TYPED) + // PLAN: assumed `vectorcraft_ui_egui::replace_words() -> ReplaceWords`, the catalog's Replace question + .replace_words(vectorcraft_ui_egui::replace_words()) + .show_hook(marking_dialogs(&BEACON)); + (service.with_last_folders(folders), panels) } -macro_rules! dialog_settings { - ($($dialog:ty),*) => {$( - impl DialogSettings for $dialog { - fn parent(self, window: &winit::window::Window) -> Self { - self.set_parent(window) - } - fn title(self, title: &str) -> Self { - self.set_title(title) - } - fn filter(self, name: &str, exts: &[impl ToString]) -> Self { - self.add_filter(name, exts) - } - fn folder(self, folder: &str) -> Self { - self.set_directory(folder) - } - fn file_name(self, name: &str) -> Self { - self.set_file_name(name) - } - } - )*}; +/// A hook that marks `beacon` as in a dialog while the dialog shows: it waits for the user, so the +/// hang report (`hang_watch`) doesn't take the wait for a stall. Making the dialog stays timed. +fn marking_dialogs(beacon: &'static Beacon) -> ShowHook { + Box::new(move |show: &mut dyn FnMut()| { + let _mark = beacon.activity(Activity::Dialog); + show(); + }) } -dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog); - -/// On Linux and the BSDs the dialog is GTK's or the desktop portal's, which match a file type's -/// `*.ext` patterns case-sensitively. -const CASE_SENSITIVE_FILTERS: bool = - cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")); - -/// The extensions an open dialog's filter is given for `exts`: with `any_case`, each extension -/// that has a letter is followed by a pattern with each letter as a `[xX]` pair, so the filter for -/// `dib` also lists `image.DIB` and `image.Dib`. -fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { - let mut out = Vec::with_capacity(exts.len() * 2); - for e in exts { - let e = e.as_ref(); - out.push(e.to_string()); - if any_case && e.chars().any(|c| c.is_ascii_alphabetic()) { - out.push( - e.chars() - .map(|c| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() }) - .collect(), - ); - } - } - out -} - -/// `d` set up for `request`: its title, file types, folder and suggested name. -fn dialog_for(d: D, request: &PickRequest) -> D { - let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, - PickRequest::OpenMany => { - return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { - d.filter( - vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), - &open_extensions(exts, CASE_SENSITIVE_FILTERS), - ) - }); - } - PickRequest::Folder => return d, - PickRequest::FolderAt(folder) => return d.folder(folder), - }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); - let d = pick.filters.iter().fold(d, |d, (name, exts)| { - d.filter( - vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), - &open_extensions(exts, any_case), - ) - }); - let d = match &pick.folder { - Some(folder) => d.folder(folder), - None => d, - }; - if pick.name.is_empty() { - return d; - } - // Windows' save dialog changes the extension when a different file type is chosen only when - // the suggested name has no explicit extension. rfd supplies the first filter's extension to - // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). - // A remaining dot in the stem would look like another explicit extension to Windows. - #[cfg(windows)] - if matches!(request, PickRequest::Save(_)) - && pick.filters.len() > 1 - && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) - && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) - && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) - && !stem.contains('.') +/// Starts the host's tablet reader for `window`, which writes the pen's pressure and end into `pen`: +/// XInput2 under X11 and XWayland, AppKit's events on macOS, the pen's pointer messages on Windows. +/// Other windows read the pen from touch events only. +// PLAN: assumed `tablet::start`, `mac_tablet::start` and `windows_stylus::start` take the `PenSource` to write into (shell-w13) +pub(crate) fn start_pen(window: &Parent, pen: &PenSource) { + #[cfg(target_os = "linux")] { - return d.file_name(stem); + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + let x11 = window + .as_ref() + .and_then(|w| w.window_handle().ok()) + .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); + if x11 { + tablet::start(pen.clone()); + } } - d.file_name(&pick.name) + #[cfg(not(target_os = "linux"))] + let _ = window; + #[cfg(target_os = "macos")] + mac_tablet::start(pen.clone()); + #[cfg(all(windows, not(target_vendor = "win7")))] + windows_stylus::start(pen.clone()); + #[cfg(not(any(target_os = "linux", target_os = "macos", all(windows, not(target_vendor = "win7")))))] + let _ = pen; } #[cfg(test)] #[test] -fn a_folder_picker_asked_for_a_folder_starts_there() { - /// The settings a dialog was given, by name. - #[derive(Default)] - struct Recorded(Vec); - impl DialogSettings for Recorded { - fn parent(self, _: &winit::window::Window) -> Self { - self - } - fn title(mut self, title: &str) -> Self { - self.0.push(format!("title {title}")); - self - } - fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { - self.0.push(format!("filter {name}")); - self - } - fn folder(mut self, folder: &str) -> Self { - self.0.push(format!("folder {folder}")); - self - } - fn file_name(mut self, name: &str) -> Self { - self.0.push(format!("name {name}")); - self - } - } - assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); - assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); -} - -/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the -/// window and keeps it in front). -#[cfg(not(target_os = "macos"))] -fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog { - match parent { - Some(w) => dialog_for(rfd::FileDialog::new().parent(w), request), - None => dialog_for(rfd::FileDialog::new(), request), - } -} - -/// Before `request`'s dialog shows: a save dialog's folder (the Templates folder) may not exist yet. -fn make_folder(request: &PickRequest) { - if let PickRequest::Save(FilePick { folder: Some(folder), .. }) = request { - let _ = std::fs::create_dir_all(folder); - } -} - -/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked. On -/// Linux and the BSDs a save dialog with two or more file types is the desktop portal's, over -/// `parent`, and its answer also names the file type picked ([`portal_save`]); `dialog` shows when -/// the portal can't. -#[cfg(not(target_os = "macos"))] -#[cfg_attr(windows, allow(unused_variables))] -fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec { - #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] - if let PickRequest::Save(pick) = request - && let Some(answer) = portal_save::pick(pick, parent.as_deref()) - { - return answer; - } - let paths = match request { - PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), - PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), - }; - paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() -} - -/// Show the dialog for `request` over `parent` now → the paths picked. -#[cfg(not(target_os = "macos"))] -fn pick_now(request: PickRequest, parent: &Parent) -> Vec { - let beacon = &vectorcraft_ui_egui::hang_beacon::BEACON; - marked_dialog(beacon, || make_folder(&request), || show_dialog(file_dialog(&request, parent), &request, parent)) -} - -/// Run `prepare` (making the dialog's folder), then `show`, marked on `beacon` as a dialog: the -/// dialog waits for the user and is not a stall for the hang report (`hang_watch`), while `prepare` -/// is still timed. -#[cfg(not(target_os = "macos"))] -fn marked_dialog(beacon: &vectorcraft_ui_egui::hang_beacon::Beacon, prepare: impl FnOnce(), show: impl FnOnce() -> T) -> T { - prepare(); - let _mark = beacon.activity(vectorcraft_ui_egui::hang_beacon::Activity::Dialog); - show() -} - -#[cfg(all(test, not(target_os = "macos")))] -#[test] -fn making_a_dialogs_folder_is_timed_and_the_dialog_is_not() { - use vectorcraft_ui_egui::hang_beacon::{Activity, Beacon}; - let beacon = Beacon::new(); - let mut preparing = None; - let showing = marked_dialog(&beacon, || preparing = Some(beacon.sample().activity), || beacon.sample().activity); - assert_eq!(preparing, Some(Activity::None), "making the folder is timed"); - assert_eq!(showing, Activity::Dialog, "the dialog is not"); +fn a_dialog_is_marked_while_it_shows_and_not_after() { + let beacon: &'static Beacon = Box::leak(Box::new(Beacon::new())); + let mut hook = marking_dialogs(beacon); + let mut showing = None; + hook(&mut || showing = Some(beacon.sample().activity)); + assert_eq!(showing, Some(Activity::Dialog), "a dialog waiting for the user is not a stall"); assert_eq!(beacon.sample().activity, Activity::None, "the mark ends with the dialog"); } -/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an -/// event winit held back meanwhile aborts the app (#867). Dialogs are sheets there ([`start_pick`]); -/// one asked for any other way (a bug: outside a command, a dialog's OK or a button) picks nothing. -#[cfg(target_os = "macos")] -fn pick_now(request: PickRequest, _parent: &Parent) -> Vec { - log::error!("no file dialog shown for {request:?}: macOS shows them as sheets, from commands, dialogs' OK and buttons only"); - Vec::new() -} - /// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere. fn reveal(path: &str) -> Result<(), String> { explorer_safe(path)?; @@ -300,134 +151,10 @@ fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string()) } -/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the -/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then -/// offers to kill the window as not responding (#592). -#[cfg(not(target_os = "macos"))] -fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { - let dialog = file_dialog(&request, parent); - let (tx, rx) = std::sync::mpsc::channel(); - let ui = ui.clone(); - let parent = parent.clone(); - std::thread::Builder::new() - .name("file-dialog".into()) - .spawn(move || { - make_folder(&request); - // The app gone meanwhile has no use for the answer. - let _ = tx.send(show_dialog(dialog, &request, &parent)); - ui.request_repaint(); - }) - .ok()?; - Some(rx) -} - -/// The paths a dialog shown as a sheet picks, once it closes. -#[cfg(target_os = "macos")] -type SheetAnswer = std::pin::Pin> + Send>>; - -/// macOS: show the dialog for `request` as a sheet on `parent`'s window, answering on the receiver -/// (#867). Shown in line, the panel ran AppKit's modal event loop inside winit's event handler: an -/// event winit had held back meanwhile (one came as a resize of the panel ended) then re-entered -/// the handler, and winit's panic there, inside an AppKit callback, aborted the app. The sheet -/// returns at once and the window keeps running; a thread of its own waits for the answer. -#[cfg(target_os = "macos")] -fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option>> { - use winit::raw_window_handle::HasWindowHandle as _; - // rfd runs the panel modally after all unless it has the running app's window to hold the - // sheet (and from another thread it can't reach the window): no dialog then (`pick_now`). - let mtm = objc2::MainThreadMarker::new(); - let running = mtm.is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isRunning()); - let Some(window) = parent.as_ref().filter(|w| running && w.window_handle().is_ok()) else { - log::error!("no window to show the file dialog on (main thread: {}, running: {running})", mtm.is_some()); - return None; - }; - // The thread first, so the answer of a sheet once shown always has somewhere to go. - let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::(); - let (tx, rx) = std::sync::mpsc::channel(); - let ui = ui.clone(); - std::thread::Builder::new() - .name("file-dialog".into()) - .spawn(move || { - if let Ok(answer) = sheet_rx.recv() { - // The app gone meanwhile has no use for the answer. - let _ = tx.send(pollster::block_on(answer)); - ui.request_repaint(); - } - }) - .ok()?; - make_folder(&request); - // The panel is built and the sheet is begun below, on the main thread (as it must). - let dialog = dialog_for(rfd::AsyncFileDialog::new().parent(window), &request); - let path = |f: &rfd::FileHandle| f.path().to_string_lossy().to_string(); - let answer: SheetAnswer = match request { - PickRequest::Open(_) => { - let picked = dialog.pick_file(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - PickRequest::OpenMany | PickRequest::OpenFiles(_) => { - let picked = dialog.pick_files(); - Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) - } - // A save panel with two or more named file types is built by `mac_save_format`, which sets - // up its Format menu before the sheet begins (#866); rfd shows the others. - PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) { - // The dialog thread blocks here until the sheet answers. - Ok(mac_save_format::Begin::Shown(picked)) => Box::pin(async move { picked.recv().unwrap_or_default() }), - Ok(mac_save_format::Begin::DeferToRfd) => { - // Nothing is added to the sheet once rfd has begun it: an accessory view set then - // made recent macOS versions dismiss the sheet at once (#1800). - let picked = dialog.save_file(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - // AppKit returned nil for the panel. rfd uses the same `+savePanel` and would panic - // on that nil; treat the pick as cancelled instead (#5980). - Err(()) => Box::pin(async move { Vec::new() }), - }, - PickRequest::Folder | PickRequest::FolderAt(_) => { - let picked = dialog.pick_folder(); - Box::pin(async move { picked.await.iter().map(path).collect() }) - } - }; - // The thread can't be gone: it waits for this. If it were, its receiver answers as cancelled. - let _ = sheet_tx.send(answer); - Some(rx) -} - -/// The host's services; `ui` is woken when a file dialog answers. -pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { - use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; - let wayland = parent.as_ref().and_then(|w| w.window_handle().ok()).is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_))); - // A window on X11 (XWayland included) reads a tablet pen's pressure itself (#764). - #[cfg(target_os = "linux")] - let x11 = parent - .as_ref() - .and_then(|w| w.window_handle().ok()) - .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); - let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); - #[cfg(any(target_os = "macos", target_os = "linux", windows))] - let sampled_ui = ui.clone(); - #[cfg(target_os = "linux")] - let sampled_parent = p1.clone(); +/// The host's services. File dialogs, the clipboard, URLs, the pen and the screen color picker are +/// the framework's. +pub(crate) fn services() -> Services { Services { - pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), - pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), - pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), - pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), - // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows - // dialogs run the window's events while they are open. - start_pick: cfg!(unix).then(|| Box::new(move |request: PickRequest| start_pick(request, &p5, &ui)) as vectorcraft_ui_egui::picks::StartPick), - dialogs_are_sheets: cfg!(target_os = "macos"), - wayland, - no_cursor_theme: wayland && cursor_theme::theme_missing(), - #[cfg(target_os = "linux")] - stylus: if x11 { tablet::start() } else { None }, - // macOS reads it from AppKit's events (#852). - #[cfg(target_os = "macos")] - stylus: mac_tablet::start(), - // Windows reads it from the pen's pointer messages (`windows_stylus`). - #[cfg(windows)] - stylus: Some(windows_stylus::start()), read: Some(Box::new(read_file)), // Load Actions… refuses a file over its size limit without reading all of it. read_head: Some(Box::new(read_file_head)), @@ -441,19 +168,6 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { fileio::write_file_with(p, fill).map_err(|e| e.to_string()) })), - // Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event). - // Its calls are marked for the hang report (`hang_watch`). - system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))), - // Linux checks whether Paste has something to take on a background thread: an X11 clipboard - // owner that never answers holds a text read for up to 4 s for each format it tries, and - // quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which - // formats the clipboard holds and macOS asks the pasteboard server, so they check in line. - // The probe's handle is made on its own thread, from the window (`Send`), not its raw display. - clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory), - // Help → Discord / website / GitHub, the Discord button, About and Home links. - open_url: Some(Box::new(|url: &str| { - let _ = webbrowser::open(url); - })), reveal: Some(Box::new(reveal)), // Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders. open_file: Some(Box::new(open_file)), @@ -461,15 +175,6 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { open_in_photocraft: Some(Box::new(open_in_photocraft)), check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), - pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), - pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), - // Sample Color from Screen: the system's color sampler. - #[cfg(target_os = "macos")] - screen_color: Some(mac_screen_color::sampler(sampled_ui)), - #[cfg(target_os = "linux")] - screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)), - #[cfg(windows)] - screen_color: Some(windows_screen_color::sampler(sampled_ui)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), ..Default::default() @@ -837,104 +542,4 @@ mod open_with_tests { } } -#[cfg(test)] -mod dialog_tests { - use super::{CASE_SENSITIVE_FILTERS, DialogSettings, FilePick, PickRequest, dialog_for, fileio, open_extensions}; - /// The file types a dialog was given, by label. - #[derive(Default)] - struct Filters(Vec<(String, Vec)>, Option); - - impl DialogSettings for Filters { - fn parent(self, _window: &winit::window::Window) -> Self { - self - } - fn title(self, _title: &str) -> Self { - self - } - fn filter(mut self, name: &str, exts: &[impl ToString]) -> Self { - self.0.push((name.to_string(), exts.iter().map(ToString::to_string).collect())); - self - } - fn folder(self, _folder: &str) -> Self { - self - } - fn file_name(mut self, name: &str) -> Self { - self.1 = Some(name.to_string()); - self - } - } - - /// Does the case-sensitive pattern `*.{ext}` match `name`? `ext` may hold literal characters, - /// `*` and `[..]` sets. - fn matches(ext: &str, name: &str) -> bool { - fn here(p: &[char], n: &[char]) -> bool { - match p.split_first() { - None => n.is_empty(), - Some(('*', rest)) => (0..=n.len()).any(|i| here(rest, &n[i..])), - Some(('[', rest)) => { - let Some(end) = rest.iter().position(|&c| c == ']') else { return false }; - n.split_first().is_some_and(|(c, n)| rest[..end].contains(c) && here(&rest[end + 1..], n)) - } - Some((c, rest)) => n.split_first().is_some_and(|(d, n)| d == c && here(rest, n)), - } - } - let pattern: Vec = format!("*.{ext}").chars().collect(); - here(&pattern, &name.chars().collect::>()) - } - - /// Where filters match case-sensitively, every extension of File › Open and Place lists files - /// whose extension is in capitals or mixed case, `image.DIB` and `image.Pns` included. - #[test] - fn open_and_place_filters_list_extensions_in_any_case() { - let all = fileio::open_filters().chain(fileio::place_filters()); - for (label, exts) in all { - let patterns = open_extensions(exts, true); - for ext in exts { - let mut mixed = ext.to_ascii_uppercase(); - mixed.replace_range(..1, &ext[..1]); - for name in [format!("a.{ext}"), format!("a.{}", ext.to_ascii_uppercase()), format!("a.{mixed}")] { - assert!(patterns.iter().any(|p| matches(p, &name)), "{label}: {patterns:?} don't match {name}"); - } - } - } - assert_eq!(open_extensions(&["dib", "jp2", "*"], true), ["dib", "[dD][iI][bB]", "jp2", "[jJ][pP]2", "*"]); - assert_eq!(open_extensions(&["dib", "PNS"], false), ["dib", "PNS"]); - } - - /// Open and Place dialogs get the any-case patterns on Linux and the BSDs; a save dialog's file - /// types stay as listed. - #[test] - fn open_dialogs_get_any_case_patterns_where_filters_are_case_sensitive() { - let dib = vec![FilePick::filter("BMP", &["bmp", "dib"])]; - let pick = FilePick { filters: dib.clone(), ..Default::default() }; - let expected = |any_case: bool| open_extensions(&["bmp", "dib"], any_case); - let opened = dialog_for(Filters::default(), &PickRequest::Open(pick.clone())).0; - assert_eq!(opened[0].1, expected(CASE_SENSITIVE_FILTERS)); - let saved = dialog_for(Filters::default(), &PickRequest::Save(pick)).0; - assert_eq!(saved, dib); - let placed = dialog_for(Filters::default(), &PickRequest::OpenMany).0; - let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); - assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); - } - - /// A format selected after the Windows Save As dialog opens can replace the suffix of the - /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. - #[cfg(windows)] - #[test] - fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { - let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; - let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); - assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); - - let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); - let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); - let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); - let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; - assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); - } -} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..ab540e874b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -11,11 +11,13 @@ //! (Windows and Linux; `single_instance`). //! //! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on -//! macOS instead of the macOS menu bar (`mac_menu`). +//! macOS instead of the macOS menu bar. //! -//! `--control ` (or `VECTORCRAFT_CONTROL_PORT`; a port from 1 to 65535, or the app doesn't -//! start) starts a localhost JSON-lines control server: +//! `--control ` (or `VECTORCRAFT_CONTROL_PORT`; a port from 0 to 65535, 0 picking a free +//! one, or the app doesn't start) starts a localhost JSON-lines control server: //! `{"id":1,"method":"ui.inspect","params":{}}` → `{"id":1,"ok":true,"result":…}`. +//! `--control-token ` (or `VECTORCRAFT_CONTROL_TOKEN`) or `--control-token-file ` +//! (or `VECTORCRAFT_CONTROL_TOKEN_FILE`) sets the token each connection sends first. //! See `vectorcraft_ui_egui::control` for the methods. `--automation-read-root` and //! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the //! files its requests read and write (`vectorcraft_engine::file_access`); the person at the @@ -26,42 +28,26 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] mod automation_args; -mod caps_lock; mod clipboard; #[cfg(feature = "wgpu")] mod compositor_gpu; -mod control_server; mod cursor_theme; mod display_profile; #[cfg(feature = "wgpu")] mod gpu; mod hang_watch; #[cfg(target_os = "linux")] -mod linux_screen_color; -#[cfg(target_os = "linux")] mod linux_stylus; mod logging; #[cfg(all(target_os = "macos", feature = "wgpu"))] mod mac_color_space; #[cfg(target_os = "macos")] -mod mac_cursor; -#[cfg(target_os = "macos")] mod mac_fonts; -#[cfg(target_os = "macos")] -mod mac_menu; -#[cfg(target_os = "macos")] -mod mac_save_format; -#[cfg(target_os = "macos")] -mod mac_screen_color; mod mac_tablet; #[cfg(target_os = "macos")] mod mac_window; #[cfg(target_os = "macos")] mod open_documents; -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] -mod portal_request; -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))] -mod portal_save; mod prefs_dir; mod presentation; mod printing; @@ -72,53 +58,111 @@ mod single_instance; #[cfg(windows)] mod system_fonts; mod tablet; -mod window; mod window_frame; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; -mod windows_screen_color; mod windows_stylus; mod xwayland; +use std::sync::{Arc, Mutex}; + +// PLAN: assumed paths: `craft::ui::shell::embed`, `craft::ui::{InstallSpec, register_app_icons}`, `craft::ui::runtime::PenSource`, `craft::window::{Prefix, SystemWindows}`, `craft::host::{AppInfo, Backend::X11}`, `craft::dialogs::{FilePanels, FileService}` +use craft::automation::server::{self, Listening}; +use craft::automation::{ControlOptions, EnvNames}; +use craft::dialogs::{FilePanels, FileService}; +use craft::host::target::{Backend, ShellInfo}; +use craft::host::{AppInfo, Wake}; +use craft::settings::SharedSettings; +use craft::ui::InstallSpec; +use craft::ui::runtime::PenSource; +use craft::ui::shell::embed; +use craft::window::policy::{TitleBarPref, decide_for}; +use craft::window::restore::Store; +use craft::window::{Prefix, SystemWindows}; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::file_access::{self, AutomationRoots}; use vectorcraft_ui_egui::dialogs::safe_mode; use vectorcraft_ui_egui::graphics::GraphicsLoss; -use vectorcraft_ui_egui::picks::PickRequest; -use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp}; +use vectorcraft_ui_egui::settings::AppSettings; +use vectorcraft_ui_egui::{Services, VectorcraftApp}; mod app; mod host_services; mod prefs; -mod titlebar; #[cfg(all(test, feature = "wgpu"))] use app::bring_window_forward; use app::native_input_hook; use app::open_or_hold; -use host_services::services; -#[cfg(all(test, feature = "wgpu"))] -use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes}; -use prefs::{load_prefs, log_dir, prefs_enabled, prefs_path, read_prefs}; -#[cfg(all(test, feature = "wgpu", any(target_os = "macos", target_os = "windows")))] -use titlebar::CUSTOM_TITLEBAR; -#[cfg(feature = "wgpu")] -use titlebar::adapter_summary; -#[cfg(all(test, feature = "wgpu"))] -use titlebar::custom_titlebar_from; -#[cfg(all(test, feature = "wgpu"))] -use titlebar::opted_into_system_title_bar; +use host_services::{file_service, services, start_pen}; +use prefs::{load_prefs, log_dir, open_store, prefs_enabled}; + +/// The window's size when no saved placement overrides it, and the smallest it may be, in points. +const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0]; +const MIN_SIZE: [f32; 2] = [800.0, 500.0]; + +/// The app id every OS window carries; it matches `packaging/linux/ai.storyteller.vectorcraft.desktop`. +const WINDOW_APP_ID: &str = "ai.storyteller.vectorcraft"; + +/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets +/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches +/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. +fn app_icon() -> egui::IconData { + #[cfg(target_os = "macos")] + let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png"); + #[cfg(not(target_os = "macos"))] + let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png"); + eframe::icon_data::from_png_bytes(png).unwrap_or_default() +} + +/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the +/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too. #[cfg(windows)] -use titlebar::set_taskbar_icon; -#[cfg(all(test, feature = "wgpu"))] -use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies}; -use titlebar::{custom_titlebar, native_options, titlebar_from_env}; +fn set_taskbar_icon(w: &winit::window::Window) { + use winit::platform::windows::WindowExtWindows as _; + let icon = app_icon(); + // An icon that can't be made leaves the generic one: nothing else depends on it. + if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) { + w.set_taskbar_icon(Some(i)); + } +} + +/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports. +#[cfg(feature = "wgpu")] +fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String { + format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type) +} + +/// The window's options: the app draws the title bar when `custom_titlebar`, else the desktop does. +fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { + eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("VectorCraft") + .with_inner_size(DEFAULT_SIZE) + .with_min_inner_size(MIN_SIZE) + .with_drag_and_drop(true) + .with_decorations(!custom_titlebar) + .with_fullsize_content_view(true) + .with_titlebar_shown(false) + .with_title_shown(false) + .with_icon(app_icon()) + .with_app_id(WINDOW_APP_ID), + ..Default::default() + } +} struct App { app: VectorcraftApp, - host_caps_lock: caps_lock::HostCapsLock, + /// The preferences, written through [`prefs::save_tick`] and on exit. + settings: SharedSettings, + /// The file service the host's `Files` is, kept for the folders its picks chose. + files: Arc, + /// Shows the native dialogs the file service was asked for. + file_panels: FilePanels, + /// Keeps the control server running while the app does. + _control_server: Option, /// Reported by wgpu when the window's graphics device is lost (a driver reset). graphics_loss: GraphicsLoss, /// The graphics device was lost and the unsaved changes are kept for Data Recovery. @@ -130,14 +174,8 @@ struct App { /// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635), /// and to take the window off screen on quit before the clipboard handles let go (`quit_windows`). winit_window: Option>, - /// A saved or fitted geometry asked for maximize once the window is mapped (Linux). - pending_maximize: bool, - /// Frames left to retry [`window::apply_pending_maximize`]. - maximize_tries: u8, /// The command line's files, held back until the choice about a stopped plug-in is made. held_files: Vec, - /// The time and UI zoom of the last monitor list ([`window::monitors_due`]). - monitors_listed: Option<(f64, f32)>, /// Reads the profile of the display that shows the main window, for the canvas. display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). @@ -158,6 +196,10 @@ Opens the VectorCraft desktop app with the given files. Options: --control Start the localhost JSON-lines control server on (or VECTORCRAFT_CONTROL_PORT) + --control-token The token control connections send first + (or VECTORCRAFT_CONTROL_TOKEN) + --control-token-file Read that token from + (or VECTORCRAFT_CONTROL_TOKEN_FILE) --automation-read-root Confine the files control requests read to (may be given more than once) --automation-write-root Confine the files control requests write to @@ -275,7 +317,7 @@ fn read_command_line( fn main() -> std::process::ExitCode { // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if let Some(result) = craft::update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } // Before any thread starts: the pointer must find a cursor theme on Wayland (#2450). @@ -294,16 +336,24 @@ fn main() -> std::process::ExitCode { Err(code) => return code, }; let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args; - // After the arguments: `--control` and `--version` win over a bad environment value. - let control_port = match control.port { - Some(port) => Some(port), - None => match automation_args::env_control_port(std::env::var_os("VECTORCRAFT_CONTROL_PORT")) { - Ok(port) => port, - Err(e) => { - eprintln!("vectorcraft: {e}"); - return std::process::ExitCode::FAILURE; - } - }, + // After the arguments: the flags and `--version` win over a bad environment value. + // PLAN: assumed `ControlArg::into_options(self) -> ControlOptions` (shell-w12 edits `automation_args`) + let control_options = match ControlOptions::resolve(control.into_options(), &EnvNames::for_app("VECTORCRAFT")) { + Ok(options) => options, + Err(e) => { + eprintln!("vectorcraft: {e}"); + return std::process::ExitCode::FAILURE; + } + }; + let control_port = control_options.port; + // Read before the window opens: a token file that can't be read keeps the app from starting + // rather than leaving the channel open without one. + let control_token = match control_port.map(|_| control_options.server_token()).transpose() { + Ok(token) => token.map(|token| (control_options.token_notice(&token), token)), + Err(e) => { + eprintln!("vectorcraft: {e}"); + return std::process::ExitCode::FAILURE; + } }; // Before desktop services, so every start-up warning is recorded (`logging`). let logger = logging::install(); @@ -317,7 +367,6 @@ fn main() -> std::process::ExitCode { } #[cfg(target_os = "macos")] let _ = new_instance; - vectorcraft_ui_egui::i18n::detect_system_lang_in_background(); // Before the first render: the cores the process may run on. #[cfg(windows)] windows_cores::install(); @@ -366,14 +415,19 @@ fn main() -> std::process::ExitCode { } } }; - let saved = read_prefs(); - let saved_window = saved.as_ref().and_then(|ui| ui.window); + let (settings, settings_report) = open_store(); + if settings_report.has_problems() { + log::warn!("the preferences were not read as saved: {settings_report:?}"); + } + // An engine preference the window's start reads before the app exists. + let engine_pref = |key: &str| settings.lock().get().ui.engine_prefs.get(key).cloned(); #[cfg(feature = "wgpu")] - let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + let gpu_pref_value = engine_pref("gpuPreference"); + #[cfg(feature = "wgpu")] + let gpu_pref = gpu_pref_value.as_ref().and_then(serde_json::Value::as_str); // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. #[cfg(feature = "wgpu")] - let low_latency_drawing = - saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); + let low_latency_drawing = engine_pref("lowLatencyDrawing").and_then(|v| v.as_bool()).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -407,17 +461,15 @@ fn main() -> std::process::ExitCode { }; #[cfg(feature = "wgpu")] let crash = left_out.crash.clone(); - let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref()); - let options = native_options(custom_titlebar); // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux // Display Server › X11 opens the window through XWayland instead, where file drops work (#1151), // and the other choices do so when a pen is attached, where the pen draws (#2028, #4967). #[cfg(target_os = "linux")] let mut forced_to_x11 = false; #[cfg(target_os = "linux")] - let options = { - let mut options = options; - let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); + { + let pref_value = engine_pref("linuxDisplayServer"); + let pref = pref_value.as_ref().and_then(serde_json::Value::as_str); if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { if xwayland::x11_libraries_found() { forced_to_x11 = true; @@ -426,21 +478,34 @@ fn main() -> std::process::ExitCode { } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } - use winit::platform::x11::EventLoopBuilderExtX11 as _; - options.event_loop_builder = Some(Box::new(|builder| { - builder.with_x11(); - })); } else { log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); } } - options - }; + } #[cfg(not(target_os = "linux"))] let forced_to_x11 = false; - // Preferences › User Interface notes under System Title Bar when the desktop draws the frame - // with it on or off. - let desktop_keeps_frame = titlebar::desktop_keeps_frame(forced_to_x11); + // A window forced onto XWayland runs on X11, whose window manager draws the frame: the + // framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and + // Preferences › User Interface › System Title Bar. + // PLAN: assumed `Backend::X11` + let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() }; + let titlebar_pref = + if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated }; + let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref); + let custom_titlebar = matches!(decision.frame, craft::window::Frame::App(_)); + let options = native_options(custom_titlebar); + #[cfg(target_os = "linux")] + let options = { + let mut options = options; + if forced_to_x11 { + use winit::platform::x11::EventLoopBuilderExtX11 as _; + options.event_loop_builder = Some(Box::new(|builder| { + builder.with_x11(); + })); + } + options + }; // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end // is down; the message hook notes each pointer contact and whether it starts with the barrel // button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the @@ -538,7 +603,34 @@ fn main() -> std::process::ExitCode { run( options, Box::new(move |cc| { - VectorcraftApp::install_ime_reset_hooks(&cc.egui_ctx); + let ctx = &cc.egui_ctx; + let winit_window = cc.winit_window().cloned(); + let pen = PenSource::default(); + let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows)) + .app_id(WINDOW_APP_ID) + .placement(Arc::new(Mutex::new(Store::open("vectorcraft")))) + .frame(decision) + .pen(pen.clone()); + embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + // PLAN: assumed `craft::ui::register_app_icons(&[..])` and `cursors::CURSOR_ICONS` (cv.S13) + craft::ui::register_app_icons(&vectorcraft_ui_egui::icons::APP_ICONS); + craft::ui::register_app_icons(&vectorcraft_ui_egui::cursors::CURSOR_ICONS); + start_pen(&winit_window, &pen); + // PLAN: assumed `UiState::last_folders: HashMap`, the folders the picks chose + let folders = settings.lock().get().ui.last_folders.clone(); + let wake = { + let ctx = ctx.clone(); + Wake::new(move || ctx.request_repaint()) + }; + let (file_service, file_panels) = file_service(wake, folders); + let files = Arc::new(file_service); + craft::host::Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") }) + // PLAN: assumed `vectorcraft_ui_egui::i18n::shared() -> Arc` + .i18n(vectorcraft_ui_egui::i18n::shared()) + .settings(Arc::new(settings.clone())) + .files(files.clone()) + .install(ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); @@ -546,7 +638,9 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_color_settings(&mut session); // Before any plug-in loads: this launch's marker in the Launch folder next to the // preferences (none for runs without preferences), and Safe Mode. - let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch"))); + // PLAN: assumed `prefs::prefs_dir() -> Option` (shell-w8), the one folder rule + let launch_dir = prefs::prefs_dir().filter(|_| prefs_enabled()).map(|d| d.join("Launch")); + let folder = |name: &str| prefs::prefs_dir().map(|d| d.join(name).to_string_lossy().to_string()); let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag); prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. @@ -556,9 +650,9 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_new_doc_profiles(&mut session); prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); - let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); + let mut app = VectorcraftApp::new(session, services()); app.set_startup_update_check(true); - load_prefs(&mut app, saved); + load_prefs(&mut app, &settings); safe_mode::after_start(&mut app, stopped); // The saved PDF presets live in their own folder (also read by vectorcraft-cli), // which takes over from the copy the preferences file used to hold. @@ -569,38 +663,27 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_arrowheads(&mut app.session); // The custom bevels, kept in their own file next to the preferences. prefs_dir::attach_bevels(&mut app.session); - // Fit the window to its monitor, or put it back where it was (still hidden). - let winit_window = cc.winit_window().cloned(); + // The window's placement comes back through the framework's placement store. + #[cfg(windows)] if let Some(w) = &winit_window { - let g = window::restore(w, saved_window); - app.ui.window = Some(g); - #[cfg(windows)] set_taskbar_icon(w); } - // Linux may not map the window before the first frames, so a saved maximize is retried then (#3635). - let pending_maximize = cfg!(target_os = "linux") && app.ui.window.as_ref().is_some_and(|g| g.maximized); // User Defined swatch, graphic style, symbol and brush libraries live next to the preferences. - let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string())); - app.session.swatch_libraries.set_user_dir(swatches); - let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string())); - app.session.style_libraries.set_user_dir(styles); - let symbols = prefs_path().and_then(|p| Some(p.parent()?.join("Symbols").to_string_lossy().to_string())); - app.session.symbol_libraries.set_user_dir(symbols); - let brushes = prefs_path().and_then(|p| Some(p.parent()?.join("Brushes").to_string_lossy().to_string())); - app.session.brush_libraries.set_user_dir(brushes); + app.session.swatch_libraries.set_user_dir(folder("Swatches")); + app.session.style_libraries.set_user_dir(folder("Graphic Styles")); + app.session.symbol_libraries.set_user_dir(folder("Symbols")); + app.session.brush_libraries.set_user_dir(folder("Brushes")); // With the User Defined libraries listed, the persistent library panels reopen. vectorcraft_ui_egui::panels::library_panel::restore(&mut app); // So do the Libraries panel's libraries; runs without preferences (agents' test // runs) keep theirs for the session only, never touching the user's. if prefs_enabled() { - let libraries = prefs_path().and_then(|p| Some(p.parent()?.join("Libraries").to_string_lossy().to_string())); - app.session.libraries.set_dir(libraries); + app.session.libraries.set_dir(folder("Libraries")); } // Data Recovery copies live next to the preferences too (none for runs without // preferences, such as agents' test runs, unless the recoveryFolder preference is set). if std::env::var_os("VECTORCRAFT_NO_PREFS").is_none() { - let recovery = prefs_path().and_then(|p| Some(p.parent()?.join("Data Recovery").to_string_lossy().to_string())); - app.session.recovery.set_default_folder(recovery); + app.session.recovery.set_default_folder(folder("Data Recovery")); } let graphics_loss = GraphicsLoss::default(); #[cfg(feature = "wgpu")] @@ -663,29 +746,32 @@ fn main() -> std::process::ExitCode { if previous_hang.is_some() && app.ui.status.is_empty() { vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app); } - app.titlebar_from_env = titlebar_from_env(); - app.custom_titlebar = custom_titlebar; - app.caption_layout = caption_layout; - app.desktop_frame = !custom_titlebar; - app.desktop_keeps_frame = desktop_keeps_frame; - if let Some(port) = control_port { - let rx = control_server::start(port, cc.egui_ctx.clone()); - app = app.with_control(rx).with_automation_roots(roots.clone()); - if let Some(roots) = &roots { - // Everywhere the app doesn't say whose work it is (worker threads), the - // roots hold: unconfined is only what the person at the keyboard does. - file_access::confine_process(roots.clone()); - log::info!("control channel confined to the automation roots: {}", roots.describe()); + let mut control_server = None; + if let (Some(port), Some((notice, token))) = (control_port, control_token) { + match server::listen(port, token, craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx)) { + Ok((rx, listening)) => { + eprintln!("{notice}"); + log::info!("control channel: {listening:?}"); + control_server = Some(listening); + app = app.with_control(rx).with_automation_roots(roots.clone()); + if let Some(roots) = &roots { + // Everywhere the app doesn't say whose work it is (worker threads), the + // roots hold: unconfined is only what the person at the keyboard does. + file_access::confine_process(roots.clone()); + log::info!("control channel confined to the automation roots: {}", roots.describe()); + } + } + Err(e) => { + log::error!("no control channel on port {port}: {e}"); + eprintln!("vectorcraft: can't listen on port {port}: {e}"); + } } } #[cfg(target_os = "macos")] { open_documents::set_ui(&cc.egui_ctx); - // The macOS menu bar, installed now so winit's default menu doesn't stay up. - if !in_window_menus { - app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app); - } - mac_cursor::install(&cc.egui_ctx, winit_window.as_ref()); + // PLAN: menus-w7 installs the macOS menu bar into `app.services.native_menu` here unless `in_window_menus`. + let _ = in_window_menus; } #[cfg(not(target_os = "macos"))] { @@ -700,17 +786,17 @@ fn main() -> std::process::ExitCode { // The content and the pointer stay aligned on Windows (#1758). let window_frame = window_frame::service(cc, custom_titlebar); Ok(Box::new(App { - host_caps_lock: caps_lock::HostCapsLock::new(winit_window.as_deref()), app, + settings, + files, + file_panels, + _control_server: control_server, graphics_loss, graphics_lost: false, frames: 0, window_frame, winit_window, - pending_maximize, - maximize_tries: 8, held_files, - monitors_listed: None, display_profile: Default::default(), frame_start: None, min_frame, diff --git a/apps/vectorcraft/src/titlebar.rs b/apps/vectorcraft/src/titlebar.rs deleted file mode 100644 index cb98fa2648..0000000000 --- a/apps/vectorcraft/src/titlebar.rs +++ /dev/null @@ -1,228 +0,0 @@ -use super::window; -#[cfg(target_os = "linux")] -use super::xwayland; - -/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets -/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches -/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon. -fn app_icon() -> egui::IconData { - #[cfg(target_os = "macos")] - let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png"); - #[cfg(not(target_os = "macos"))] - let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png"); - eframe::icon_data::from_png_bytes(png).unwrap_or_default() -} - -/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the -/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too. -#[cfg(windows)] -pub(crate) fn set_taskbar_icon(w: &winit::window::Window) { - use winit::platform::windows::WindowExtWindows as _; - let icon = app_icon(); - // An icon that can't be made leaves the generic one: nothing else depends on it. - if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) { - w.set_taskbar_icon(Some(i)); - } -} - -/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports. -#[cfg(feature = "wgpu")] -pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String { - format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type) -} - -/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`). -/// macOS keeps its traffic lights over the integrated title strip. -/// -/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the -/// `craft-window` probe) and by the tests; Linux and the BSDs take the decision from the probe. -#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] -pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); - -/// Whether the user asked for the system title bar in Preferences › User Interface › System Title -/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is -/// `false` (the default). This preference forces the desktop/native frame back on unless -/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]). -pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { - saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false) -} - -/// Whether the user asked for VectorCraft's own title bar in Preferences › User Interface › -/// VectorCraft Title Bar on Every Desktop (Linux and the BSDs). Read like -/// [`opted_into_system_title_bar`]; a missing or unreadable value is `false` (the default). -pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool { - saved.map(|ui| ui.engine_prefs.get("appTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false) -} - -/// Whether the app draws the frame on this start, before the System Title Bar preference is -/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and -/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when the -/// variable is set to `app`, `system` or `desktop`;VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window -/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe -/// decides. -pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option, forced_to_x11: bool, opted_into_app: bool) -> bool { - match overridden { - Some(app) => app, - None => opted_into_app || (probed_app && !forced_to_x11), - } -} - -/// The frame this start uses, before the System Title Bar preference is applied -/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame -/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps -/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft -/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can -/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons. -pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame { - let probed_app = matches!(probed, craft_window::Frame::App(_)); - match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) { - (true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame, - (true, _) => craft_window::Frame::App(craft_window::Layout::default()), - (false, _) => craft_window::Frame::Desktop, - } -} - -/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button -/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of -/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the -/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge. -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout { - use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout}; - let caption = |b: &craft_window::Button| match b { - craft_window::Button::Minimize => Caption::Minimize, - craft_window::Button::Maximize => Caption::Maximize, - craft_window::Button::Close => Caption::Close, - }; - match frame.layout() { - Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() }, - None => CaptionLayout::default(), - } -} - -/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see -/// [`custom_titlebar_from`]). -#[cfg(any(target_os = "macos", target_os = "windows"))] -pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout { - vectorcraft_ui_egui::titlebar::CaptionLayout::default() -} - -/// The `craft-window` probe's answer for this process (its override variable is -/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection. -fn probed_choice() -> &'static craft_window::Choice { - static CHOICE: std::sync::OnceLock = std::sync::OnceLock::new(); - CHOICE.get_or_init(|| craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"))) -} - -/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences › -/// User Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while -/// it is set to `app`, `system` or `desktop`. Always `false` on macOS and Windows. -pub(crate) fn titlebar_from_env() -> bool { - cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some() -} - -/// Whether System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR` -/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is -/// set in. -pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool { - opted_into_system && !from_env -} - -/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate -/// decided and the user's System Title Bar preference. -/// -/// The suite-wide rule (`craft_window::Choice`) is: the desktop draws the frame -/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with -/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it -/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter), -/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly -/// when `craft-window` says the app owns the frame **and** the user has not opted into the system -/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set -/// to one of those values ([`system_title_bar_applies`]). -/// -/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the -/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but -/// VectorCraft insets its content under the macOS traffic lights and draws its own caption buttons -/// on Windows — an overdraw on an OS-decorated window that is VectorCraft's choice, not -/// `craft-window`'s. Only Linux and the BSDs take the decision from the probe. -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -pub(crate) fn custom_titlebar_from(frame: &craft_window::Frame, opted_into_system: bool) -> bool { - matches!(frame, craft_window::Frame::App(_)) && !opted_into_system -} - -/// macOS and Windows: today's behavior, independent of the `craft-window` probe (see -/// [`custom_titlebar_from`]). macOS never draws its own frame (`CUSTOM_TITLEBAR` is `false`); -/// Windows draws its own caption unless the user opted into the system title bar. -#[cfg(any(target_os = "macos", target_os = "windows"))] -pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_system: bool) -> bool { - CUSTOM_TITLEBAR && !opted_into_system -} - -/// Whether this start draws its own title bar, and where its caption buttons go -/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its -/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System -/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or -/// `desktop`. Call once at startup, -/// before [`native_options`]. -/// -/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through -/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs -/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native -/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins, -/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]). -pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) { - let choice = probed_choice(); - let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env()); - // macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from` - // ignores the frame there). - let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved); - #[cfg(target_os = "linux")] - // When the window will actually open on X11 (XWayland) — the user asked for it *and* the X11 - // libraries are present, the same two conditions the launch path checks below — that run is - // effectively X11, so keep the native frame. If the libraries are missing, startup stays on - // Wayland, so the probe's own decision (app-drawn on GNOME) must stand. - let forced_to_x11 = { - let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str); - xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found() - }; - #[cfg(not(target_os = "linux"))] - let forced_to_x11 = false; - let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app); - (custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame)) -} - -/// Whether the desktop would draw this window's frame with System Title Bar on or off while -/// VectorCraft Title Bar on Every Desktop is off: `VECTORCRAFT_TITLEBAR` is not set to `app`, -/// `system` or `desktop` (`overridden` is `None`), and the probe chose -/// [`craft_window::Frame::Desktop`] or the window opens through XWayland (`forced_to_x11`) -/// ([`app_draws_frame`]). The saved VectorCraft Title Bar on Every Desktop is left out, so the value -/// stays `true` on such a desktop while that preference gives the app the frame. Always `false` on -/// macOS and Windows, where System Title Bar decides the frame by itself. -pub(crate) fn desktop_keeps_frame_from(probed: &craft_window::Frame, overridden: Option, forced_to_x11: bool) -> bool { - let probed_app = matches!(probed, craft_window::Frame::App(_)); - cfg!(not(any(target_os = "macos", target_os = "windows"))) && overridden.is_none() && !app_draws_frame(probed_app, None, forced_to_x11, false) -} - -/// [`desktop_keeps_frame_from`] for this start's probe, given whether the launch path opens the -/// window through XWayland. -pub(crate) fn desktop_keeps_frame(forced_to_x11: bool) -> bool { - let choice = probed_choice(); - desktop_keeps_frame_from(choice.frame(), choice.overridden(), forced_to_x11) -} - -pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions { - eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - .with_title("VectorCraft") - .with_inner_size(window::DEFAULT_SIZE) - .with_min_inner_size(window::MIN_SIZE) - .with_drag_and_drop(true) - .with_decorations(!custom_titlebar) - .with_fullsize_content_view(true) - .with_titlebar_shown(false) - .with_title_shown(false) - .with_icon(app_icon()) - .with_app_id("ai.storyteller.vectorcraft"), - ..Default::default() - } -} diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs deleted file mode 100644 index ce224584fd..0000000000 --- a/apps/vectorcraft/src/window.rs +++ /dev/null @@ -1,576 +0,0 @@ -//! The main window's size and position. The first launch fits the window to its monitor, opening -//! it maximized where the default size leaves no room for a taskbar or Dock. Later launches restore -//! the size, position and maximized state saved with the UI preferences (`UiState::window`), moved -//! onto a monitor that is still connected. - -use vectorcraft_ui_egui::DockMonitor; -use vectorcraft_ui_egui::state::WindowGeometry; -use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize}; - -/// The first window's size, in points. -pub const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0]; -/// The smallest window, in points. -pub const MIN_SIZE: [f32; 2] = [800.0, 500.0]; -/// Room the first window leaves around itself for a taskbar, Dock or menu bar when it decides -/// whether to open maximized: a monitor with less room opens it maximized. This check uses the -/// fixed allowance on every platform, including where the system reports a work area. -const SCREEN_ROOM: [f32; 2] = [64.0, 128.0]; - -/// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs. -const MONITORS_EVERY: f64 = 1.0; - -/// A monitor: its top-left corner and size in physical pixels, its scale factor, and the part -/// windows may use where the system reports one. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Monitor { - pos: [i64; 2], - size: [i64; 2], - scale: f32, - /// `[x, y, width, height]` in physical pixels, without the taskbar, Dock or menu bar. - work: Option<[i64; 4]>, -} - -/// A monitor's rect and its work area as the system lists them, `[x, y, width, height]` in -/// physical pixels. Only Windows and macOS list them. -#[derive(Clone, Copy, Debug, PartialEq)] -#[cfg_attr(not(any(all(windows, feature = "wgpu"), target_os = "macos")), allow(dead_code))] -pub struct WorkArea { - monitor: [i64; 4], - work: [i64; 4], -} - -impl Monitor { - pub fn new(pos: PhysicalPosition, size: PhysicalSize, scale: f64) -> Self { - let scale = scale as f32; - let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale, work: None } - } - - /// This monitor with the work area of the entry in `areas` whose monitor rect matches its own, - /// to the pixel either way to allow for rounding. Without a match, or when the matching work - /// area has no width or height, it has none. - fn with_work_area(self, areas: &[WorkArea]) -> Self { - let [x, y] = self.pos; - let [w, h] = self.size; - let rect = [x, y, w, h]; - let work = - areas.iter().find(|a| a.monitor.iter().zip(rect).all(|(a, b)| a.abs_diff(b) <= 1)).map(|a| a.work).filter(|&[_, _, w, h]| w > 0 && h > 0); - Self { work, ..self } - } - - /// Its size in points. - fn points(&self) -> [f32; 2] { - self.size.map(|s| s as f32 / self.scale) - } - - /// This monitor with its work area made smaller by a window frame of `frame` physical pixels - /// (outer size less inner size), so a window whose inner size fits the result fits the work area - /// with its frame. - fn less_frame(self, frame: [i64; 2]) -> Self { - let work = self.work.map(|[x, y, w, h]| [x, y, (w - frame[0].max(0)).max(1), (h - frame[1].max(0)).max(1)]); - Self { work, ..self } - } - - /// The size of its work area in points, or of the whole monitor when it has none. - fn work_points(&self) -> [f32; 2] { - self.work.map_or_else(|| self.points(), |[_, _, w, h]| [w, h].map(|s| s as f32 / self.scale)) - } - - /// Its size in points less room for a taskbar, Dock or menu bar. - fn usable(&self) -> [f32; 2] { - let points = self.points(); - std::array::from_fn(|i| points[i] - SCREEN_ROOM[i]) - } - - /// A window of `size` points on this monitor, in physical pixels. - fn pixels(&self, size: [f32; 2]) -> [i64; 2] { - size.map(|s| (s * self.scale) as i64) - } - - /// How much of a window at `pos` of `size` points this monitor shows, in square pixels. - fn overlap(&self, pos: [i32; 2], size: [f32; 2]) -> i64 { - let px = self.pixels(size); - let span = |i: usize| { - let start = i64::from(pos[i]).max(self.pos[i]); - let end = i64::from(pos[i]).saturating_add(px[i]).min(self.pos[i] + self.size[i]); - (end - start).max(0) - }; - span(0).saturating_mul(span(1)) - } - - /// The top-left corner nearest to `pos` (centred when none) that keeps a window of `size` - /// points on this monitor, inside its work area when it has one. A window bigger than the area - /// gets the area's top-left corner. - fn keep_on(&self, pos: Option<[i32; 2]>, size: [f32; 2]) -> [i32; 2] { - let px = self.pixels(size); - let [x, y] = self.pos; - let [w, h] = self.size; - let [ax, ay, aw, ah] = self.work.unwrap_or([x, y, w, h]); - let (start, extent) = ([ax, ay], [aw, ah]); - std::array::from_fn(|i| { - let lo = start[i]; - let hi = lo + extent[i].saturating_sub(px[i]).max(0); - let want = pos.map_or(lo + (hi - lo) / 2, |p| i64::from(p[i])); - i32::try_from(want.max(lo).min(hi)).unwrap_or_default() - }) - } - - /// This monitor for floating panels, in the points egui reports for a window on it: physical - /// pixels divided by the monitor's scale factor and the UI zoom. The work area is converted the - /// same way. - fn docking(&self, name: Option, zoom: f32) -> DockMonitor { - let scale = self.scale * zoom; - let [x, y] = self.pos; - let [w, h] = self.size; - let points = |rect: [i64; 4]| rect.map(|v| v as f32 / scale); - DockMonitor { name, rect: points([x, y, w, h]), scale, work_area: self.work.map(points) } - } -} - -/// Where the window opens: `saved` (the last session's geometry) kept on a connected monitor, else -/// the default size on `home` (the monitor the system opens it on). Without monitors (the system -/// doesn't list them, so nothing to check a saved geometry against) the default size. -pub fn place(saved: Option, monitors: &[Monitor], home: Option) -> WindowGeometry { - let default = WindowGeometry { pos: None, size: DEFAULT_SIZE, maximized: false }; - let Some(home) = home.and_then(|i| monitors.get(i)).or(monitors.first()) else { - return default; - }; - let Some(saved) = saved else { - let usable = home.usable(); - if (0..2).all(|i| DEFAULT_SIZE[i] <= usable[i]) { - return default; - } - // A small screen: maximized, with a size that fits once un-maximized. - let size = fit(DEFAULT_SIZE, usable); - return WindowGeometry { pos: Some(home.keep_on(None, size)), size, maximized: true }; - }; - // The monitor showing most of the window; none when it was on a monitor that is gone. - let shown = saved.pos.and_then(|p| { - let (area, m) = monitors.iter().map(|m| (m.overlap(p, saved.size), m)).max_by_key(|(area, _)| *area)?; - (area > 0).then_some(m) - }); - let m = shown.unwrap_or(home); - // Bigger than its monitor (a smaller screen than last time): maximized, like the first window. - let room = m.points(); - let too_big = (0..2).any(|i| saved.size[i] > room[i]); - // No bigger than the work area either, so the window fits below or beside the taskbar. - let work = m.work_points(); - let room = if too_big { m.usable() } else { room }; - let size = fit(saved.size, std::array::from_fn(|i| room[i].min(work[i]))); - WindowGeometry { - // Moved fully onto its monitor, or centred on the home monitor. - pos: saved.pos.map(|p| m.keep_on(shown.map(|_| p), size)), - size, - maximized: saved.maximized || too_big, - } -} - -/// `size` no bigger than `room`, and no smaller than the smallest window unless `room` is. -fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] { - std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0)) -} - -/// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most -/// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom. -pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool { - listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY) -} - -/// The connected monitors for floating panels (`Services::dock_monitors`), with the work area the -/// system reports for each (Windows and macOS). -pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec { - let areas = work_areas::list(); - let monitors: Vec<_> = - window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas), m.name())).collect(); - docking_list(&monitors, zoom, cfg!(target_os = "macos")) -} - -/// A rect in macOS screen coordinates (points, origin at the bottom-left of the primary screen, -/// y up) in the physical pixels winit gives a monitor's position and size: points from the top-left -/// of the primary screen, `primary_height` points tall, times `scale`. -#[cfg(any(target_os = "macos", test))] -fn from_bottom_left([x, y, w, h]: [f64; 4], primary_height: f64, scale: f64) -> Option<[i64; 4]> { - let rect = [x, primary_height - (y + h), w, h].map(|v| (v * scale).round()); - // `as` saturates; a coordinate of 1e12 pixels or more is not a monitor's. - rect.iter().all(|v| v.is_finite() && v.abs() < 1e12).then(|| rect.map(|v| v as i64)) -} - -/// Each monitor's rect and work area as the system reports them. -mod work_areas { - pub use platform::list; - - /// `GetMonitorInfo` for every monitor: `rcMonitor` and `rcWork`, in the physical pixels winit - /// reports for a per-monitor DPI aware process. - #[cfg(all(windows, feature = "wgpu"))] - mod platform { - use super::super::WorkArea; - use winsafe::prelude::Handle; - use winsafe::{HDC, RECT}; - - pub fn list() -> Vec { - let rect = |r: RECT| { - let [left, top, right, bottom] = [r.left, r.top, r.right, r.bottom].map(i64::from); - [left, top, right - left, bottom - top] - }; - let mut areas = Vec::new(); - // Without a list the panels keep to the monitors' whole rects, as before. - let _ = HDC::NULL.EnumDisplayMonitors(None, |monitor, _, _| { - if let Ok(info) = monitor.GetMonitorInfo() { - areas.push(WorkArea { monitor: rect(info.rcMonitor), work: rect(info.rcWork) }); - } - true - }); - areas - } - } - - /// `NSScreen`'s `frame` and `visibleFrame` for every screen, turned into the top-left origin - /// and physical pixels winit uses for its monitors. - #[cfg(target_os = "macos")] - mod platform { - use super::super::{WorkArea, from_bottom_left}; - use objc2_app_kit::NSScreen; - use objc2_foundation::{MainThreadMarker, NSRect}; - - pub fn list() -> Vec { - // `NSScreen::screens` needs the main thread, where the UI frame runs. - let Some(mtm) = MainThreadMarker::new() else { - return Vec::new(); - }; - let screens: Vec<_> = NSScreen::screens(mtm).iter().collect(); - // The first screen holds the menu bar and is the origin of the screen coordinates. - let Some(primary) = screens.first().map(|s| s.frame().size.height) else { - return Vec::new(); - }; - let rect = |r: NSRect| [r.origin.x, r.origin.y, r.size.width, r.size.height]; - screens - .iter() - .filter_map(|s| { - let scale = s.backingScaleFactor(); - let monitor = from_bottom_left(rect(s.frame()), primary, scale)?; - let work = from_bottom_left(rect(s.visibleFrame()), primary, scale)?; - Some(WorkArea { monitor, work }) - }) - .collect() - } - } - - /// No work areas: the panels keep to the monitors' whole rects. - #[cfg(not(any(all(windows, feature = "wgpu"), target_os = "macos")))] - mod platform { - pub fn list() -> Vec { - Vec::new() - } - } -} - -/// The list for floating panels, empty when `monitors` have different scales and `shared_points` is -/// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the -/// scale of the monitor it is created on, which can put a window saved on another scale off every -/// monitor. With an empty list craft-ui opens the window on the main window's monitor. -/// -/// A name that two monitors share is left out, so craft-ui finds those monitors by their rects: macOS -/// can give two displays of one model the same name. -fn docking_list(monitors: &[(Monitor, Option)], zoom: f32, shared_points: bool) -> Vec { - if !shared_points && monitors.windows(2).any(|pair| pair[0].0.scale != pair[1].0.scale) { - return Vec::new(); - } - let unique = |name: &String| monitors.iter().filter(|(_, other)| other.as_ref() == Some(name)).count() == 1; - monitors.iter().map(|(monitor, name)| monitor.docking(name.clone().filter(unique), zoom)).collect() -} - -/// Size and place the new window (eframe shows it after drawing the first frame) and return its -/// geometry. On Linux the window may not be mapped yet, so [`apply_pending_maximize`] must run -/// until the host reports maximized (fixes #3635). -pub fn restore(window: &winit::window::Window, saved: Option) -> WindowGeometry { - let handles: Vec<_> = window.available_monitors().collect(); - let areas = work_areas::list(); - // The system title bar and border, which the inner size leaves out, in points: each monitor - // draws them at its own scale. - let (outer, inner, scale) = (window.outer_size(), window.inner_size(), window.scale_factor()); - let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - let frame = [outer.width.saturating_sub(inner.width), outer.height.saturating_sub(inner.height)].map(|px| f64::from(px) / scale); - let monitors: Vec = handles - .iter() - .map(|m| { - let px = frame.map(|f| (f * m.scale_factor()).ceil().min(1e6) as i64); - Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas).less_frame(px) - }) - .collect(); - let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|c| handles.iter().position(|m| *m == c)); - let g = place(saved, &monitors, home); - if let Some([x, y]) = g.pos { - window.set_outer_position(PhysicalPosition::new(x, y)); - } - // Returns the new size when it applies at once; either way the window gets it. - let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1])); - #[cfg(not(target_os = "linux"))] - if g.maximized { - window.set_maximized(true); - } - g -} - -/// Keep asking the host to maximize until it sticks, or give up after a few frames. -pub fn apply_pending_maximize(window: &winit::window::Window, want: bool, tries: &mut u8) -> bool { - if !want { - return false; - } - if window.is_maximized() { - return false; - } - if *tries == 0 { - return false; - } - *tries -= 1; - window.set_maximized(true); - true -} - -/// Per frame: remember the window's geometry for the next launch. Minimized or full screen keeps -/// the last one; maximized only sets its flag, so un-maximizing next time restores the last size. -/// `host_maximized` is the window manager's idea of maximized when egui does not report it (#3635). -pub fn track(ctx: &egui::Context, geometry: &mut Option, host_maximized: Option) { - let zoom = ctx.zoom_factor(); - ctx.input(|i| { - let v = i.viewport(); - if v.minimized == Some(true) || v.fullscreen == Some(true) { - return; - } - let maximized = v.maximized == Some(true) || host_maximized == Some(true); - if maximized { - if let Some(g) = geometry { - g.maximized = true; - } - return; - } - let Some(inner) = v.inner_rect else { return }; - let pos = v.outer_rect.map(|r| [r.min.x, r.min.y].map(|c| (c * i.pixels_per_point).round() as i32)); - *geometry = Some(WindowGeometry { pos, size: [inner.width() * zoom, inner.height() * zoom], maximized: false }); - }); -} - -#[cfg(test)] -mod tests { - use super::*; - - fn monitor(x: i32, y: i32, w: u32, h: u32, scale: f64) -> Monitor { - Monitor::new(PhysicalPosition::new(x, y), PhysicalSize::new(w, h), scale) - } - - fn saved(pos: Option<[i32; 2]>, size: [f32; 2], maximized: bool) -> Option { - Some(WindowGeometry { pos, size, maximized }) - } - - #[test] - fn the_first_window_fits_its_screen() { - // 1920 × 1080: the default size, where the system puts it. - let big = [monitor(0, 0, 1920, 1080, 1.0)]; - assert_eq!(place(None, &big, Some(0)), WindowGeometry { pos: None, size: DEFAULT_SIZE, maximized: false }); - // 1600 × 900, 1366 × 768 and 1920 × 1080 at 150% (1280 × 720 points): maximized, and a - // size that fits the screen with room for the taskbar once un-maximized. - for (m, size) in [ - (monitor(0, 0, 1600, 900, 1.0), [1440.0, 772.0]), - (monitor(0, 0, 1366, 768, 1.0), [1302.0, 640.0]), - (monitor(0, 0, 1920, 1080, 1.5), [1216.0, 592.0]), - ] { - let g = place(None, &[m], Some(0)); - assert!(g.maximized, "{m:?}"); - assert_eq!(g.size, size, "{m:?}"); - let [x, y] = g.pos.unwrap(); - let px = m.pixels(g.size); - assert!(x >= 0 && y >= 0 && i64::from(x) + px[0] <= m.size[0] && i64::from(y) + px[1] <= m.size[1], "{m:?}: {g:?}"); - } - // No monitor information: the default size, whatever was saved. - assert_eq!(place(None, &[], None), WindowGeometry { pos: None, size: DEFAULT_SIZE, maximized: false }); - assert_eq!(place(saved(Some([9000, 9000]), [1e9, 1e9], true), &[], None).size, DEFAULT_SIZE); - } - - #[test] - fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() { - let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom); - let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0); - assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None }); - // A window at (3000, 200) on this monitor reports (1500, 100). - let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0); - assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None }); - // The UI zoom divides what egui reports as well. - let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25); - assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None }); - } - - #[test] - fn floating_panels_get_each_monitors_work_area_in_the_same_points() { - // A 4K monitor at 200% with a 96-pixel taskbar along its bottom, and one at 100% to its - // right with a 48-pixel taskbar along its left edge. - let areas = [ - WorkArea { monitor: [0, 0, 3840, 2160], work: [0, 0, 3840, 2064] }, - WorkArea { monitor: [3840, 0, 1920, 1080], work: [3888, 0, 1872, 1080] }, - ]; - let left = monitor(0, 0, 3840, 2160, 2.0).with_work_area(&areas); - assert_eq!(left.docking(None, 1.0).work_area, Some([0.0, 0.0, 1920.0, 1032.0])); - // The UI zoom divides the work area as it divides the rect. - assert_eq!(left.docking(None, 1.25).work_area, Some([0.0, 0.0, 1536.0, 825.6])); - // Rounding of a fractional scale can move a rect by a pixel. - let right = monitor(3841, 0, 1919, 1080, 1.0).with_work_area(&areas); - assert_eq!(right.docking(None, 1.0).work_area, Some([3888.0, 0.0, 1872.0, 1080.0])); - // A monitor the system did not list keeps to its whole rect. - let other = monitor(5760, 0, 1920, 1080, 1.0).with_work_area(&areas); - assert_eq!(other.docking(None, 1.0).work_area, None); - assert_eq!(monitor(0, 0, 3840, 2160, 2.0).with_work_area(&[]).docking(None, 1.0).work_area, None); - // A work area with no height is left out, so the monitor keeps to its whole rect. - let flat = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 1080, 1920, 0] }]; - assert_eq!(monitor(0, 0, 1920, 1080, 1.0).with_work_area(&flat).docking(None, 1.0).work_area, None); - } - - #[test] - fn a_restored_window_keeps_its_title_bar_out_of_a_taskbar_along_the_top() { - // A 1920 × 1080 monitor with a 48-pixel taskbar along its top edge. - let areas = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 48, 1920, 1032] }]; - let m = [monitor(0, 0, 1920, 1080, 1.0).with_work_area(&areas)]; - // A window saved at the top edge moves down below the taskbar. - let g = place(saved(Some([100, 0]), [1000.0, 700.0], false), &m, Some(0)); - assert_eq!(g.pos, Some([100, 48])); - // A window that fits below the taskbar keeps its place. - assert_eq!(place(saved(Some([100, 200]), [1000.0, 700.0], false), &m, Some(0)).pos, Some([100, 200])); - // A window taller than the work area is made as tall as the work area and placed in it. - let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &m, Some(0)); - assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 1032.0])); - // With a system frame of 16 × 39 pixels the inner size leaves room for it. - let framed = [m[0].less_frame([16, 39])]; - let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &framed, Some(0)); - assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 993.0])); - // Without a work area the frame leaves the monitor's rect as it was. - assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None); - } - - #[test] - fn macos_screen_rects_turn_into_winits_top_left_pixels() { - // A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock, - // and a 1920 × 1080 screen at 1× above it, its bottom-left 200 points right of the - // primary's top-left. - let primary = 982.0; - assert_eq!(from_bottom_left([0.0, 0.0, 1512.0, 982.0], primary, 2.0), Some([0, 0, 3024, 1964])); - assert_eq!(from_bottom_left([0.0, 80.0, 1512.0, 865.0], primary, 2.0), Some([0, 74, 3024, 1730])); - assert_eq!(from_bottom_left([200.0, 982.0, 1920.0, 1080.0], primary, 1.0), Some([200, -1080, 1920, 1080])); - assert_eq!(from_bottom_left([f64::NAN, 0.0, 1.0, 1.0], primary, 1.0), None); - assert_eq!(from_bottom_left([0.0, 0.0, 1e300, 1.0], primary, 1.0), None); - } - - #[test] - fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() { - let named = |m: Monitor, name: &str| (m, Some(name.to_string())); - let same = [named(monitor(0, 0, 1920, 1080, 1.5), "a"), named(monitor(1920, 0, 1920, 1080, 1.5), "b")]; - assert_eq!(docking_list(&same, 1.0, false).len(), 2); - let mixed = [named(monitor(0, 0, 3840, 2160, 2.0), "a"), named(monitor(3840, 0, 1920, 1080, 1.0), "b")]; - assert_eq!(docking_list(&mixed, 1.0, false), Vec::new()); - assert_eq!(docking_list(&mixed, 1.0, true).len(), 2); - assert_eq!(docking_list(&[], 1.0, false), Vec::new()); - } - - #[test] - fn a_name_that_two_monitors_share_is_left_out_of_the_list() { - let list = [ - (monitor(0, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())), - (monitor(1920, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())), - (monitor(3840, 0, 1920, 1080, 1.0), Some("Monitor #2".to_string())), - (monitor(5760, 0, 1920, 1080, 1.0), None), - ]; - let names: Vec<_> = docking_list(&list, 1.0, false).into_iter().map(|m| m.name).collect(); - assert_eq!(names, [None, None, Some("Monitor #2".to_string()), None]); - } - - #[test] - fn the_monitor_list_is_read_on_the_first_frame_then_once_a_second_or_on_a_zoom_change() { - assert!(monitors_due(None, 0.0, 1.0)); - assert!(!monitors_due(Some((5.0, 1.0)), 5.0, 1.0)); - assert!(!monitors_due(Some((5.0, 1.0)), 5.5, 1.0)); - assert!(monitors_due(Some((5.0, 1.0)), 6.0, 1.0)); - assert!(monitors_due(Some((5.0, 1.0)), 5.5, 1.25)); - } - - #[test] - fn the_saved_window_comes_back_where_it_was() { - let two = [monitor(0, 0, 2560, 1440, 1.0), monitor(2560, 0, 1920, 1080, 1.0)]; - for g in [saved(Some([100, 80]), [1200.0, 800.0], false), saved(Some([2700, 50]), [1000.0, 700.0], true), saved(None, [1000.0, 700.0], false)] - { - assert_eq!(Some(place(g, &two, Some(0))), g); - } - } - - #[test] - fn a_saved_window_stays_on_a_connected_monitor() { - let laptop = [monitor(0, 0, 1600, 900, 1.0)]; - // Last time on a second monitor that is gone: centred on the remaining one. - let g = place(saved(Some([2700, 50]), [1000.0, 700.0], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([300, 100]), size: [1000.0, 700.0], maximized: false }); - // Half off the monitor's right and bottom edges: moved fully onto it. - let g = place(saved(Some([1200, 600]), [1000.0, 700.0], false), &laptop, Some(0)); - assert_eq!(g.pos, Some([600, 200])); - // Bigger than the screen now (it was on a larger one): it fits, and opens maximized. - let g = place(saved(Some([0, 0]), [2400.0, 1300.0], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([0, 0]), size: [1536.0, 772.0], maximized: true }); - // A monitor left of the primary one (negative coordinates) still counts. - let left = [monitor(0, 0, 1920, 1080, 1.0), monitor(-1920, 0, 1920, 1080, 1.0)]; - assert_eq!(place(saved(Some([-1800, 40]), [1000.0, 700.0], false), &left, Some(0)).pos, Some([-1800, 40])); - // Nonsense sizes from a damaged preferences file are kept within the screen. - let g = place(saved(Some([i32::MAX, i32::MIN]), [-5.0, f32::MAX], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([400, 64]), size: [800.0, 772.0], maximized: true }); - let g = place(saved(Some([5, 5]), [f32::NEG_INFINITY, f32::INFINITY], false), &laptop, Some(0)); - assert_eq!(g, WindowGeometry { pos: Some([400, 64]), size: [800.0, 772.0], maximized: true }); - } - - #[test] - fn the_window_geometry_is_tracked_for_the_next_launch() { - let ctx = egui::Context::default(); - let mut geometry = None; - let mut frame = |info: egui::ViewportInfo| { - let mut input = egui::RawInput::default(); - input.viewports.insert(egui::ViewportId::ROOT, info); - ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, None)).textures_delta.clear(); - geometry - }; - let rect = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(1000.0, 600.0)); - let normal = egui::ViewportInfo { - native_pixels_per_point: Some(1.5), - inner_rect: Some(rect), - outer_rect: Some(rect), - maximized: Some(false), - ..Default::default() - }; - // Position in physical pixels, size in points. - let g = WindowGeometry { pos: Some([30, 45]), size: [1000.0, 600.0], maximized: false }; - assert_eq!(frame(normal.clone()), Some(g)); - // Maximized or minimized: the size to restore stays. - let big = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 700.0)); - let maximized = egui::ViewportInfo { inner_rect: Some(big), outer_rect: Some(big), maximized: Some(true), ..normal.clone() }; - assert_eq!(frame(maximized), Some(WindowGeometry { maximized: true, ..g })); - let minimized = egui::ViewportInfo { inner_rect: None, outer_rect: None, minimized: Some(true), ..normal.clone() }; - assert_eq!(frame(minimized), Some(WindowGeometry { maximized: true, ..g })); - assert_eq!(frame(normal), Some(g)); - // Saved with the preferences; older preference files have no window. - let mut ui = vectorcraft_ui_egui::UiState { window: Some(g), ..Default::default() }; - let back: vectorcraft_ui_egui::UiState = serde_json::from_slice(&serde_json::to_vec(&ui).unwrap()).unwrap(); - assert_eq!(back.window, Some(g)); - ui.window = None; - let json = serde_json::to_value(&ui).unwrap(); - assert!(json.get("window").is_none()); - let back: vectorcraft_ui_egui::UiState = serde_json::from_value(json).unwrap(); - assert_eq!(back.window, None); - } - - #[test] - fn the_host_maximized_flag_is_remembered_when_egui_does_not_report_it() { - let ctx = egui::Context::default(); - let mut geometry = Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: false }); - let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1920.0, 1080.0)); - let mut input = egui::RawInput::default(); - input.viewports.insert( - egui::ViewportId::ROOT, - egui::ViewportInfo { inner_rect: Some(rect), outer_rect: Some(rect), maximized: None, ..Default::default() }, - ); - let mut out = ctx.run_ui(input, |ui| track(ui.ctx(), &mut geometry, Some(true))); - out.textures_delta.clear(); - assert_eq!(geometry, Some(WindowGeometry { pos: Some([10, 20]), size: [800.0, 600.0], maximized: true })); - } -} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 6c38464bd0..a3779a7256 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -1,48 +1,8 @@ -use super::{Arc, ClipboardProbeFactory, Mutex, SystemClipboard, background, native_menu, picks, place, print, screen_color, stylus}; - -/// A file type a dialog filters by: its label, which shows translated, and its extensions without -/// the dot. -pub type FileFilter = (String, Vec); - -/// What a file dialog shows: a suggested file name (save dialogs), the folder to start in and the -/// file-type filters. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct FilePick { - pub name: String, - pub folder: Option, - /// The default type first; empty = every file. - pub filters: Vec, -} - -impl FilePick { - /// A save dialog suggesting `name`. - pub fn named(name: &str) -> Self { - Self { name: name.to_string(), ..Default::default() } - } - - /// The file type `label` with `extensions`. - pub fn filter(label: &str, extensions: &[&str]) -> FileFilter { - (label.to_owned(), extensions.iter().map(|e| (*e).to_owned()).collect()) - } - - /// The file types of `list`, as the engine lists them: `(label, extensions)`. - pub fn filters<'a>(list: impl IntoIterator) -> Vec { - list.into_iter().map(|(label, extensions)| Self::filter(label, extensions)).collect() - } -} +use super::{Arc, Mutex, background, place, print}; pub type CheckApplicationFn = Box Result<(), String>>; pub type OpenApplicationFn = Box Result>; -pub type PickOpen = Box Option>; - -pub type PickSave = Box Option>; - -pub type PickOpenFiles = Box Vec>; - -/// Shows a folder picker that starts in the given folder; returns the folder picked. -pub type PickFolderAt = Box Option>; - pub type ReadFn = Box Result, String>>; /// The first `max` bytes of the file at a path (all of it when it is shorter); the rest of the file @@ -63,16 +23,10 @@ pub type ExistsFn = Arc bool + Send + Sync>; pub type Inbox = Arc)>>>; -/// The web open picker's answers in order: the picked file, or `None` when it was canceled. -pub type PickedInbox = Arc)>>>>; - /// Starts a browser download of the bytes under a file name; an error when it couldn't be started /// (the save or export then fails as a refused write does: #1693). pub type DownloadFn = Box Result<(), String>>; -/// Opens a URL in the system browser. -pub type OpenUrlFn = Box; - /// Whether a URL from a document may open in the browser: an `http:`, `https:` or `mailto:` URL /// without control characters. The system hands other schemes (`file:`, application schemes) to /// other programs. @@ -91,13 +45,10 @@ pub type RevealFn = Box Result<(), String>>; /// Opens a file in a fixed app; `Ok(false)` when that app isn't installed. pub type OpenInFn = Box Result>; -/// Platform services injected by the host app (desktop or web). +/// Platform services injected by the host app (desktop or web). File dialogs, the clipboard, URLs, +/// the pen and the screen color picker are the framework host's. #[derive(Default)] pub struct Services { - /// Show an open dialog; returns a path. - pub pick_open: Option, - /// Show a save dialog (suggested name, folder, file types); returns a path. - pub pick_save: Option, pub read: Option, /// Read at most a number of bytes from a file (desktop). A file with a size limit is read one /// byte past the limit, so a larger file is refused without reading all of it. Without it, the @@ -105,50 +56,19 @@ pub struct Services { pub read_head: Option, pub write: Option, /// Is there a file or folder at a path (desktop)? The app asks before replacing a file that a - /// save panel's name names once the app gives it an extension ([`picks::ask_to_replace`]), and - /// before a save or export replaces a file it writes beside that one (a file per artboard, a - /// linked image). Without it, no file counts as there. + /// save panel's name names once the app gives it an extension, and before a save or export + /// replaces a file it writes beside that one (a file per artboard, a linked image). Without it, + /// no file counts as there. pub exists: Option, /// Files that arrived asynchronously (web drops): (name, bytes). pub inbox: Option, - /// Web: the open picker's answers (`open_async`). A file opens as automation's when automation - /// opened a picker that has not answered yet. - pub picked_inbox: Option, /// Web: files the page's script handed over (`window.vectorcraft.openFile`). They open as /// automation's. pub page_inbox: Option, /// Web: trigger a browser download instead of writing a path. pub download: Option, - /// Web: start an async open (bytes arrive via `picked_inbox`). - pub open_async: Option>, - /// Read the system clipboard's text (desktop). Without it, pasted text only arrives with - /// egui's Paste event (web, and keyboard paste everywhere). - pub clipboard_read: Option Option>>, - /// Open a URL in the system browser (desktop). Without it, egui opens it (a new tab on the web). - pub open_url: Option, - /// Show an open dialog for several files (File → Place…); returns their paths (none: cancelled). - pub pick_open_multi: Option Vec>>, - /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with - /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. - pub pick_open_files: Option, - /// Web: start an async pick of files to place (they arrive via `place_inbox`). - pub place_async: Option>, - /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the - /// canvas). + /// Files that arrived asynchronously to be placed (web: dropped on the canvas). pub place_inbox: Option, - /// Web: start an async pick of a script to run (it arrives via `script_inbox`; a canceled pick - /// delivers nothing). - pub script_async: Option>, - /// Scripts the web's picker delivered for File › Scripts › Other Script…. - pub script_inbox: Option, - /// The system clipboard with all its formats (desktop): Copy offers text, SVG, PDF and PNG, - /// Paste takes SVG, PDF, text and bitmaps from other apps. Without it, SVG text only (through - /// egui and `clipboard_read`). - pub system_clipboard: Option>, - /// A second system-clipboard handle, for checking whether Paste has something to take on a - /// background thread (Linux: an X11 clipboard owner that never answers would freeze the UI). - /// Taken on the first frame. Without it the check runs on the UI thread. - pub clipboard_probe: Option, /// File → Show in Folder: select a file in the system file manager (desktop). pub reveal: Option, /// Write a file from any thread (desktop): lets Background Save and Export write off the UI @@ -173,16 +93,6 @@ pub struct Services { pub check_application: Option, /// Launch a native-picked application with one file argument; false only when absent. pub open_in_application: Option, - /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). - pub pick_folder: Option Option>>, - /// Show a folder picker that starts in a folder (a script's `selectDlg`); returns its path. - /// Without it, `pick_folder`, which starts where the host starts it. - pub pick_folder_at: Option, - /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, Linux - /// through the desktop portal, and browsers with an EyeDropper): Sample Color from Screen - /// ([`screen_color`]). Without it that command answers with an error and the Color Picker's - /// eyedropper button is gray. - pub screen_color: Option, /// Where Data Recovery keeps its copies when not in a folder (the web's browser storage; /// tests): installed into the session ([`vectorcraft_engine::cmd::recovery`]). pub recovery_store: Option>, @@ -190,36 +100,11 @@ pub struct Services { /// (web). Without it Print saves the job as a PDF. pub print: Option>, /// The macOS menu bar, when the desktop app installed one: the in-window menus are hidden then. - pub native_menu: Option, - /// Show file dialogs off the UI thread (desktop Linux, where a dialog in line holds the window - /// and the compositor finds it not answering, #592) or as sheets on the window (macOS, where a - /// dialog in line aborts the app, #867): what asked runs again with the answer ([`picks`]). - /// Without it they are shown in line. - pub start_pick: Option, - /// [`Self::start_pick`]'s dialogs are sheets on the window (macOS): while one is open the app - /// neither quits nor closes documents, as under the modal dialog before. - pub dialogs_are_sheets: bool, - /// The window is on Wayland: the tool cursors are painted into it instead of handed to the - /// compositor as bitmaps ([`cursors::os_cursors`]). - pub wayland: bool, - /// On Wayland, no cursor theme can be loaded, so winit sets no pointer and the compositor's - /// default one would never come back once the canvas hid it: the canvas keeps the system - /// pointer and paints no tool glyph ([`cursors::paint_glyphs`], #2450). - pub no_cursor_theme: bool, - /// The pen pressure and pen end the host reads from the system itself (desktop Linux under - /// X11 and XWayland, macOS and Windows). The canvas uses the pressure when a frame's events carry no touch force, - /// and the end to switch to the Eraser tool and back. Without it, pen pressure comes from - /// touch events only ([`stylus`]). - pub stylus: Option, - /// The host's rewrites of a window's raw input (pen barrel button, closing the macOS menu - /// bar's open menu) for floating panels in OS windows of their own: eframe runs the host's - /// `raw_input_hook` for the main window only. + // PLAN: assumed `craft::menu::NativeMenu` is the facade path of `craft_menu::NativeMenu` + pub native_menu: Option, + /// The host's rewrites of a window's raw input (pen barrel button) for floating panels in OS + /// windows of their own: eframe runs the host's `raw_input_hook` for the main window only. pub native_input_hook: Option, - /// The connected monitors, kept current by the desktop host: floating panels in OS windows of - /// their own store the monitor they are on and reopen on it. The rects are in the points egui - /// reports for a window on that monitor. Empty on the web, and where the host cannot place a - /// window by these points, which sends floating panels to the main window's monitor. - pub dock_monitors: Vec, /// The text Help › Copy Troubleshooting Info copies (desktop: the platform, the graphics /// processor, recent commands and frame times, and the hang reports of this session and the /// one before). Without it the command copies the version only ([`crate::troubleshooting`]).