diff --git a/Cargo.lock b/Cargo.lock index 785cdc401c..d64fbf82ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1906,6 +1906,7 @@ dependencies = [ "craft-scraft-format", "craft-settings", "craft-sf2", + "craft-shared-vec", "craft-sheet", "craft-shx", "craft-silhouette-studio", @@ -2044,6 +2045,7 @@ name = "craft-appkit" version = "0.1.0" dependencies = [ "block2 0.6.2", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", ] @@ -2277,6 +2279,7 @@ dependencies = [ "craft-atomic", "craft-control-protocol", "craft-flags", + "craft-platform", "dirs", "getrandom 0.3.4", "log", @@ -2415,6 +2418,7 @@ name = "craft-dialogs" version = "0.1.0" dependencies = [ "block2 0.6.2", + "craft-appkit", "craft-atomic", "craft-behavior", "craft-browse", @@ -4079,6 +4083,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-shared-vec" +version = "0.1.0" +dependencies = [ + "craft-shared-vec", + "proptest", + "serde", + "serde_json", +] + [[package]] name = "craft-sheet" version = "0.1.0" @@ -4198,6 +4212,7 @@ dependencies = [ name = "craft-suite-account" version = "0.1.0" dependencies = [ + "craft-platform", "dirs", "keyring", "keyring-core", diff --git a/Cargo.toml b/Cargo.toml index 0782449467..ed10972d58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ craft-ssip = { path = "crates/ssip" } craft-ber = { path = "crates/ber" } craft-proto = { path = "crates/proto" } craft-render-parity = { path = "crates/render-parity" } +craft-shared-vec = { path = "crates/shared-vec" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` diff --git a/README.md b/README.md index b3508121a7..d6a05ffc3a 100644 --- a/README.md +++ b/README.md @@ -388,6 +388,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui` feature). - [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md). +- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`. - [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies. - [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft. - [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused. diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml index ad602e383a..5d451b3975 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-appkit" -description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." version.workspace = true edition.workspace = true license.workspace = true @@ -8,11 +8,12 @@ rust-version.workspace = true repository.workspace = true # `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through -# `NSNotificationCenter` with a block. +# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } +objc2 = { version = "0.6.4", default-features = false, features = ["std"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] } # The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 78dd786b15..70ed01f92d 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,5 @@ -//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS -//! only; the crate is empty elsewhere. +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the +//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound. @@ -14,6 +14,8 @@ use block2::RcBlock; use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; use objc2_foundation::{NSNotification, NSNotificationCenter}; +pub mod save_panel; + /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` /// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once /// for the process; a later call replaces nothing and does nothing. diff --git a/crates/appkit/src/save_panel.rs b/crates/appkit/src/save_panel.rs new file mode 100644 index 0000000000..979be8f96d --- /dev/null +++ b/crates/appkit/src/save_panel.rs @@ -0,0 +1,64 @@ +//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action. + +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; +use objc2_app_kit::{NSPopUpButton, NSSavePanel}; +use objc2_foundation::{NSObject, NSObjectProtocol}; + +/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems +/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it. +pub fn new_save_panel(mtm: MainThreadMarker) -> Option> { + // SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as + // `Option`, so nil is `None`. + let panel: Option> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] }; + if panel.is_some() { + return panel; + } + // SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`. + unsafe { msg_send![NSSavePanel::class(), savePanel] } +} + +/// The closure a [`PopUpChoice`] calls. +pub struct Ivars { + on_choose: Box, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[ivars = Ivars] + #[name = "CraftPopUpChoice"] + /// The target of a pop-up menu's action; see [`on_choose`]. + pub struct PopUpChoice; + + // SAFETY: NSObjectProtocol has no additional requirements. + unsafe impl NSObjectProtocol for PopUpChoice {} + + impl PopUpChoice { + // SAFETY: NSControl's target-action sends the pop-up button as the one object argument. + #[unsafe(method(choose:))] + fn choose(&self, sender: &NSPopUpButton) { + if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) { + (self.ivars().on_choose)(index); + } + } + } +); + +/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target, +/// so the caller keeps the returned object for as long as `popup` can send its action. +pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained { + let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) }); + // SAFETY: NSObject's designated initializer, called once on the allocated subclass. + let target: Retained = unsafe { msg_send![super(this), init] }; + let object: &AnyObject = ⌖ + // SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps + // `target` alive while `popup` can send it (the documentation above). + unsafe { + popup.setTarget(Some(object)); + popup.setAction(Some(sel!(choose:))); + } + target +} diff --git a/crates/automation/README.md b/crates/automation/README.md index 2fdbf75be4..120e046f3e 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index 6296beea76..c240725742 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -16,7 +16,7 @@ use crate::security; use crate::server::{self, Listening}; /// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so -/// freeing a taken port is enough. +/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`]. pub const RETRY: Duration = Duration::from_secs(5); /// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence @@ -123,6 +123,10 @@ pub struct AgentLink { applied: Option>, retry_at: Option, retry: Duration, + /// The token a failed start already read and checked, for its retries with the same settings; + /// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms + /// on the UI thread, which every retry of a taken port would otherwise pay again. + checked_token: Option, status: AgentLinkStatus, } @@ -144,6 +148,7 @@ impl AgentLink { applied: None, retry_at: None, retry: RETRY, + checked_token: None, status: AgentLinkStatus::default(), } } @@ -166,7 +171,12 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` - /// equals the last call's and no retry of a failed start is due. + /// equals the last call's and no retry of a failed start is due. A token file refused as it is + /// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still + /// can't be used (a folder in its place, a folder that can't be written) schedules no retry: + /// that lasts until someone changes it, and on Windows each check blocks the UI thread for + /// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`] + /// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again. pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { let mut update = LinkUpdate::default(); if self.launch.is_some() { @@ -174,9 +184,15 @@ impl AgentLink { } let now = motion::now(); let retry_due = self.retry_at.is_some_and(|at| now >= at); - if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due { + let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want); + if unchanged && !retry_due { return update; } + // Only a retry with the same settings reuses the token its failed start checked: after a + // change (agents off and on again, another port) the file may hold another token by now. + if !unchanged { + self.checked_token = None; + } let before = (self.status.clone(), self.applied.clone().flatten()); self.applied = Some(want.cloned()); self.retry_at = None; @@ -218,6 +234,10 @@ impl AgentLink { update.requests = Some(requests); Ok(()) } + Err(problem @ LinkProblem::TokenFile(_)) => { + log::warn!("{problem}"); + Err(problem) + } Err(problem) => { log::warn!("{problem}"); self.retry_at = Some(motion::now() + self.retry); @@ -229,13 +249,21 @@ impl AgentLink { /// The token from the settings folder (created `0600` when missing), the server, then the /// connection file. Any failure leaves nothing running. - fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { + /// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]). + /// The token file is the link's own, so one refused as it is gets a new token (see + /// [`fresh_token`]). + fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { let token_file = dir.join(TOKEN_FILE); - let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?; + let token = match self.checked_token.clone() { + Some(token) => token, + None => fresh_token(&token_file)?, + }; + self.checked_token = Some(token.clone()); let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?; let running = Running { server, dir: dir.to_path_buf(), port_pref }; let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone()); write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?; + self.checked_token = None; Ok((running, requests)) } @@ -250,3 +278,22 @@ impl AgentLink { self.status.problem = Some(problem); } } + +/// The token in `token_file`, created when missing. A regular file the check refuses (one an +/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged +/// token) is replaced with a new token, once: the token is only this link's secret, and a client +/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted +/// the file. Anything else in the way (a folder, a link) is reported, not removed. +fn fresh_token(token_file: &Path) -> Result { + let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string())); + let problem = match read() { + Ok(token) => return Ok(token), + Err(problem) => problem, + }; + if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) { + return Err(problem); + } + log::warn!("{problem}; writing a new token file"); + std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?; + read() +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index b1c005dadf..2290c7c08f 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -5,8 +5,9 @@ //! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the //! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued //! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees -//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes -//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]). +//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's +//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through +//! [`crate::screenshot::Captures`]). //! //! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch //! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave @@ -15,6 +16,7 @@ use std::sync::mpsc::{Receiver, Sender}; +use craft_ui::dialog::{DialogHost, DialogId, HeldOk}; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; @@ -133,6 +135,19 @@ pub enum Reply { /// A `ui.accessTree`: hold the reply until the window's settled access tree can be read /// ([`ControlChannel::poll_access_trees`]). AccessTree, + /// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the + /// app answers it ([`ControlChannel::poll_held`]). + #[non_exhaustive] + AfterHeldOk { + /// The dialog whose OK is held. + dialog: DialogId, + /// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog + /// is not the one the request confirmed. + open: u64, + /// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it: + /// the earlier confirms still held for this open are answered with it. + refused: Option, + }, } impl Reply { @@ -174,6 +189,7 @@ pub struct ControlChannel { input_waiters: Vec>, job_waiters: Vec<(JobId, Sender)>, tree_waiters: Vec>, + held_waiters: Vec<(DialogId, u64, Sender)>, /// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases. pub captures: Captures, } @@ -181,7 +197,14 @@ pub struct ControlChannel { impl ControlChannel { /// Attach a transport's receiver (TCP, stdin, tests). pub fn new(rx: Receiver) -> Self { - Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() } + Self { + rx, + input_waiters: Vec::new(), + job_waiters: Vec::new(), + tree_waiters: Vec::new(), + held_waiters: Vec::new(), + captures: Captures::default(), + } } /// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned @@ -200,8 +223,16 @@ impl ControlChannel { /// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the /// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time); - /// `document` the identity a screenshot is attributed to. + /// `document` the identity a screenshot is attributed to. A screenshot is admitted at + /// [`motion::now`]; [`Self::settle_at`] takes the time instead. pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64) { + self.settle_at(req, outcome, document, settle_ms, motion::now()); + } + + /// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its + /// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to + /// [`Captures::issue`] and [`Captures::drain`]. + pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option, settle_ms: f64, now: Instant) { let reply = req.reply; match outcome { Reply::Done(v) => { @@ -210,9 +241,21 @@ impl ControlChannel { Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), Reply::AccessTree => self.tree_waiters.push(reply), + Reply::AfterHeldOk { dialog, open, refused } => { + if let Some(reason) = refused { + self.held_waiters.retain(|(earlier, earlier_open, tx)| { + let answered = (*earlier, *earlier_open) == (dialog, open); + if answered { + let _ = tx.send(json!({"ok": false, "error": reason})); + } + !answered + }); + } + self.held_waiters.push((dialog, open, reply)); + } Reply::Screenshot { token, path, region, viewport } => { let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms }; - if let Err((reply, e)) = self.captures.admit(request, motion::now()) { + if let Err((reply, e)) = self.captures.admit(request, now) { let _ = reply.send(json!({"ok": false, "error": e})); } } @@ -291,6 +334,29 @@ impl ControlChannel { } } + /// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success + /// once the app accepted the dialog's held OK; once it refused it, an error whose text is the + /// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed + /// while it waited, also when the same dialog opened again since. A request stays held while + /// the app has not answered. Call it in every pass after the app answered the held OKs it + /// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a + /// dialog the app accepted; calling it more than once in a pass is harmless. + pub fn poll_held(&mut self, host: &DialogHost) { + self.held_waiters.retain(|(dialog, open, reply)| { + let answer = match host.held_state(*dialog) { + _ if host.open_serial(*dialog) != Some(*open) => { + json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"}) + } + Some(HeldOk::Waiting) => return true, + Some(HeldOk::Accepted) => json!({"ok": true, "result": null}), + Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}), + _ => json!({"ok": false, "error": "the app refused OK"}), + }; + let _ = reply.send(answer); + false + }); + } + /// Drops the host's queued input and the step in flight, and fails every /// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters /// remain (their input was already consumed). True when anything was pending or waiting. @@ -331,6 +397,6 @@ impl ControlChannel { /// Waiters of every kind, for `ui.inspect`'s `pending` count and tests. pub fn waiting(&self) -> usize { - self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending() + self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending() } } diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 398c917c57..749626cc61 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -1,7 +1,8 @@ //! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type. //! -//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s -//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its +//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits +//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the +//! `id` `inspect` lists, or `"top"` for the top one; its fields are its //! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and //! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a //! click's would. @@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt}; use egui::Context; use serde_json::{Value, json}; +use crate::control::Reply; use crate::protocol::Params; /// The most `fields` one `ui.dialog.set` call takes. @@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value { /// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field, /// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]). /// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field -/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it. +/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it; +/// a second confirm while that answer waits is refused. /// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape /// answer gives that answer, with its tag; any other dialog closes with its children with Cancel. pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { @@ -49,6 +52,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: Some(run(host, ctx, method, params, fields)) } +/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a +/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it +/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal +/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once. +pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option { + // The dialog is named before the call: a confirm that closes it may leave another dialog on top. + let named = dialog_id(host, params).ok(); + // A refusal this confirm replaces still answers the confirms it refused. + let refused = match named.and_then(|id| host.held_state(id)) { + Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()), + _ => None, + }; + let result = dialog_method(host, ctx, method, params)?; + let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting)); + Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) { + Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused }, + None => Reply::from_result(result), + }) +} + fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result { let params = Params(params).only(None, fields)?; let read = Params(¶ms); @@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field } }, "ui.dialog.confirm" => { + // A second OK while the first waits files nothing, as the disabled button shows. + if host.held_state(id) == Some(HeldOk::Waiting) { + return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned()); + } if let Some(choice) = params.get("choice") { host.set_json_field(ctx, id, "choice", choice.clone())?; } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 259d2f3cb2..8e75f07ecd 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -8,8 +8,11 @@ //! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept //! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it. +#[cfg(not(windows))] use std::fs::OpenOptions; -use std::io::{BufRead, Write}; +use std::io::BufRead; +#[cfg(not(windows))] +use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; @@ -319,30 +322,34 @@ fn read_token_file(path: &Path) -> Result { Ok(token) } -fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { +/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one +/// that caused it, with the path in its message. +fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> { + let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display())); if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?; + std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?; } - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token - // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + // On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's + // access list, and the token is written through the handle that created it. #[cfg(windows)] { use craft_platform::owner_only; - if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { - drop(file); - let _ = std::fs::remove_file(path); - return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + owner_only::current_user_sid() + .and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes())) + .map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) + } + #[cfg(not(windows))] + { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); } + let mut file = options.open(path).map_err(|e| at(path, e))?; + writeln!(file, "{token}").map_err(|e| at(path, e)) } - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } /// The server's token, lower-cased. Both given is @@ -355,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// file can be reached by others: ; restrict it to its owner`), and its trimmed content is /// validated. A missing one is created with a generated token (parent directories created, /// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a -/// newline); losing that create race to another process reads the winner's file instead. +/// newline); losing that create race to another process reads the winner's file instead. On +/// Windows a create that does not finish in time fails (`I/O: : cannot create the control +/// token file for its owner only: `), and a file it left at the path is not read as a winner's. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { + server_token_with(supplied, token_file, create_token_file) +} + +/// [`server_token`], with `create` making a missing token file. +fn server_token_with( + supplied: Option<&str>, + token_file: Option<&Path>, + create: impl FnOnce(&Path, &str) -> std::io::Result<()>, +) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); } @@ -370,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result }; match read_token_file(path) { Ok(existing) => Ok(existing.to_ascii_lowercase()), - Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) { + Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) { Ok(()) => Ok(token), - // Another process won the create-new race. - Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), - Err(e) => Err(e), + // Another process won the create-new race. A file left by a create that ran out of time is this one's. + Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), + Err(e) => Err(AutomationError::Io(e.to_string())), }, Err(e) => Err(e), } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index b5ba980c95..2716fc24c2 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -141,6 +141,12 @@ fn server_token_sources_and_validation() { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); } + #[cfg(windows)] + { + use craft_platform::owner_only; + let sddl = owner_only::sddl_of(&file).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); + } assert_eq!(server_token(None, Some(&file)).unwrap(), created); // An existing file's content is trimmed and lower-cased. @@ -163,3 +169,25 @@ fn server_token_sources_and_validation() { "bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE" ); } + +// A token file create that runs out of time fails with its own error, even when it left a file at +// the path: that file is not read as another process's. A create that another process beat to the +// path reads that process's token. +#[trial] +fn a_token_file_create_that_runs_out_of_time_is_an_error() { + let dir = scratch_dir("token-limit"); + let file = dir.join("token"); + let late = |p: &Path, _: &str| { + std::fs::write(p, "partial").unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display()))) + }; + let err = server_token_with(None, Some(&file), late).unwrap_err().to_string(); + assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}"); + std::fs::remove_file(&file).unwrap(); + let beaten = |p: &Path, _: &str| { + create_token_file(p, TOKEN).unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")) + }; + assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index bea9c8d5a5..31481f4cb1 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ //! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`, -//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. +//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -12,7 +12,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -22,8 +23,7 @@ //! //! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action //! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a -//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a -//! drag is `ui.click {hold}`, `ui.move` and `ui.release`. +//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. use std::path::PathBuf; @@ -43,6 +43,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -302,6 +308,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?, control?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are placed before anything is queued (a control point against the access tree the host kept for + /// `viewport`), so a point that cannot be placed leaves no press down. When the host withdraws the rest of the + /// gesture after its press ran, the button stays down until `ui.release`, as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.place(host, viewport, map)?, self.to.place(host, viewport, map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// The most notches one `ui.wheel` turn in lines may ask for, either way. pub const MAX_NOTCHES: f32 = 100.0; @@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V "ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)), "ui.drop" => drop_files(params, host, viewport, map), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 7ca7bb5f0c..6cca4325a2 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -308,6 +308,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() { TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); } +/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the +/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every +/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again. +#[trial] +fn a_refused_token_file_is_not_retried_until_the_settings_change() { + let dir = temp_dir("link-token-no-retry"); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let wanted = free_port(); + assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + // The file is fixed, but the same settings don't look at it again. + std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let same = link.sync(Some(&on(u32::from(wanted))), &host); + assert!(same.requests.is_none() && !same.changed, "no retry with the same settings"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + let changed = link.sync(Some(&on(0)), &host); + assert!(changed.requests.is_some(), "a settings change tries again"); + assert_eq!(link.status().problem, None); +} + +/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its +/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can +/// connect instead of staying out until someone deletes the file (photocraft#17006). +#[trial] +fn a_refused_token_file_is_replaced_with_a_new_token() { + let dir = temp_dir("link-token-refresh"); + let file = dir.path().join(TOKEN_FILE); + std::fs::write(&file, "not a token\n").unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + let token = std::fs::read_to_string(&file).unwrap(); + assert_ne!(token.trim(), "not a token"); + assert_eq!(token.trim().len(), 64, "a new token: {token:?}"); + assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening")); +} + +/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows +/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time. +#[trial] +fn a_taken_port_retry_reuses_the_checked_token() { + let dir = temp_dir("link-token-reuse"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + // Reading the file now fails, so a retry that read it would report a token file problem. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let retried = link.sync(Some(&on(port)), &host); + assert!(retried.requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + + // Once a start succeeded, the next one reads the file again. + let moved = link.sync(Some(&on(0)), &host); + assert!(moved.requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + +/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token +/// file again, so a server never listens with a token the file no longer holds. +#[trial] +fn a_settings_change_reads_the_token_file_again() { + let dir = temp_dir("link-token-settings"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + assert!(!link.sync(None, &host).stopped, "nothing was running"); + // While agents are off the token file changes; here it can't be read at all, which the next start must report. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let back = link.sync(Some(&on(port)), &host); + assert!(back.requests.is_none(), "started with the token the file no longer holds"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + /// Dropping the link stops its server and removes its connection file. #[trial] fn dropping_the_link_removes_its_connection_file() { diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index ad6986f096..b15b926dcd 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -1,9 +1,13 @@ //! `ui.dialog.*` on typed dialogs through one generic path. -use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect}; +use std::sync::mpsc::{Receiver, channel}; + +use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse}; +use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect}; use craft_ui::contract::{Bind, SaveKey}; -use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; +use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft_ui::runtime::env::{Label, Word}; use craft_ui::testing::trial; use egui::Context; use serde_json::{Value, json}; @@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() { assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); } +const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists"); + +/// The open parameter dialog `id` names. +fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog { + host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).expect("the held dialog is open") +} + +/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered, +/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog +/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a +/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once. +#[trial] +fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + let (_requests, rx) = channel(); + let mut control = ControlChannel::new(rx); + let dialog = |ctx: &Context, held: bool| { + let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields)) + }); + if held { dialog.held_ok() } else { dialog } + }; + let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver { + let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()})); + let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method"); + control.settle(request, outcome, None, 0.0); + reply + }; + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + control.poll_held(&host); + assert!(reply.try_recv().is_err(), "the reply waits for the app's answer"); + assert_eq!(control.waiting(), 1); + let again = confirm(&mut host, &mut control, id); + assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused"); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 0); + + // A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal. + let first = confirm(&mut host, &mut control, id); + assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal"); + held(&mut host, id).answer_ok(Err(Label::from(TAKEN))); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"}))); + assert_eq!(control.waiting(), 1); + assert!(held(&mut host, id).take_ok().is_some()); + held(&mut host, id).answer_ok(Ok(())); + control.poll_held(&host); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null}))); + assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes"); + assert!(matches!(host.take_keyed::(), Some((DialogResult::Ok(_), _)))); + + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + control.poll_held(&host); + let closed = reply.try_recv().expect("a closed dialog answers the held confirm"); + assert_eq!(closed["ok"], false); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + host.take_keyed::(); + + // The same dialog opened again is a new open: its answer is not the closed one's. + let id = host.open(dialog(&ctx, true)); + let reply = confirm(&mut host, &mut control, id); + assert!(host.cancel_by_id(&ctx, id)); + assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id"); + assert_eq!(control.waiting(), 1); + control.poll_held(&host); + let closed = reply.try_recv().expect("the closed open's confirm is answered"); + assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}"); + assert!(host.cancel_by_id(&ctx, id)); + host.take_keyed::(); + + let id = host.open(dialog(&ctx, false)); + let reply = confirm(&mut host, &mut control, id); + assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once"); + assert_eq!(control.waiting(), 0); +} + /// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that /// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread. #[trial] diff --git a/crates/automation/tests/it/screenshot.rs b/crates/automation/tests/it/screenshot.rs index e9f06c409e..28a0ac8f35 100644 --- a/crates/automation/tests/it/screenshot.rs +++ b/crates/automation/tests/it/screenshot.rs @@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() { } } +/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app +/// also passes to `issue` and `drain`, not from the wall clock. +#[trial] +fn a_screenshot_settled_at_a_time_counts_from_that_time() { + use craft_automation::control::{ControlChannel, ControlRequest, Reply}; + use craft_automation::screenshot::ScreenshotParams; + use serde_json::json; + + let ctx = Context::default(); + // An app clock ahead of the wall clock. + let arrived = motion::now() + Duration::from_secs(60); + let (_transport, requests) = channel(); + let mut control = ControlChannel::new(requests); + control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0)); + let (request, rx) = ControlRequest::new("ui.screenshot", json!({})); + let params = ScreenshotParams::from_params(&json!({})).expect("no params"); + control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived); + assert!(rx.try_recv().is_err(), "the reply waits for the capture"); + + let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None); + assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::>()); + assert!(callbacks.is_empty(), "not issued inside its settle delay"); + assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline"); + let finished = control.captures.drain(arrived + DEADLINE, None); + assert_eq!(finished.len(), 1); + assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0])); +} + /// Cancelling releases the budget at once; an image that arrives afterwards is dropped. #[trial] fn cancellation_releases_the_budget_and_drops_a_late_image() { diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index ee2c484f6c..dc3ca5efb6 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,12 +1,12 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::access::NO_TREE; -use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::access::{NO_CONTROL, NO_TREE}; +use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -123,6 +123,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -292,6 +338,25 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. That holds +/// for a document end without a canvas and for a control end that names no control of the window. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); + let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}}); + let answer = input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &map); + assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}"); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -358,6 +423,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "y": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})), ("ui.move", json!({"x": 10, "y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 442c65f8b0..74879e4676 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -42,7 +42,8 @@ pub struct Workspace

{ #[serde(default)] hidden: Vec<(P, Location

)>, /// Floating panels, and closed panels that were floating, with the docked location each one left, so Dock Panel - /// can return it. A closed panel's record lives as long as its `hidden` record. Saved with the workspace. + /// can return it; a closed panel that floats records the place it would reopen at. A closed panel's record lives + /// as long as its `hidden` record. Saved with the workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] floated: Vec<(P, Location

)>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. @@ -264,6 +265,16 @@ impl Workspace

{ Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?, _ => false, }; + // Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel + // that would reopen in a floating window has no docked place. + let hidden_place = match &action { + Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed + .restored(panel, &policy) + .filter(|restored| !floats(&restored.layout, panel)) + .and_then(|restored| restored.layout.location(panel).ok()) + .map(|location| (panel.clone(), location)), + _ => None, + }; if !reopened { // SetNative records where the window system has a floating window, so a lock // does not refuse it. @@ -278,6 +289,12 @@ impl Workspace

{ proposed.hidden.push((panel, location)); } proposed.track_floated(&before); + if let Some((panel, location)) = hidden_place + && floats(&proposed.layout, &panel) + && !proposed.floated.iter().any(|(p, _)| p == &panel) + { + proposed.floated.push((panel, location)); + } all_closed.extend(closed); } let visible: HashSet

= proposed.layout.panels().into_iter().cloned().collect(); diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..4b8355d7cf 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,7 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. +//! All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,19 +231,39 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } - /// The item with a shorter form `extent` long, which it takes before any free item leaves. + /// The item with a shorter form `extent` long, which it takes before any free item leaves unless it is late. + /// An item marked [`FitItem::short_late`] takes that form only after no free item is left to leave. pub const fn short(mut self, extent: f32) -> Self { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: lower ranks shorten first, and the last item of a rank first. + /// Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left. + /// The other items go to the overflow menu before this one shortens. A free item with a late short form leaves + /// in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +298,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +325,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index bd782a0e9c..103a97fcf0 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -85,15 +85,12 @@ pub struct GridCursor { impl GridCursor { /// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A /// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share - /// does not go below it. + /// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns. pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self { let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0); let content: Vec = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect(); - let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x) - .into_iter() - .enumerate() - .map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width }) - .collect(); + let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x); + keep_fill_least(columns, &mut widths, least); let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect(); GridCursor { flow, @@ -266,6 +263,44 @@ impl GridCursor { } } +/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a +/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight. +/// The fill columns together take more than their room only when their least widths do not fit in it. +fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) { + let fills: Vec<(usize, f32)> = columns + .iter() + .enumerate() + .filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None }) + .collect(); + let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum(); + if !room.is_finite() { + // Room with no bound leaves every share above its least. + for (i, _) in &fills { + widths[*i] = widths[*i].max(least(*i)); + } + return; + } + let mut raised = vec![false; columns.len()]; + loop { + let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::(); + let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum(); + let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 }; + let mut more = false; + for (i, weight) in &fills { + if !raised[*i] && share(*weight) < least(*i) { + raised[*i] = true; + more = true; + } + } + if !more { + for (i, weight) in &fills { + widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) }; + } + return; + } + } +} + /// `columns` with each `Fill` column as a `Content` column. fn as_content(columns: &[ColumnWidth]) -> Vec { columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect() @@ -288,4 +323,43 @@ mod tests { cursor.cell(Vec2::new(150.0, 100.0)); assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds"); } + + /// The widths of one row of `columns` placed by `last`, read from the cells. + fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec { + let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last); + columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect() + } + + #[test] + fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &fitting); + let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0])); + assert!(shares[0] < 120.0, "the first column's share is below its least"); + assert!(raised[0] >= 120.0, "the first column keeps its least"); + assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow"); + assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights"); + assert_eq!(raised[3], shares[3], "the content column keeps its width"); + assert_eq!(raised.iter().sum::(), 300.0, "the row fills the grid and no more"); + } + + #[test] + fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]); + let widths = row_widths(&columns, &last); + assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least"); + assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room"); + assert_eq!(widths.iter().sum::(), 330.0, "the row is as wide as the least widths and no wider"); + } + + #[test] + fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &last); + let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0])); + assert_eq!(kept, shares); + } } diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index 0aae495027..495b781c6d 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool { } /// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can -/// tell it from a number or an operator. +/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch). pub fn is_unit_spelling(spelling: &str) -> bool { - !spelling.is_empty() && spelling.chars().all(is_unit_char) + let letters = spelling.strip_prefix('/').unwrap_or(spelling); + !letters.is_empty() && letters.chars().all(is_unit_char) } /// A unit spelling and the factor that turns its quantity into the base unit. @@ -41,7 +42,9 @@ struct Unit { /// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it /// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest /// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a -/// quantity when `px` is registered. A group separator counts only before exactly three digits. +/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after +/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before +/// exactly three digits. #[derive(Clone, Debug, PartialEq)] pub struct Reader { decimal: char, @@ -213,8 +216,9 @@ impl Parse<'_> { } } - /// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no - /// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it. + /// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a + /// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them, + /// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide. fn quantity(&mut self, scaled: bool) -> Result { let number = self.number()?; self.tag = None; @@ -223,8 +227,11 @@ impl Parse<'_> { return Ok(number / 100.0); } let reader = self.reader; - let run: Vec = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); - let unit = (1..=run.len()).rev().find_map(|len| { + let after = &self.chars[self.at..]; + let slash = usize::from(after.first() == Some(&'/')); + let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count(); + let run = &after[..slash + letters]; + let unit = (1 + slash..=run.len()).rev().find_map(|len| { let lowered = run[..len].iter().collect::().to_lowercase(); reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit)) }); @@ -326,6 +333,20 @@ mod tests { near(&percent, "2%", 14.0); assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share"); + let per_inch = Reader::new().unit_tagged("/in", 1.0, 0); + assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in")); + for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] { + near(&per_inch, text, 40.0); + } + assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit"); + assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product"); + assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value"); + for bad in ["", "/in", "40/inch", "40/"] { + assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value"); + } + near(&lengths, "144/2in", 1.0); + assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number"); + let german = Reader::new().decimal(',').group('.'); near(&german, "1.234,5", 1234.5); near(&german, "1.234.567", 1_234_567.0); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index ba1ff28419..b81db15a6e 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -247,6 +247,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks() { assert!(!floats(workspace.layout(), 3) && workspace.floated().is_empty(), "docking back drops the record"); } +/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old +/// group keeps its front tab; docking it then returns it to that group at its old index. +#[test] +fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() { + let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0)); + let mut opened = Workspace::new(docked()); + opened.apply(Action::close(2), false, allow).unwrap(); + opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap(); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(float, false, allow).unwrap(); + let layout = workspace.layout(); + assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. }))); + assert_eq!(group_members(layout, 3), [3]); + assert_eq!(front(layout, 3), 3, "the old group keeps its front tab"); + assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives"); + + let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) }; + let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone()); + workspace.apply(back, false, allow).unwrap(); + assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index"); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(6), false, allow).unwrap(); + workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place"); +} + /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index a153276ada..254d30f628 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> { Variation::WarmCool => (&words.cool, &words.warm), Variation::VividMuted => (&words.muted, &words.vivid), }; - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(left.clone()).show(ui); Text::new(right.clone()).show(ui); }); diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index 28de7cc7b1..64213ce9a8 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter; use craft_keymap::Mods; use craft_theme::Srgba; use craft_ui::buttons::{Button, PopupMark}; -use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring}; +use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band}; use craft_ui::contract::{ Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, @@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra if style.ring { let ground = ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) }); - ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground); + ui.draw().surface_styled(well.shrink(ring_band(well)), &ground); } else { ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge); } diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 90c92271b2..d79e86cf93 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -448,7 +448,7 @@ pub struct ColorPanel<'a> { wells: Option<([PairWell; 2], Bind<'a, Well>)>, edited: Option>, shown: Option, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option, gamut: Option>, } @@ -471,7 +471,7 @@ struct Inputs<'a> { wells: Option<&'a [PairWell; 2]>, edited: Option<&'a Option>, shown: &'a ColorPanelShown, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option<&'a RecentSetup>, } @@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> { wells: None, edited: None, shown: None, - recent: &[], + recent: None, recent_setup: None, gamut: None, } @@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> { self } - /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. + /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row + /// for a host that gives them, an empty list included; without them it shows no row. pub fn recent(mut self, colors: &'a [Srgba]) -> Self { - self.recent = colors; + self.recent = Some(colors); self } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index a3ff66c160..183844b574 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed}; use craft_theme::Srgba; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; -use craft_ui::display::Text; +use craft_ui::display::{Shade, Text}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::Label; +use craft_ui::style::TypeRole; use craft_ui::text::{HexField, TextField}; use egui::Ui; @@ -131,8 +132,8 @@ impl Body<'_> { } } - /// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and - /// picks nothing; a Shift click moves to the next mode. + /// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end + /// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode. fn spectrum(&mut self, ui: &mut Ui) { let mode = self.shown_mode(); let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum }; @@ -145,6 +146,7 @@ impl Body<'_> { .gamut(gamut) .gamut_revision(revision) .web_safe(self.now.web_safe_ramp) + .square_boxes(true) .sizing(Sizing::Fill) .show(ui); self.ramp_events(ramp.edit.events); @@ -154,14 +156,19 @@ impl Body<'_> { } } - /// The Recent Colors as a spaced palette; a pick sets the colour. + /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list + /// is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { - if self.inputs.recent.is_empty() { + let Some(recent) = self.inputs.recent else { + return; + }; + Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui); + if recent.is_empty() { return; } - let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); + let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); let mut current = self.color(); let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced); if let Some(setup) = self.inputs.recent_setup { diff --git a/crates/color-ui/src/ui/ramp.rs b/crates/color-ui/src/ui/ramp.rs index 2a01579348..e541695543 100644 --- a/crates/color-ui/src/ui/ramp.rs +++ b/crates/color-ui/src/ui/ramp.rs @@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter; use craft_theme::{Hsb, Srgba}; use craft_ui::canvas::context_click; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi, + PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; use craft_ui::primitives::{Marker, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::FireSource; @@ -240,6 +240,11 @@ pub struct ColorRamp<'a> { /// Whether the white and black boxes follow the bar; on by default. #[prop] boxes: bool, + /// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a + /// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by + /// its content and in a short one. + #[prop] + square_boxes: bool, /// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value. #[prop(into)] kind_name: Option