diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 33106085a5..5c802e799e 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -122,10 +122,12 @@ jobs: cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} lint-cache: false - # The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them. + # The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a + # workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them. unreached-rs-allow: | **/fixtures/** vendor/** + crates/pdf/read-only-contract/** timeout-minutes: &timeout 120 # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). tools: &tools cargo-nextest@0.9.150 diff --git a/Cargo.lock b/Cargo.lock index 59f96c7eee..db35446e07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2040,6 +2040,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", ] @@ -2272,6 +2273,7 @@ dependencies = [ "craft-ai-agents", "craft-atomic", "craft-flags", + "craft-platform", "dirs", "getrandom 0.3.4", "log", @@ -2410,6 +2412,7 @@ name = "craft-dialogs" version = "0.1.0" dependencies = [ "block2 0.6.2", + "craft-appkit", "craft-atomic", "craft-behavior", "craft-browse", @@ -4155,6 +4158,7 @@ dependencies = [ name = "craft-suite-account" version = "0.1.0" dependencies = [ + "craft-platform", "dirs", "keyring", "keyring-core", @@ -5581,7 +5585,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "emath", @@ -5637,7 +5641,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -5672,7 +5676,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit", "ahash", @@ -5691,7 +5695,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -5710,7 +5714,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5730,7 +5734,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "egui", @@ -5743,7 +5747,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "eframe", "egui", @@ -5820,7 +5824,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", ] @@ -5893,7 +5897,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -5919,7 +5923,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[package]] name = "equator" @@ -15251,19 +15255,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" diff --git a/Cargo.toml b/Cargo.toml index 7166c5a781..3608b63e20 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -317,20 +317,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid 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/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..8377eb8cfb 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -200,8 +200,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) => { @@ -212,7 +220,7 @@ impl ControlChannel { Reply::AccessTree => self.tree_waiters.push(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})); } } 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/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/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/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 14a752fe9e..298e6419aa 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -41,8 +41,8 @@ pub struct Workspace

{ /// goes back. #[serde(default)] hidden: Vec<(P, Location

)>, - /// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the - /// workspace. + /// Floating panels with the docked location each one left, so Dock Panel can return it; a closed panel that + /// floats records the place it would reopen at. 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 +264,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 +288,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/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 1d25354fdc..b6eea87da1 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -241,6 +241,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { assert!(workspace.floated().is_empty(), "closing 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/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