Merge next into main

This commit is contained in:
aiongg committed 2026-11-26 05:38:41 +00:00
commit ecdc221f4a
288 files changed
+9931 -932

No files matched your search

Generated
+15
View File
@@ -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",
+1
View File
@@ -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-<name> = { path = "crates/<name>" }`
+1
View File
@@ -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.
+5 -4
View File
@@ -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
+4 -2
View File
@@ -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.
+64
View File
@@ -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<Retained<NSSavePanel>> {
// 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<Retained<NSSavePanel>> = 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<dyn Fn(usize)>,
}
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<PopUpChoice> {
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<PopUpChoice> = unsafe { msg_send![super(this), init] };
let object: &AnyObject = &target;
// 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
}
+1 -1
View File
@@ -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. |
+52 -5
View File
@@ -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<Option<AgentSettings>>,
retry_at: Option<Instant>,
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<String>,
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<ControlRequest>), 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<ControlRequest>), 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<String, LinkProblem> {
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()
}
+72 -6
View File
@@ -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<String>,
},
}
impl Reply {
@@ -174,6 +189,7 @@ pub struct ControlChannel {
input_waiters: Vec<Sender<ControlResponse>>,
job_waiters: Vec<(JobId, Sender<ControlResponse>)>,
tree_waiters: Vec<Sender<ControlResponse>>,
held_waiters: Vec<(DialogId, u64, Sender<ControlResponse>)>,
/// 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<ControlRequest>) -> 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<DocumentId>, 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<DocumentId>, 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()
}
}
+30 -3
View File
@@ -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<Result<Value, String>> {
@@ -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<Reply> {
// 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<Value, String> {
let params = Params(params).only(None, fields)?;
let read = Params(&params);
@@ -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())?;
}
+41 -23
View File
@@ -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<String, AutomationError> {
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: <why>; 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: <path>: cannot create the control
/// token file for its owner only: <why>`), 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<String, AutomationError> {
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<String, AutomationError> {
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),
}
+28
View File
@@ -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);
}
+76 -4
View File
@@ -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<Self, String> {
let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?;
let p = Params(&p);
let point = |name: &str| -> Result<At, String> {
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)),
+90
View File
@@ -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() {
+91 -2
View File
@@ -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::<HostedParamDialog>()).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<ControlResponse> {
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::<HostedParamDialog>(), 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::<HostedParamDialog>();
// 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::<HostedParamDialog>();
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]
+28
View File
@@ -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::<Vec<_>>());
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() {
+76 -3
View File
@@ -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<Event> = 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<Pos2> = 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", &params, &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", &params, &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})),
+18 -1
View File
@@ -42,7 +42,8 @@ pub struct Workspace<P> {
#[serde(default)]
hidden: Vec<(P, Location<P>)>,
/// 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<P>)>,
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
@@ -264,6 +265,16 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
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<P: Clone + Eq + Hash> Workspace<P> {
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<P> = proposed.layout.panels().into_iter().cloned().collect();
+47 -16
View File
@@ -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<f32>,
/// 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<FitItem> = 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<usize>, Vec<usize>) = (0..items.len()).partition(|&at| shown[at]);
let short = kept.iter().copied().filter(|&at| short[at]).collect();
Fit { shown: kept, overflow: left, short }
+80 -6
View File
@@ -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<f32> = (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::<f32>();
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<ColumnWidth> {
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<f32> {
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::<f32>(), 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::<f32>(), 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);
}
}
+28 -7
View File
@@ -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<f64, NotAValue> {
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<char> = 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::<String>().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);
+29
View File
@@ -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<u32> {
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)]);
+31
View File
@@ -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];
+1 -1
View File
@@ -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);
});
+2 -2
View File
@@ -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);
}
+6 -5
View File
@@ -448,7 +448,7 @@ pub struct ColorPanel<'a> {
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
edited: Option<Option<PickedColor>>,
shown: Option<ColorPanelShown>,
recent: &'a [Srgba],
recent: Option<&'a [Srgba]>,
recent_setup: Option<RecentSetup>,
gamut: Option<Gamut<'a>>,
}
@@ -471,7 +471,7 @@ struct Inputs<'a> {
wells: Option<&'a [PairWell; 2]>,
edited: Option<&'a Option<PickedColor>>,
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
}
+13 -6
View File
@@ -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 {
+14 -2
View File
@@ -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<Label>,
@@ -265,6 +270,7 @@ impl<'a> ColorRamp<'a> {
web_safe: false,
recolor_clicks: false,
boxes: true,
square_boxes: false,
kind_name: None,
colors: Arc::default(),
shown_ends: ends,
@@ -416,6 +422,12 @@ impl Component for ColorRamp<'_> {
Some(Axis::X)
}
/// With [`square_boxes`](ColorRamp::square_boxes), as tall as its two end boxes stacked, each as tall as it is wide;
/// else the style's least, a color band.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
if self.square_boxes { Vec2::new(0.0, cx.style.boxes * 2.0) } else { Vec2::ZERO }
}
fn sense(&self) -> Sense {
Sense::empty()
}
+57 -10
View File
@@ -136,11 +136,19 @@ pub(super) fn group_rename(groups: &[SwatchGroup], index: usize, text: &str) ->
(!name.is_empty() && !groups.iter().enumerate().any(|(i, g)| i != index && g.name == name)).then(|| name.to_owned())
}
/// The flat rows of the browser: each group's header, then its swatches.
/// Whether the browser shows a header row for `group`: every group but the one with an empty name, which holds the
/// swatches outside every group.
fn has_header(group: &SwatchGroup) -> bool {
!group.name.is_empty()
}
/// The flat rows of the browser: each group's header (none for the swatches outside every group), then its swatches.
fn flat<'a>(groups: impl IntoIterator<Item = &'a SwatchGroup>) -> Vec<SwatchKey> {
let mut rows = Vec::new();
for group in groups {
rows.push(SwatchKey::Group(group.name.clone()));
if has_header(group) {
rows.push(SwatchKey::Group(group.name.clone()));
}
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
}
rows
@@ -167,10 +175,21 @@ fn resolve_move(groups: &[SwatchGroup], names: &[&str], to: usize, parent: Optio
(group < groups.len()).then_some((group, slot))
}
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay.
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay: each staying group
/// whose first row (its header, or its first swatch when it has none) is above `to`. Groups never land above the
/// swatches outside every group when those come first.
fn group_slot(groups: &[SwatchGroup], names: &[&str], to: usize) -> usize {
let remaining = flat(groups.iter().filter(|g| !names.contains(&g.name.as_str())));
remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count()
let mut row = 0;
let mut slot = 0;
let mut staying = groups.iter().filter(|g| !names.contains(&g.name.as_str())).peekable();
let floor = usize::from(staying.peek().is_some_and(|g| !has_header(g)));
for group in staying {
if row < to {
slot += 1;
}
row += usize::from(has_header(group)) + group.entries.len();
}
slot.max(floor)
}
/// The `at` of each edit that moves `moved` (in library order) one by one within `order`, so that they end up together
@@ -352,8 +371,8 @@ impl SwatchLibrary {
}
/// Applies a reorder of the browser: swatches go into a group at a place, or groups to a place among the
/// groups. `to` counts in the flat rows (a header, then its swatches) that remain once the moved ones are
/// taken out. Anything else leaves the library as it is.
/// groups. `to` counts in the flat rows (a header, then its swatches; no header for the group with an empty
/// name) that remain once the moved ones are taken out. Anything else leaves the library as it is.
pub fn apply_reorder(&mut self, mv: &ReorderMove<SwatchKey>) -> bool {
if mv.copy {
return false;
@@ -641,17 +660,24 @@ fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>
}
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
/// colour value (the name alone for a swatch without a colour).
/// colour value (the name alone for a swatch without a colour). A group with an empty name holds the swatches outside
/// every group: its swatches show at the top level, with no header.
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
for group in groups {
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
let header = has_header(group);
let depth = usize::from(header);
if header {
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
}
for entry in &group.entries {
let named = match entry.color() {
Some(color) => format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())),
None => entry.name.clone(),
};
rows.push(PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named));
rows.push(
PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), depth).tooltip(named.clone()).accessible_name(named),
);
}
}
rows
@@ -676,6 +702,27 @@ pub(crate) mod tests {
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
}
/// The swatches outside every group (the group with an empty name) have no header row, so a place below them
/// counts them as rows: a group dropped there lands after them, and a swatch dropped there joins them. A group
/// dropped above them lands after them too.
#[trial]
fn drops_below_the_ungrouped_swatches_land_after_them() {
let library = SwatchLibrary::new(vec![group("", &["A", "B"]), group("G", &["C"]), group("H", &["D"])]);
let rows: Vec<_> = swatch_rows(&library.groups, &SwatchesWords::default()).into_iter().map(|row| row.key).collect();
assert_eq!(rows, flat(&library.groups), "the reorder counts the rows the browser shows");
for to in [0, 2] {
let mut moved = library.clone();
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Group("H".to_owned()), vec![SwatchKey::Group("H".to_owned())], to, false)));
let order: Vec<_> = moved.groups.iter().map(|g| g.name.as_str()).collect();
assert_eq!(order, ["", "H", "G"], "H dropped at row {to} lands below the ungrouped swatches, above G");
}
let mut moved = library.clone();
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Swatch("C".to_owned()), vec![SwatchKey::Swatch("C".to_owned())], 2, false)));
assert_eq!(moved.find("C"), Some(SwatchAt::new(0, 2)), "C joins the ungrouped swatches, after B");
}
/// Edits that move several items down or up give the order the browser's own reorder gives.
#[trial]
fn multi_item_moves_apply_as_the_reorder_does() {
+20 -2
View File
@@ -18,7 +18,7 @@ use craft_ui::patterns::presets::{
};
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Count, Env};
use egui::{Response, Ui};
use egui::{AsIdSalt, IdSalt, Response, Ui};
use super::library::{HostThumb, find_swatch, has, panel_source};
use super::menu::event_edits;
@@ -77,6 +77,8 @@ type PayloadAdder<'a> = Box<dyn for<'b> Fn(PresetBrowser<'b, SwatchKey>) -> Pres
/// [`search`](SwatchesPanel::search), [`row_icons`](SwatchesPanel::row_icons), [`takes_drop`](SwatchesPanel::takes_drop)
/// and [`row_items`](SwatchesPanel::row_items) pass through; the events they cause come out in
/// [`SwatchesPanelOutput::events`].
/// - [`document`](SwatchesPanel::document) keeps the browser's own state (an open rename field, the scroll position)
/// per document, so a host that shows one panel for several documents does not carry it from one to another.
/// - It fills the room it is given, and its browser scrolls the swatches: show it outside a body that scrolls.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
@@ -96,6 +98,7 @@ pub struct SwatchesPanel<'a> {
takes_drop: Option<DropMaker<'a>>,
payloads: Vec<PayloadAdder<'a>>,
row_items: Option<RowItemsFn<'a>>,
document: Option<IdSalt>,
}
/// What the body decided; `show` stores the state and reports the rest after the real run.
@@ -126,6 +129,7 @@ impl<'a> SwatchesPanel<'a> {
takes_drop: None,
payloads: Vec::new(),
row_items: None,
document: None,
}
}
@@ -216,6 +220,14 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll
/// position) for each document, so a rename left open in one document does not open on another document's
/// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in.
pub fn document(mut self, document: impl AsIdSalt) -> Self {
self.document = Some(IdSalt::new(document));
self
}
/// Draws the panel and returns the user's actions this pass.
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
let SwatchesPanel {
@@ -234,12 +246,15 @@ impl<'a> SwatchesPanel<'a> {
takes_drop,
payloads,
row_items,
document,
} = self;
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
let words = Env::of(ui).words::<SwatchesWords>();
let mut held_state = Held::new(state);
let ctx = ui.ctx().clone();
let browser_id = ui.scope_id();
// A document's browser has an id of its own; otherwise the browser takes the scope id of the `Ui` it is shown in.
let document_id = document.map(|document| ui.scope_id().with(document));
let browser_id = document_id.unwrap_or_else(|| ui.scope_id());
let icons: BTreeMap<&str, Vec<(IconSpec<'static>, String)>> = match &row_icons {
Some(icons) => {
groups.iter().flat_map(|g| g.entries.iter()).map(|e| (e.name.as_str(), icons(&SwatchKey::Swatch(e.name.clone())))).collect()
@@ -267,6 +282,9 @@ impl<'a> SwatchesPanel<'a> {
.select(select)
.reorder(PresetReorder::items_and_groups())
.selection(Bind::bound(&mut st.selection));
if let Some(id) = document_id {
browser = browser.browser_id(id);
}
if let Some(options) = footer_options {
browser = browser.footer(options);
}
+44
View File
@@ -202,6 +202,50 @@ impl WheelRig {
}
}
/// The names focus takes from the hue ring of a wheel shown in an arena (a split area's body) between two buttons,
/// one per Tab in `keys` (with its modifiers).
fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>> {
let mut fixture = Fixture::new(move |ui| {
let _ = craft_ui::buttons::Button::new("Before").show(ui);
let limits = |_: &usize| craft_ui::contract::SizeLimits::default();
let rules = craft_ui::docking::tree::FrameRules::new(&limits);
let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0));
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| {
let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui);
});
let _ = craft_ui::buttons::Button::new("After").show(ui);
});
fixture.room(vec2(420.0, 420.0));
fixture.settle();
let hue = fixture.by_label("Hue").expect("the ring");
fixture.access(AccessActionKind::Focus, &hue);
fixture.idle(2);
let focused = |fixture: &Fixture| {
let tree = fixture.tree();
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
};
assert_eq!(focused(&fixture).as_deref(), Some("Hue"), "{inner:?}: the ring takes focus");
keys.iter()
.map(|mods| {
fixture.key(Key::Tab, *mods);
fixture.idle(2);
focused(&fixture)
})
.collect()
}
/// In an arena, as in a docked panel, Tab from the hue ring lands on the saturation and brightness control, also when a
/// square shows it through its own folded picker, then goes on past the wheel; Shift-Tab comes back the same way.
#[trial]
fn in_an_arena_tab_from_the_ring_reaches_the_saturation_and_brightness_control() {
let (on, back) = (Modifiers::NONE, Modifiers::SHIFT);
for inner in [WheelInner::Triangle, WheelInner::Square] {
let walk = arena_tab_walk(inner, &[on, on, back, back]);
let expected = ["Saturation and brightness", "After", "Saturation and brightness", "Hue"].map(|name| Some(name.to_owned()));
assert_eq!(walk, expected, "{inner:?}");
}
}
/// A square wheel hands a press between the square and the ring to the square; its named markers speak their colour,
/// pick on a click, and a press held on one still drags the ring; Shift snaps a ring drag to 45 degrees, in both
/// variants.
+38 -2
View File
@@ -1,13 +1,49 @@
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, and its swatch size.
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, its swatch size and its ring.
use craft_color_ui::ui::{Paint, PaintChip, PaintChipSize};
use craft_color_ui::ui::{GradientPreview, Paint, PaintChip, PaintChipSize};
use craft_theme::Srgba;
use craft_ui::buttons::PopupMark;
use craft_ui::contract::{Bind, Role, Show as _};
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Shape};
use std::cell::Cell;
use std::rc::Rc;
/// Every shape of the frame, groups opened.
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
}
/// A ring chip wider than it is high keeps an open middle: the hole inside the band is at least a third of the chip's
/// height, and the band is as thick at the sides as at the top and bottom. Checked for a solid paint, drawn as a band
/// of the colour, and for a gradient, whose middle is covered by the surface the chip sits on.
#[trial]
fn a_wide_ring_chip_keeps_an_open_middle() {
let gradient = GradientPreview::new(vec![(0.0, Srgba::rgb(0.2, 0.4, 0.8)), (1.0, Srgba::WHITE)]);
for paint in [Paint::Solid(Srgba::rgb(0.2, 0.4, 0.8)), Paint::Gradient(gradient)] {
let mut fixture = Fixture::new(move |ui| {
let mut paint = paint.clone();
let _ = PaintChip::new("Stroke", Bind::bound(&mut paint), Srgba::BLACK).ring(true).show(ui);
});
fixture.settle();
let well = fixture.by_role(Role::COLOR_WELL).first().copied().expect("the chip is a colour well").rect;
assert!(well.width() > well.height(), "the chip is wider than it is high");
// The hole is the smallest rect drawn round the well's centre.
let hole = flat(fixture.frame_shapes())
.into_iter()
.filter_map(|shape| match shape {
Shape::Rect(rect) => Some(rect.rect),
_ => None,
})
.filter(|rect: &Rect| rect.center().distance(well.center()) < 0.5 && rect.width() < well.width() - 2.0)
.min_by(|a, b| a.area().total_cmp(&b.area()))
.expect("a hole inside the band");
assert!(hole.height() >= well.height() / 3.0, "the hole is {:?} in a {:?} well", hole.size(), well.size());
let (side, top) = (hole.left() - well.left(), hole.top() - well.top());
assert!((side - top).abs() < 0.5, "the band is {side} at the sides and {top} at the top");
}
}
/// A click on the menu mark, past the well, opens the chip's popover, as a click on the well does.
#[trial]
fn a_click_on_the_menu_mark_opens_the_popover() {
+125 -3
View File
@@ -7,15 +7,17 @@ use std::rc::Rc;
use craft_behavior::{EditEvent, Mixed, Selection};
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
use craft_color_ui::ui::{
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey,
SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows,
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
SwatchesWords, swatch_rows,
};
use craft_host::target::Os;
use craft_theme::{ColorModel as _, HsbModel, Srgba};
use craft_ui::choice::SwatchTable;
use craft_ui::contract::Role;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::{Label, Scale};
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::testing::focus::AccessActionKind;
@@ -254,6 +256,36 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
}
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
#[trial]
fn a_fill_stroke_spectrum_keeps_its_end_boxes_square_in_a_content_sized_host() {
for (room, content_sized) in [(COLOR_ROOM, true), (Vec2::new(280.0, 96.0), false)] {
let mut fixture = Fixture::new(move |ui| {
let mut state = ColorPanelState::default();
let show = |ui: &mut egui::Ui, state: &mut ColorPanelState| {
let _ = ColorPanel::new(Bind::bound(state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke).show(ui);
};
if content_sized {
let _ = Stack::new().show(ui, |ui, _| show(ui, &mut state));
} else {
show(ui, &mut state);
}
});
fixture.room(room).settle();
let bar = fixture.by_label("Color Ramp").expect("the spectrum").rect;
let ends: Vec<_> = fixture
.by_role(Role::BUTTON)
.into_iter()
.filter(|button| button.rect.left() >= bar.right() - 0.5 && button.rect.y_range().intersects(bar.y_range()))
.collect();
assert_eq!(ends.len(), 2, "{room:?}: the white and black boxes beside the bar ({bar:?})");
for end in ends {
assert!(end.rect.height() >= end.rect.width() - 0.5, "{room:?}: an end box at least square ({:?} beside {bar:?})", end.rect);
}
}
}
const SWATCHES: [(&str, [f32; 3]); 6] = [
("Red", [0.90, 0.28, 0.30]),
("Orange", [0.97, 0.42, 0.08]),
@@ -408,6 +440,28 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
}
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
/// it; a host that gives no recent colors gets no row.
#[trial]
fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() {
let caption = |recent: Option<&'static [Srgba]>| {
let mut fixture = Fixture::new(move |ui| {
let mut state = ColorPanelState::default();
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
let _ = match recent {
Some(colors) => panel.recent(colors),
None => panel,
}
.show(ui);
});
fixture.room(COLOR_ROOM).settle();
fixture.texts().iter().any(|run| run.text == "Recent Colors")
};
assert!(caption(Some(&[])), "an empty list shows the row's caption");
assert!(caption(Some(&RECENT)), "a list with a color shows it");
assert!(!caption(None), "a host with no recent colors shows no row");
}
/// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first;
/// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`.
#[trial]
@@ -541,6 +595,30 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
}
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
#[trial]
fn swatches_outside_every_group_show_without_a_header() {
let entry = |name: &str, rgb: [f32; 3]| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(rgb));
let groups = vec![
SwatchGroup { name: String::new(), entries: vec![entry("Red", [1.0, 0.0, 0.0]), entry("Blue", [0.0, 0.0, 1.0])] },
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Green", [0.0, 1.0, 0.0])] },
];
let (fixture, _) = swatches_rig(groups, SwatchesState::default());
let tree = fixture.tree();
let unnamed: Vec<_> = tree
.keys()
.into_iter()
.filter(|&key| matches!(tree.role_of(key), Some(Role::HEADING | Role::BUTTON)))
.filter(|&key| tree.name_of(key).is_none_or(|name| name.is_empty() || name.starts_with(',')))
.map(|key| (tree.role_of(key), tree.name_of(key), tree.bounds_of(key)))
.collect();
assert!(unnamed.is_empty(), "every heading and button is named, starting with a label: {unnamed:?}");
assert!(fixture.by_label("Red, #ff0000").is_some(), "the ungrouped swatches show");
let headings: Vec<_> = tree.with_role(Role::HEADING).into_iter().filter_map(|key| tree.name_of(key)).collect();
assert!(headings.iter().any(|name| name.starts_with("Other")), "a named group keeps its header: {headings:?}");
}
/// Tb-8 (5): a click uses any swatch, as production applied every one: a colour swatch reports its colour, and a
/// gradient, pattern or None swatch reports where it is with no colour, for the host to apply its paint. The panel
/// reported only colour swatches.
@@ -628,6 +706,34 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
}
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
/// swatch of the same name opens no field, and Enter there renames nothing.
#[trial]
fn a_rename_left_open_stays_with_its_document() {
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
let groups = vec![SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] }];
let document = Rc::new(Cell::new(1_u32));
let edits = Rc::new(RefCell::new(Vec::new()));
let (shown, seen) = (Rc::clone(&document), Rc::clone(&edits));
let mut state = SwatchesState::default();
let mut fixture = Fixture::new(move |ui| {
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED).document(shown.get()).show(ui);
seen.borrow_mut().extend(out.edits);
});
fixture.room(Vec2::new(320.0, 400.0)).settle();
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
fixture.click(&red).key(Key::F2, Modifiers::NONE).type_text("X").settle();
let typed = |fixture: &Fixture, text: &str| {
let tree = fixture.tree();
tree.keys().into_iter().any(|key| tree.value_of(key) == Some(text))
};
assert!(typed(&fixture, "X"), "the rename field is open in the first document");
document.set(2);
fixture.settle();
fixture.type_text("Y").key(Key::Enter, Modifiers::NONE).settle();
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
}
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
}
@@ -768,3 +874,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() {
fixture.click(&marker).idle(1);
assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker");
}
/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its
/// right edge.
#[trial]
fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
let mut fixture = Fixture::new(|ui| {
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
});
fixture.room(COLOR_ROOM).settle();
let grid = fixture.by_label("Variations").expect("the variations grid").rect;
let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted"));
let (shades, tints) = (run("Shades"), run("Tints"));
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
}
+4
View File
@@ -34,6 +34,10 @@ craft-flags = { workspace = true, optional = true }
dirs = { version = "7", optional = true }
log = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies]
# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours).
craft-platform = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
tempfile = "3"
+268 -119
View File
@@ -101,7 +101,7 @@ impl App {
/// Record `port` as the running app's, readable only by the user like the token files.
pub fn write_current_port(&self, port: u16) -> Result<PathBuf> {
let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;
self.write_token_file(&path, &port.to_string())?;
self.write_private(&path, &port.to_string(), true)?;
Ok(path)
}
@@ -141,16 +141,27 @@ impl App {
}
/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`
/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one
/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file
/// is removed and no token is written. A file left by an earlier launch is replaced. The process
/// file beside it ([`pid_path`]) records this process, best effort.
/// and the file `0600` on Unix; on Windows the file is created with an access list of the user
/// and SYSTEM only and the token is written through the handle that created it
/// (`create_for_user`), so the file never has its folder's access list. A file left by an
/// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process,
/// best effort.
pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> {
self.write_private(path, token, false)
}
/// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while
/// this one was being created is replaced (the discovery file, which names the latest launch);
/// otherwise this write fails and that launch's token stays.
fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> {
#[cfg(windows)]
let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some());
let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace);
#[cfg(not(windows))]
let restrict = |_: &Path| Ok(());
write_token_file_with(path, token, restrict)
let create = {
let _ = replace;
create_new_file
};
write_token_file_with(path, token, create)
}
}
@@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows).
fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
/// [`App::write_token_file`], with `create` making the new file with its contents, readable only
/// by the user.
fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> {
let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;
std::fs::create_dir_all(dir)?;
let _ = std::fs::remove_file(path);
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
opts.mode(0o600);
}
let opened = opts.open(path)?;
// On a refusal the file goes with the closure, so it is closed before it is removed.
let mut f = match restrict(path).map(|()| opened) {
Ok(f) => f,
Err(e) => {
let _ = std::fs::remove_file(path);
return Err(e);
}
};
f.write_all(token.as_bytes())?;
f.write_all(b"\n")?;
f.sync_all()?;
create(path, format!("{token}\n").as_bytes())?;
let pid = std::process::id();
let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));
let _ = std::fs::write(pid_path(path), line);
@@ -369,74 +367,148 @@ fn held_by_another(path: &Path, token: &str) -> bool {
read_token(path).is_some_and(|held| !tokens_match(&held, token.trim()))
}
/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process
/// is left suspended (security software holding it), and waiting on it without a limit froze
/// the app.
#[cfg(windows)]
const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
/// How a run of `icacls` ended.
#[cfg(any(windows, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum IcaclsEnd {
Succeeded,
Failed,
/// It didn't finish within [`ICACLS_LIMIT`] and was ended.
TimedOut,
/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a
/// file created this way has its folder's access list; the token file there is made by
/// `create_for_user`.
fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> {
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut f = opts.open(path)?;
f.write_all(contents)?;
f.sync_all()
}
/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is
/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder,
/// the user's own local app data, which other users can't read by default; nothing is known about
/// the permissions of any other folder.
/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell;
/// on some computers a new process is left suspended (security software holding it), and waiting
/// on it without a limit froze the app.
#[cfg(windows)]
const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
/// Windows: create `path` with the current user as owner and an access list of that user and
/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written
/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`.
/// Another account never gets a moment in which the file has its folder's access list and could be
/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names;
/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and
/// what `replace` changes.
#[cfg(windows)]
fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> {
use craft_platform::owner_only;
/// How many creates that were not waited for are still running.
static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c));
create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0
}
/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names
/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that
/// folder's permissions; in the default folder, the user's own local app data, which other users
/// can't read by default, `path` created with that folder's access list ([`create_new_file`]).
#[cfg(any(windows, test))]
fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> {
match end {
IcaclsEnd::Succeeded => Ok(()),
IcaclsEnd::TimedOut if !custom_folder => Ok(()),
IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))),
IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))),
fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> {
if custom_folder {
Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display())))
} else {
create_new_file(path, contents)
}
}
/// Windows: drop inherited entries and grant only the current user full access. An `icacls`
/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means.
#[cfg(windows)]
fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> {
use std::os::windows::process::CommandExt;
let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?;
let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty());
let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}"));
let child = std::process::Command::new("icacls")
.arg(path)
.args(["/inheritance:r", "/grant:r", &format!("{who}:F")])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.creation_flags(0x0800_0000)
.spawn()?;
let end = match wait_within(child, ICACLS_LIMIT)? {
Some(status) if status.success() => IcaclsEnd::Succeeded,
Some(_) => IcaclsEnd::Failed,
None => IcaclsEnd::TimedOut,
/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its
/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path`
/// (`.<name>.<process id>.<count>.tmp`), and the file takes the name `path` only once `private`
/// has finished, so `path` never holds a file that is still being written: with `replace` by a
/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`],
/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool
/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result.
/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its
/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any
/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that
/// leaves new processes suspended holds at most the threads that were started together. The
/// thread's handle is returned for tests.
#[cfg(any(windows, test))]
fn create_within(
path: &Path,
contents: &[u8],
custom_folder: bool,
replace: bool,
limit: std::time::Duration,
stuck: &'static std::sync::atomic::AtomicUsize,
private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static,
) -> (Result<()>, Option<std::thread::JoinHandle<()>>) {
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{RecvTimeoutError, channel};
use std::sync::{Arc, Mutex, PoisonError};
/// Numbers the thread's files within this process.
static COUNT: AtomicU64 = AtomicU64::new(0);
if stuck.load(Ordering::Acquire) > 0 {
return (not_waited_for(path, contents, custom_folder), None);
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
let (sender, receiver) = channel();
// Set under the lock when the caller stops waiting; the thread reads it under the same lock
// before it reports, so its result is either received or its file is removed.
let abandoned = Arc::new(Mutex::new(false));
let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned));
let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || {
let made = private(&own_file, &owned_contents);
let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner);
if *abandoned {
let _ = std::fs::remove_file(&own_file);
stuck.fetch_sub(1, Ordering::AcqRel);
} else {
let _ = sender.send(made);
}
});
let handle = match spawned {
Ok(handle) => handle,
Err(e) => return (Err(e), None),
};
restriction_result(end, custom_folder, path)
let made = match receiver.recv_timeout(limit) {
Ok(made) => made,
Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))),
Err(RecvTimeoutError::Timeout) => {
let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner);
match receiver.try_recv() {
Ok(made) => made,
Err(_) => {
*abandoned = true;
stuck.fetch_add(1, Ordering::AcqRel);
drop(abandoned);
return (not_waited_for(path, contents, custom_folder), Some(handle));
}
}
}
};
let placed = match made {
// `owner_only` ended a tool that ran out of its own time: the same as not waiting.
Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder),
made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }),
};
let _ = std::fs::remove_file(&staged);
(placed, Some(handle))
}
/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it
/// hasn't finished by then.
/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch
/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a
/// `create_new` there would, instead of replacing the first one's token. The new name is a hard
/// link. On a volume without hard links the file is renamed once `path` is found free; there a
/// launch that puts its file at `path` between that check and the rename has it replaced, as std
/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the
/// caller to remove.
#[cfg(any(windows, test))]
fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result<Option<std::process::ExitStatus>> {
let start = std::time::Instant::now();
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
fn place_new(staged: &Path, path: &Path) -> Result<()> {
match std::fs::hard_link(staged, path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => {
Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display())))
}
if start.elapsed() >= limit {
// Not waited for afterwards: a suspended process may not end at once.
let _ = child.kill();
return Ok(None);
}
std::thread::sleep(std::time::Duration::from_millis(20));
Err(_) => std::fs::rename(staged, path),
}
}
@@ -456,50 +528,127 @@ mod tests {
/// An app with no data folder and no environment, whose times read `t<seconds>`.
const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 };
/// #6145: a child that doesn't finish in time is given up on, not waited for forever.
#[cfg(unix)]
/// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder
/// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created
/// anyway and holds the token. Either way the file the late create makes is removed when it
/// finishes and never takes the token file's name, even when a later write has put a file
/// there. While it runs, the next create starts no thread of its own. A create that finishes in
/// time puts its file in place unless a file already has the name, and one that fails leaves
/// nothing. A create that fails as timed out by itself is taken as one not waited for.
#[test]
fn a_slow_child_is_waited_for_only_so_long() {
use std::time::{Duration, Instant};
let start = Instant::now();
let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap();
assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none());
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
let quick = std::process::Command::new("true").spawn().unwrap();
assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success()));
let failing = std::process::Command::new("false").spawn().unwrap();
assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success()));
}
/// #6145's freeze fix stays in the default folder, the user's own; a folder picked with
/// the app's `CONTROL_DIR` gets no token unless the file was really restricted.
#[test]
fn only_the_default_folder_accepts_an_icacls_that_timed_out() {
let path = Path::new("control/7878.token");
for custom in [false, true] {
assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok());
assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err());
fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::channel;
use std::time::Duration;
static STUCK: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let names = || {
let mut names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
};
for custom in [true, false] {
let path = dir.join("7878.port");
let (go, wait) = channel::<()>();
let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| {
wait.recv().map_err(Error::other)?;
create_new_file(p, c)
});
assert_eq!(STUCK.load(Ordering::Acquire), 1);
if custom {
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
assert!(!path.exists());
let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") };
let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused);
assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut);
assert!(none.is_none());
// A later write of the same contents, as a retry of the same port would make.
create_new_file(&path, b"7878\n").unwrap();
} else {
made.unwrap();
}
go.send(()).unwrap();
handle.unwrap().join().unwrap();
assert_eq!(STUCK.load(Ordering::Acquire), 0);
assert_eq!(names(), ["7878.port"]);
assert_eq!(read_token(&path).as_deref(), Some("7878"));
std::fs::remove_file(&path).unwrap();
}
assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok());
let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err();
assert_eq!(e.kind(), ErrorKind::TimedOut);
assert!(e.to_string().contains("7878.token"), "{e}");
let path = dir.join("quick.token");
let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
made.unwrap();
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("quick"));
// Another launch's file at the name is kept, as `create_new` keeps it.
let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists);
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("quick"));
// With `replace` (the discovery file) the later launch's file takes the name.
let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file);
made.unwrap();
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("later"));
let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) };
let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused);
assert!(made.is_err());
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
// A create whose tool was ended after its own limit, within this one, is taken as one
// that was not waited for.
let ended =
|_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) };
let path = dir.join("ended.token");
let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended);
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
handle.unwrap().join().unwrap();
assert_eq!(names(), ["quick.token"]);
let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended);
made.unwrap();
handle.unwrap().join().unwrap();
assert_eq!(names(), ["ended.token", "quick.token"]);
assert_eq!(read_token(&path).as_deref(), Some("ended"));
assert_eq!(STUCK.load(Ordering::Acquire), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// A file that couldn't be restricted is removed, empty and with no process file beside it, and
/// the error goes to the caller. A restricted one gets its token.
/// A file that couldn't be created leaves no process file beside it, and the error goes to the
/// caller. A created one gets the token and a newline.
#[test]
fn a_token_file_that_could_not_be_restricted_is_removed() {
let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id()));
fn a_token_file_that_could_not_be_created_leaves_nothing() {
let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id()));
let path = dir.join("7879.token");
let e = write_token_file_with(&path, "secret-token", |p| {
assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in");
restriction_result(IcaclsEnd::TimedOut, true, p)
})
.unwrap_err();
let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err();
assert_eq!(e.kind(), ErrorKind::TimedOut);
assert!(!path.exists() && !pid_path(&path).exists());
write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap();
write_token_file_with(&path, "secret-token", create_new_file).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n");
assert!(pid_path(&path).exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// On Windows the token file is its user's alone from the moment it exists: in a folder that
/// lets Users read what is created in it, the file has no entry for Users and no other
/// account's access.
#[cfg(windows)]
#[test]
fn the_token_file_is_private_from_the_start_on_windows() {
use craft_platform::owner_only;
let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let path = dir.join("7880.token");
TEST.write_token_file(&path, "secret-token").unwrap();
let sddl = owner_only::sddl_of(&path).unwrap();
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
assert_eq!(read_token(&path).as_deref(), Some("secret-token"));
let _ = std::fs::remove_dir_all(&dir);
}
+4
View File
@@ -229,6 +229,7 @@ craft-ppt-binary = { workspace = true, optional = true }
craft-sqlite = { workspace = true, optional = true }
craft-audio-dsp = { workspace = true, optional = true }
craft-sbs = { workspace = true, optional = true }
craft-shared-vec = { workspace = true, optional = true }
[features]
ui = [
@@ -804,6 +805,9 @@ settings-testing = ["settings", "craft-settings/testing"]
sf2 = ["dep:craft-sf2"]
sf2-test-support = ["sf2", "craft-sf2/test-support"]
shared-vec = ["dep:craft-shared-vec"]
shared-vec-serde = ["shared-vec", "craft-shared-vec/serde"]
sheet = ["dep:craft-sheet"]
shx = ["dep:craft-shx"]
+2
View File
@@ -333,6 +333,8 @@ pub use craft_scraft_format as scraft_format;
pub use craft_settings as settings;
#[cfg(feature = "sf2")]
pub use craft_sf2 as sf2;
#[cfg(feature = "shared-vec")]
pub use craft_shared_vec as shared_vec;
#[cfg(feature = "sheet")]
pub use craft_sheet as sheet;
#[cfg(feature = "shx")]
+1 -1
View File
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
/// Crates the facade leaves out, by directory, with the reason. Everything else under `crates/` is a member.
pub const NOT_IN_FACADE: &[(&str, &str)] = &[
("appkit", "the `unsafe` AppKit observers behind a safe API, used by craft-window"),
("appkit", "the `unsafe` AppKit calls behind a safe API, used by craft-window and craft-dialogs"),
("design-lint", "a lint template and checker for apps' clippy.toml, run from xtask"),
("feature-root", "a build tool: the dependency set tools/cl resolves every local build's features with; never built"),
("fonts-build", "a build-script helper; apps call it from build.rs"),
+5 -4
View File
@@ -31,13 +31,14 @@ serde_json = { workspace = true, optional = true }
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] }
# The file-dialog probe asks the session bus whether the desktop portal offers a file chooser.
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`). rfd and winit already
# use these.
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`), and the Save sheet with a
# Format menu (`beginSheetModalForWindow:completionHandler:`). rfd and winit already use these.
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
craft-appkit = { workspace = true }
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSApplication", "NSOpenPanel", "NSPanel", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSString", "NSURL"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSAccessibilityProtocols", "NSApplication", "NSButton", "NSControl", "NSOpenPanel", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSText", "NSTextField", "NSView", "NSWindow", "objc2-core-foundation"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSString", "NSURL", "objc2-core-foundation"] }
# The Linux and BSD Save panel asks the desktop portal itself, which reports the file type picked.
# The versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the
+8 -2
View File
@@ -44,7 +44,7 @@ pub type Override = Box<dyn FnMut(&Request) -> Answer>;
pub enum Kind { Open { multiple: bool }, Folder, Save }
pub struct FileDialog { pub kind: Kind, pub title: Option<String>, pub filters: Vec<Filter>,
pub directory: Option<PathBuf>, pub file_name: Option<String> }
pub directory: Option<PathBuf>, pub file_name: Option<String>, pub format_label: Option<String> }
pub struct Filter { pub name: String, pub extensions: Vec<String> }
pub struct Message { pub level: MessageLevel, pub title: String, pub description: String,
pub buttons: MessageButtons }
@@ -66,7 +66,7 @@ impl<T> Dialogs<T> {
```
`FileDialog` has builders: `FileDialog::open().title("Place").filter("Images", &["png", "jpg"])`,
and `open_many`, `folder`, `save`, `directory`, `file_name`.
and `open_many`, `folder`, `save`, `directory`, `file_name`, `format_label`.
In an eframe app:
@@ -127,6 +127,12 @@ they start only with a parent in a running app, and answer `Unavailable` otherwi
before the event loop starts or after it ends (startup and crash messages) stay blocking `rfd`
calls in the app.
A Save that offers two or more file types is a sheet the crate makes itself, with a Format menu
that lists each type by name, the suggested name's type chosen. Choosing a type changes the
extension in the name field, and the answer is `Saved` with the chosen type's index in `filter`.
The menu's label is `FileDialog::format_label`, set from `FilePanels::set_format_label` (English
"Format:" when unset). A Save with one type is rfd's sheet, which has no menu.
## Follow-ups
- Linux portal Save (`org.freedesktop.portal.FileChooser.SaveFile`), so the file type the user
+115
View File
@@ -0,0 +1,115 @@
//! The Format menu of a macOS Save panel with two or more file types: which types it lists, which one is chosen
//! when the panel opens, the name a choice gives the file and the extensions the panel then allows. Plain rules on
//! names and filters, so they are tested on every platform; `macos.rs` shows the menu.
use std::path::Path;
use crate::Filter;
use crate::service::normal;
/// The indices into `filters` of the file types the menu lists, in order: types with an extension other than `*`.
/// Empty when fewer than two remain: the panel then has no menu.
pub(crate) fn entries(filters: &[Filter]) -> Vec<usize> {
let listed: Vec<usize> = filters
.iter()
.enumerate()
.filter(|(_, f)| f.extensions.iter().any(|e| !normal(e).is_empty()) && !f.extensions.iter().any(|e| normal(e) == "*"))
.map(|(at, _)| at)
.collect();
if listed.len() < 2 { Vec::new() } else { listed }
}
/// The menu's item titles for `entries`, one per entry and all different: a pop-up menu keeps one item per title, so
/// a name that repeats gets its extensions after it (`Document (docx)`), and a title that still matches an earlier
/// title or another type's name gets a number after it.
pub(crate) fn titles(filters: &[Filter], entries: &[usize]) -> Vec<String> {
let names: Vec<&str> = entries.iter().map(|&at| filters.get(at).map_or("", |f| f.name.as_str())).collect();
let mut out: Vec<String> = Vec::new();
for (&at, name) in entries.iter().zip(&names) {
let mut base = (*name).to_owned();
if names.iter().filter(|n| *n == name).count() > 1 {
let extensions: Vec<String> = filters.get(at).map(|f| f.extensions.iter().map(|e| normal(e)).collect()).unwrap_or_default();
base = format!("{name} ({})", extensions.join(", "));
}
let taken = |title: &str| out.iter().any(|t| t == title) || (title != *name && names.contains(&title));
let mut title = base.clone();
let mut number = 2;
while taken(&title) {
title = format!("{base} {number}");
number += 1;
}
out.push(title);
}
out
}
/// The file type a Save answer reports, as an index into `filters`: the one chosen in the menu (menu position
/// `chosen`), unless the name the panel returned ends in an extension that only another listed type has: the user
/// typed it, and the file is saved in that type. `kept` is the name the field still showed when the last choice could
/// not rename it. A returned name equal to it that still has the extension of the name the panel opened with
/// (`opened_with`) keeps the chosen type: the save flow gives a name with the opened extension the chosen type's
/// extension (`with_chosen_type`). Any other extension stays on the name, so the type reported is the one the name has.
pub(crate) fn answered_type(
returned: &str,
kept: Option<&str>,
opened_with: Option<&str>,
filters: &[Filter],
entries: &[usize],
chosen: usize,
) -> Option<usize> {
let chosen = entries.get(chosen).copied()?;
let Some(ext) = extension(returned) else { return Some(chosen) };
let kept_opened = kept == Some(returned) && opened_with.and_then(extension).as_ref() == Some(&ext);
if filters.get(chosen).is_some_and(|f| lists(f, &ext)) || kept_opened {
return Some(chosen);
}
Some(entries.iter().copied().find(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(chosen))
}
/// The menu position chosen when the panel opens: the type whose extensions include `name`'s, else the first.
pub(crate) fn initial(name: &str, filters: &[Filter], entries: &[usize]) -> usize {
let Some(ext) = extension(name) else { return 0 };
entries.iter().position(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(0)
}
/// The name the panel shows once `chosen` is picked: an extension `chosen` lists stays; one that another of
/// `filters` lists becomes `chosen`'s first; any other is part of the name (`art.v2`), and `chosen`'s first extension
/// is added after it. An empty name stays empty.
pub(crate) fn renamed(name: &str, chosen: &Filter, filters: &[Filter]) -> String {
let Some(first) = chosen.extensions.iter().map(|e| normal(e)).find(|e| !e.is_empty()) else { return name.to_owned() };
if name.is_empty() {
return String::new();
}
match extension(name) {
Some(ext) if lists(chosen, &ext) => name.to_owned(),
Some(ext) if filters.iter().any(|f| lists(f, &ext)) => Path::new(name).with_extension(first).to_string_lossy().into_owned(),
_ => format!("{name}.{first}"),
}
}
/// The extensions the panel allows with menu position `selected` chosen: that type's first, so that AppKit adds it
/// to a name typed without one, then the other listed types', so that a name typed with one of theirs is kept.
pub(crate) fn allowed(filters: &[Filter], entries: &[usize], selected: usize) -> Vec<String> {
let chosen = entries.get(selected).copied();
let order = chosen.into_iter().chain(entries.iter().copied().filter(|&at| Some(at) != chosen));
let mut out: Vec<String> = Vec::new();
for ext in order.filter_map(|at| filters.get(at)).flat_map(|f| f.extensions.iter().map(|e| normal(e))) {
if !ext.is_empty() && !out.contains(&ext) {
out.push(ext);
}
}
out
}
/// `name`'s extension as compared, if it has one.
fn extension(name: &str) -> Option<String> {
Path::new(name).extension().and_then(|e| e.to_str()).map(normal)
}
/// Whether `filter` lists `ext` (already [`normal`]).
fn lists(filter: &Filter, ext: &str) -> bool {
filter.extensions.iter().any(|e| normal(e) == ext)
}
#[cfg(test)]
pub(crate) mod tests;
+110
View File
@@ -0,0 +1,110 @@
use super::*;
use craft_ui::testing::trial;
fn filters() -> Vec<Filter> {
vec![Filter::new("Document", &["doc"]), Filter::new("Drawing", &["ai"]), Filter::new("Picture", &["jpg", "jpeg"])]
}
/// The menu lists the types with an extension; "every file" types and ones without an extension stay out, and a
/// panel left with one type gets no menu.
#[trial]
fn the_menu_lists_types_with_extensions_and_needs_two() {
assert_eq!(entries(&filters()), [0, 1, 2]);
let mixed = [Filter::new("Document", &["doc"]), Filter::new("All files", &["*"]), Filter::new("Any", &[]), Filter::new("Drawing", &[".ai"])];
assert_eq!(entries(&mixed), [0, 3], "the dot is not part of the extension");
assert!(entries(&[Filter::new("Document", &["doc"]), Filter::new("All files", &["*"])]).is_empty());
assert!(entries(&[]).is_empty());
}
/// Two types with one name both stay in the menu, under different titles; other titles are the names.
#[trial]
fn types_that_share_a_name_get_different_titles() {
let twice = [Filter::new("Document", &["doc"]), Filter::new("Document", &["docx"]), Filter::new("Drawing", &["ai"])];
let listed = entries(&twice);
assert_eq!(listed, [0, 1, 2]);
let shown = titles(&twice, &listed);
assert_eq!(shown.len(), listed.len());
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
assert_eq!(shown[2], "Drawing");
for set in [
vec![Filter::new("Document", &["doc"]), Filter::new("Document", &["doc"])],
vec![Filter::new("X (x) 2", &["a"]), Filter::new("X", &["x"]), Filter::new("X", &["x"])],
vec![Filter::new("X", &["x"]), Filter::new("X", &["x"]), Filter::new("X (x) 2", &["a"]), Filter::new("X (x)", &["b"])],
] {
let shown = titles(&set, &entries(&set));
assert_eq!(shown.len(), set.len());
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
}
}
/// The answer reports the chosen type, unless the user typed another listed type's extension; a name the panel kept
/// when a choice could not rename it keeps the chosen type.
#[trial]
fn a_typed_extension_of_another_type_is_the_type_saved() {
let all = filters();
let listed = entries(&all);
let (kept, opened) = (Some("Untitled-1.doc"), Some("Untitled-1.doc"));
let answer = |returned, kept| answered_type(returned, kept, opened, &all, &listed, 1);
assert_eq!(answer("Untitled-1.ai", None), Some(1));
assert_eq!(answer("Untitled-1.doc", kept), Some(1), "the panel kept the opened name");
assert_eq!(answer("Other.doc", kept), Some(0), "the user typed a new name after that");
assert_eq!(answer("Untitled-1.doc", None), Some(0), "the user typed the first type's extension back");
assert_eq!(answer("photo.JPEG", kept), Some(2), "the user typed another type's extension");
assert_eq!(answer("Other.doc", Some("Other.doc")), Some(1), "a kept name with the opened extension");
assert_eq!(answer("Other.jpg", Some("Other.jpg")), Some(2), "a kept name with another type's extension keeps that type");
assert_eq!(answer("notes.v2", None), Some(1));
assert_eq!(answer("art", None), Some(1));
assert_eq!(answered_type("art.ai", None, opened, &all, &listed, 9), None, "a position the menu doesn't have");
}
#[trial]
fn the_suggested_name_chooses_its_type_and_any_other_the_first() {
let all = filters();
let listed = entries(&all);
for (name, at) in [("Untitled-1.doc", 0), ("art.AI", 1), ("photo.jpeg", 2), ("Untitled-1", 0), ("notes.v2", 0), ("", 0)] {
assert_eq!(initial(name, &all, &listed), at, "{name}");
}
}
/// Choosing a type replaces the extension of another listed type, keeps one of its own and adds its own after any
/// other dot in the name.
#[trial]
fn choosing_a_type_gives_the_name_its_extension() {
let all = filters();
let drawing = &all[1];
for (name, expected) in [
("Untitled-1.doc", "Untitled-1.ai"),
("Plan 1.DOC", "Plan 1.ai"),
("photo.jpeg", "photo.ai"),
("art.ai", "art.ai"),
("art.AI", "art.AI"),
("art", "art.ai"),
("art.v2", "art.v2.ai"),
("", ""),
] {
assert_eq!(renamed(name, drawing, &all), expected, "{name}");
}
assert_eq!(renamed("photo.jpeg", &all[2], &all), "photo.jpeg", "a second extension of the chosen type stays");
}
/// A sequence of choices (A to B to C) ends with C's extension, and back to A gives A's.
#[trial]
fn each_choice_follows_the_previous_one() {
let all = filters();
let mut name = "Untitled-1.doc".to_owned();
for (at, ext) in [(1, "ai"), (2, "jpg"), (0, "doc")] {
name = renamed(&name, &all[at], &all);
assert_eq!(Path::new(&name).extension().and_then(|e| e.to_str()), Some(ext));
assert_eq!(Path::new(&name).file_stem().and_then(|e| e.to_str()), Some("Untitled-1"));
}
}
/// The chosen type's extension comes first, so AppKit adds it to a bare name; the others stay allowed.
#[trial]
fn the_chosen_type_is_allowed_first() {
let all = filters();
let listed = entries(&all);
assert_eq!(allowed(&all, &listed, 0), ["doc", "ai", "jpg", "jpeg"]);
assert_eq!(allowed(&all, &listed, 1), ["ai", "doc", "jpg", "jpeg"]);
assert_eq!(allowed(&all, &listed, 2), ["jpg", "jpeg", "doc", "ai"]);
}
+16 -2
View File
@@ -20,6 +20,8 @@
#![warn(missing_docs)]
mod filter;
#[cfg(any(target_os = "macos", test))]
mod format_menu;
mod native;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
pub(crate) mod portal;
@@ -92,12 +94,18 @@ pub struct FileDialog {
pub directory: Option<PathBuf>,
/// The file name a Save dialog suggests.
pub file_name: Option<String>,
/// The label of the file type menu a macOS Save panel with two or more file types shows; `None` shows
/// [`FORMAT_LABEL`]. Other platforms' dialogs label their menu themselves.
pub format_label: Option<String>,
}
/// The English label of the macOS Save panel's file type menu.
pub const FORMAT_LABEL: &str = "Format:";
impl FileDialog {
/// A dialog of `kind` with nothing else set.
pub fn new(kind: Kind) -> Self {
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None }
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None, format_label: None }
}
/// Choose one existing file.
@@ -143,6 +151,12 @@ impl FileDialog {
self.file_name = Some(file_name.into());
self
}
/// Sets the label of the macOS Save panel's file type menu, in the app's language.
pub fn format_label(mut self, label: impl Into<String>) -> Self {
self.format_label = Some(label.into());
self
}
}
/// The icon a message box shows.
@@ -223,7 +237,7 @@ pub enum Answer {
/// The chosen files or folder.
Paths(Vec<PathBuf>),
/// A Save panel's answer: the name as typed and the file type picked, when the panel reports it (the portal's
/// current filter; rfd reports `None`).
/// current filter, or the macOS panel's Format menu; rfd reports `None`).
Saved {
/// The name as typed.
path: PathBuf,
+142 -8
View File
@@ -6,22 +6,29 @@
//! rfd can't show this panel: its async dialogs always begin a sheet, on the main or first window
//! when no parent is given (rfd 0.17.2 `backend/macos/modal_future.rs:71-102`).
//!
//! Save and message boxes are sheets on the parent window through rfd, as native apps show them.
//! rfd falls back to the blocking `runModal` when the app isn't running or has no window
//! (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
//! Save and message boxes are sheets on the parent window, as native apps show them. A Save that
//! offers two or more file types is a sheet made here ([`show_save_sheet`]), with a Format menu:
//! rfd's Save panel lists the extensions of every type and has no menu to choose one
//! (rfd 0.17.2 `backend/macos/file_dialog/panel_ffi.rs:107-120`). Other Saves and message boxes
//! are rfd's sheets. rfd falls back to the blocking `runModal` when the app isn't running or has no
//! window (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
//! running app.
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::ffi::c_void;
use std::rc::Rc;
use block2::RcBlock;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSView};
use objc2_foundation::{NSArray, NSString, NSURL};
use objc2::MainThreadOnly;
use objc2::rc::{Retained, Weak};
use objc2_app_kit::{
NSAccessibility, NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSPopUpButton, NSSavePanel, NSTextField, NSView, NSWindow,
};
use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use crate::{Answer, FileDialog, Kind, Reply};
use crate::{Answer, FORMAT_LABEL, FileDialog, Filter, Kind, Reply, format_menu};
const NOT_MAIN: &str = "dialogs show from the main thread only";
const NOT_RUNNING: &str = "the app isn't running yet, so the dialog can't be shown";
@@ -62,6 +69,133 @@ fn contains(root: &NSView, view: *const c_void) -> bool {
std::ptr::eq((root as *const NSView).cast(), view) || root.subviews().iter().any(|child| contains(&child, view))
}
/// The app's window that `parent`'s view is in.
fn window_of<W: HasWindowHandle>(mtm: MainThreadMarker, parent: &W) -> Option<Retained<NSWindow>> {
let view = match parent.window_handle().map(|h| h.as_raw()) {
Ok(RawWindowHandle::AppKit(h)) => h.ns_view.as_ptr().cast_const(),
_ => return None,
};
NSApplication::sharedApplication(mtm).windows().iter().find(|window| window.contentView().is_some_and(|content| contains(&content, view)))
}
/// The Format menu's height and the room around and between its label and menu, in points.
const ACCESSORY_HEIGHT: f64 = 38.0;
const MARGIN: f64 = 12.0;
const GAP: f64 = 8.0;
/// The Format menu's size, in points.
const MENU: NSSize = NSSize::new(260.0, 26.0);
/// Shows a Save sheet with a Format menu on `parent` (a [`sheet_parent`]) when `d` offers two or more file types
/// ([`format_menu::entries`]), and answers through `reply` with the type chosen in the menu. Choosing a type puts the
/// type's extensions first in the allowed types, which AppKit adds to a name typed without one, and sets the name
/// field to [`format_menu::renamed`]. The SDK's `NSSavePanel.h` says the name field can only be set while the panel is
/// configured; macOS 27.2 shows the new name. Where a system keeps the suggested name, the answer's `filter` still names the chosen
/// type, so the save flow settles the extension (`ExtensionPolicy::picked_type`, or the app's own rule) and asks
/// before replacing a file the panel did not ask about; a kept name with another extension reports that extension's
/// type ([`format_menu::answered_type`]). Gives `reply` back when `d` offers fewer types, for rfd's panel.
///
/// The menu is the panel's accessory view, set before `beginSheetModalForWindow:completionHandler:` shows the sheet:
/// an accessory set after the sheet began made macOS dismiss the sheet at once (storytold/vectorcraft#1800). The
/// completion handler holds the panel, the menu and the menu's target until the sheet closes; the target holds the
/// panel weakly.
pub(crate) fn show_save_sheet<W: HasWindowHandle>(d: &FileDialog, parent: &W, reply: Reply) -> Result<(), Reply> {
let entries = format_menu::entries(&d.filters);
if entries.is_empty() {
return Err(reply);
}
let Some(mtm) = MainThreadMarker::new() else { return Err(reply) };
let Some(window) = window_of(mtm, parent) else { return Err(reply) };
let Some(panel) = craft_appkit::save_panel::new_save_panel(mtm) else {
reply.send(Answer::Unavailable("macOS returned no Save panel".into()));
return Ok(());
};
let name = d.file_name.clone().unwrap_or_default();
let selected = format_menu::initial(&name, &d.filters, &entries);
set_allowed_types(&panel, &d.filters, &entries, selected);
if let Some(title) = &d.title {
panel.setMessage(Some(&NSString::from_str(title)));
}
if let Some(directory) = d.directory.as_deref().and_then(NSURL::from_directory_path) {
panel.setDirectoryURL(Some(&directory));
}
panel.setExtensionHidden(false);
if !name.is_empty() {
panel.setNameFieldStringValue(&NSString::from_str(&name));
}
let label = d.format_label.as_deref().unwrap_or(FORMAT_LABEL);
let (accessory, popup) = accessory(mtm, label, &d.filters, &entries, selected);
panel.setAccessoryView(Some(&accessory));
// The name the field kept when the last choice could not rename it.
let kept: Rc<RefCell<Option<String>>> = Rc::default();
let (filters, listed, weak, kept_by_choice) = (d.filters.clone(), entries.clone(), Weak::new(&*panel), kept.clone());
let choice = craft_appkit::save_panel::on_choose(mtm, &popup, move |at| {
let (Some(panel), Some(chosen)) = (weak.load(), listed.get(at).and_then(|&i| filters.get(i))) else { return };
set_allowed_types(&panel, &filters, &listed, at);
let name = panel.nameFieldStringValue().to_string();
let new_name = format_menu::renamed(&name, chosen, &filters);
panel.setNameFieldStringValue(&NSString::from_str(&new_name));
let shown = panel.nameFieldStringValue().to_string();
*kept_by_choice.borrow_mut() = (shown != new_name).then_some(shown);
});
let reply = Cell::new(Some(reply));
let answered = panel.clone();
let (filters, opened_with) = (d.filters.clone(), d.file_name.clone());
let handler = RcBlock::new(move |response: NSModalResponse| {
// The menu sends its action to `choice` while the sheet is open; the handler keeps it until then.
let _target = &choice;
let Some(reply) = reply.take() else { return };
if response != NSModalResponseOK {
return reply.send(Answer::Cancelled);
}
let Some(path) = answered.URL().and_then(|url| url.to_file_path()) else { return reply.send(Answer::Cancelled) };
let returned = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let filter = usize::try_from(popup.indexOfSelectedItem())
.ok()
.and_then(|at| format_menu::answered_type(&returned, kept.borrow().as_deref(), opened_with.as_deref(), &filters, &entries, at));
reply.send(Answer::Saved { path, filter });
});
panel.beginSheetModalForWindow_completionHandler(&window, &handler);
Ok(())
}
/// Sets `panel`'s allowed file types to [`format_menu::allowed`].
fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], entries: &[usize], selected: usize) {
let types: Vec<Retained<NSString>> = format_menu::allowed(filters, entries, selected).iter().map(|e| NSString::from_str(e)).collect();
// As rfd does, and as `show_panel` does for Open.
#[allow(deprecated)]
panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types)));
}
/// The label and the Format menu of `filters`' `entries`, `selected` chosen, in a view for the panel's accessory.
fn accessory(
mtm: MainThreadMarker,
text: &str,
filters: &[Filter],
entries: &[usize],
selected: usize,
) -> (Retained<NSView>, Retained<NSPopUpButton>) {
let label = NSTextField::labelWithString(&NSString::from_str(text), mtm);
label.sizeToFit();
let size = label.frame().size;
label.setFrameOrigin(NSPoint::new(MARGIN, (ACCESSORY_HEIGHT - size.height) / 2.0));
let x = MARGIN + size.width + GAP;
let frame = NSRect::new(NSPoint::new(x, (ACCESSORY_HEIGHT - MENU.height) / 2.0), MENU);
let popup = NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), frame, false);
// The label beside the menu is not tied to it for VoiceOver, so the menu carries the label's words as its name.
popup.setAccessibilityLabel(Some(&NSString::from_str(text.trim_end_matches([':', ':']))));
for title in format_menu::titles(filters, entries) {
popup.addItemWithTitle(&NSString::from_str(&title));
}
if let Ok(index) = isize::try_from(selected) {
popup.selectItemAtIndex(index);
}
let view = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, NSSize::new(x + MENU.width + MARGIN, ACCESSORY_HEIGHT)));
view.addSubview(&label);
view.addSubview(&popup);
(view, popup)
}
/// Shows an Open or Folder panel that doesn't block the window and answers through `reply` when
/// it closes. AppKit calls the completion handler on the main thread.
pub(crate) fn show_panel(d: &FileDialog, reply: Reply) -> Option<Panel> {
+5 -2
View File
@@ -63,10 +63,13 @@ pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, pare
fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Option<&W>, reply: Reply) -> Shown {
#[cfg(target_os = "macos")]
let parent = match d.kind {
let (parent, reply) = match d.kind {
Kind::Open { .. } | Kind::Folder => return Shown { panel: crate::macos::show_panel(&d, reply) },
Kind::Save => match crate::macos::sheet_parent(parent) {
Ok(parent) => Some(parent),
Ok(parent) => match crate::macos::show_save_sheet(&d, parent, reply) {
Ok(()) => return Shown::default(),
Err(reply) => (Some(parent), reply),
},
Err(why) => {
reply.send(Answer::Unavailable(why));
return Shown::default();
+13 -4
View File
@@ -190,10 +190,7 @@ fn saved(results: &HashMap<String, OwnedValue>) -> Result<Saved, String> {
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
let uri = uris.first().ok_or("no file in the portal's answer")?;
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
let filter = results.get("current_filter").and_then(|v| {
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
let filter = results.get("current_filter").and_then(|v| filter_label(v));
Ok(Saved { path, filter })
}
@@ -309,6 +306,18 @@ fn options<'a>(req: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Va
o
}
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
/// another shape.
fn filter_label(value: &Value<'_>) -> Option<String> {
match value {
Value::Structure(s) => match s.fields() {
[Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()),
_ => None,
},
_ => None,
}
}
/// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes.
// pc: apps/photocraft/src/portal_save.rs:134 file_uri_path
fn file_uri_path(uri: &str) -> Option<PathBuf> {
+42
View File
@@ -27,3 +27,45 @@ fn file_uris_become_local_paths() {
assert_eq!(file_uri_path("sftp://host/x.png"), None);
assert_eq!(file_uri_path("file://host/x.png"), None);
}
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string)
/// gives the path alone; `uris` of another shape is an error.
#[trial]
fn an_answer_of_another_shape_is_not_read() {
let answer_with = |uris: Value<'_>, filter: Option<Value<'_>>| {
let mut r = HashMap::new();
r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap());
if let Some(filter) = filter {
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
}
saved(&r)
};
let card = || Value::from(vec!["file:///tmp/card".to_string()]);
let malformed = [
Value::from(("PNG".to_string(),)),
Value::from(("PNG".to_string(), vec![(0u32,)])),
Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])),
Value::from((1u32, vec![(0u32, "*.png".to_string())])),
Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)),
Value::from("PNG"),
];
for filter in malformed {
let shape = filter.value_signature().to_string();
assert_eq!(answer_with(card(), Some(filter)), Ok(Saved { path: "/tmp/card".into(), filter: None }), "{shape}");
}
// The shape the portal defines is still read, and so is the one `options` sends.
let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())]));
assert_eq!(answer_with(card(), Some(png)), Ok(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }));
let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"])));
assert_eq!(filter_label(&sent), Some("Photoshop".into()));
let malformed = [
Value::from(vec![1u32]),
Value::from(vec![("file:///tmp/card".to_string(),)]),
Value::from(Vec::<String>::new()),
Value::from("file:///tmp/card"),
];
for uris in malformed {
let shape = uris.value_signature().to_string();
assert!(answer_with(uris, None).is_err(), "{shape}");
}
}
+10
View File
@@ -276,6 +276,8 @@ pub struct FilePanels {
extension_policy: ExtensionPolicy,
replace_guard: ReplaceGuard,
replace_words: ReplaceWords,
/// The label of the macOS Save panel's file type menu; `None` shows [`crate::FORMAT_LABEL`].
format_label: Option<String>,
/// Why no file dialog can open on this system, when the probe knows.
backend_problem: fn() -> Option<String>,
/// The replace questions [`pump_with`](FilePanels::pump_with) put on the app's dialog host.
@@ -325,6 +327,7 @@ impl FileService {
extension_policy: ExtensionPolicy::default(),
replace_guard: ReplaceGuard::default(),
replace_words: ReplaceWords::default(),
format_label: None,
backend_problem: probe::known_problem,
#[cfg(feature = "ui")]
prompts: Vec::new(),
@@ -393,6 +396,12 @@ impl FilePanels {
self.replace_words = words;
}
/// The label of the file type menu on a macOS Save panel that offers two or more types ("Format:" in English);
/// the app sets it again when the language changes.
pub fn set_format_label(&mut self, label: impl Into<String>) {
self.format_label = Some(label.into());
}
/// [`extension_policy`](FilePanels::extension_policy) on panels the app already keeps, for a
/// preference that changes while the app runs.
pub fn set_extension_policy(&mut self, policy: ExtensionPolicy) {
@@ -647,6 +656,7 @@ impl FilePanels {
if request.kind == PickKind::Save {
let adds_extension = cfg!(windows) && !request.filters.is_empty();
dialog.file_name = request.file_name.as_deref().and_then(|name| dialog_file_name(name, adds_extension));
dialog.format_label = self.format_label.clone();
}
dialog
}
+47 -20
View File
@@ -4,6 +4,7 @@ use craft_behavior::CanvasView;
use egui::Pos2;
use kurbo::{Affine, CubicBez, ParamCurveNearest as _, Point};
use super::model::SelectedAnchors;
use super::{BezierHit, BezierOverlay, EditPath, HandleSide, HandlesShown, KnotRef, MAX_ANCHORS, PathSelection};
/// A shown direction handle: its path's index, its knot, side and screen end.
@@ -46,15 +47,34 @@ impl BezierOverlay<'_> {
reach: f32,
) -> Option<BezierHit> {
// pc: crates/vector/src/edit.rs:337 `hit` (handles, anchors, segments; nearest per kind).
let shown = shown_handles(paths, selection, handles, view);
let shown = shown_handles(paths, selection, &SelectedAnchors::of(selection), handles, view);
let anchors = paths.iter().map(EditPath::anchor_count).sum::<usize>() <= MAX_ANCHORS;
hit_in(paths, &shown, anchors, view, at, reach)
}
}
/// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection
/// does not show.
pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
/// does not show. `anchors` holds the anchors `sel` selects.
pub(super) fn shown_handles(
paths: &[EditPath],
sel: &PathSelection,
anchors: &SelectedAnchors,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
shown_handles_of(paths, sel, |path, knot| anchors.has_anchor(path, knot), sel.selected_len(), handles, view)
}
/// [`shown_handles`] with `has_anchor` answering whether a knot of a path is a selected anchor, and `selected` as the
/// number of selected anchors that `OneAnchor` counts.
fn shown_handles_of(
paths: &[EditPath],
sel: &PathSelection,
has_anchor: impl Fn(u64, KnotRef) -> bool,
selected: usize,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
let mut shown = Vec::new();
for (index, path) in paths.iter().enumerate() {
let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| {
@@ -65,13 +85,13 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
let Some(knot) = path.knot(knot_ref) else { continue };
for side in [HandleSide::In, HandleSide::Out] {
let of_selection = || {
sel.has_anchor(path.key, knot_ref)
|| next_to_selected_anchor(path, sel, knot_ref, side)
has_anchor(path.key, knot_ref)
|| next_to_selected_anchor(path, &has_anchor, knot_ref, side)
|| segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref))
};
let wanted = match handles {
HandlesShown::All => true,
HandlesShown::OneAnchor => sel.selected_len() == 1 && of_selection(),
HandlesShown::OneAnchor => selected == 1 && of_selection(),
HandlesShown::Selected => of_selection(),
};
if wanted && !knot.retracted(side) {
@@ -85,31 +105,38 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
/// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not
/// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted.
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`.
pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per
/// path, so it reads the listed anchors and their count from `anchors`, the anchors `sel` selects, and copies none.
pub(super) fn other_handles(
paths: &[EditPath],
at: usize,
sel: &PathSelection,
anchors: &SelectedAnchors,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
let Some(path) = paths.get(at) else { return Vec::new() };
let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key));
let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() };
let mut own = PathSelection::new(Some(path.key), anchors.clone(), None);
for (key, rest) in sel.others.iter().filter(|(key, _)| *key != path.key) {
own = own.also(*key, rest.clone());
if sel.path == Some(path.key) || handles == HandlesShown::All || !anchors.lists(path.key) {
return Vec::new();
}
if let Some(edited) = sel.path.filter(|edited| *edited != path.key) {
own = own.also(edited, sel.anchors.clone());
}
shown_handles(std::slice::from_ref(path), &own, handles, view).into_iter().map(|shown| Shown { path: at, ..shown }).collect()
let edited = sel.path.map_or(0, |_| sel.anchors.len());
let own = PathSelection::new(Some(path.key), Vec::new(), None);
shown_handles_of(std::slice::from_ref(path), &own, |key, knot| anchors.listed_anchor(key, knot), anchors.others_len() + edited, handles, view)
.into_iter()
.map(|shown| Shown { path: at, ..shown })
.collect()
}
/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out
/// handle or the next anchor's in handle, across a closed subpath's seam too.
fn next_to_selected_anchor(path: &EditPath, sel: &PathSelection, knot: KnotRef, side: HandleSide) -> bool {
fn next_to_selected_anchor(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool {
let Some(sub) = path.subpaths.get(knot.subpath) else { return false };
let count = sub.knots.len();
match side {
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, next))),
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))),
HandleSide::In => {
let previous = (knot.knot + count.saturating_sub(1)) % count.max(1);
sub.segment_ends(previous).is_some_and(|(previous, _)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
}
}
}
+13 -6
View File
@@ -37,6 +37,9 @@ use hit_test::{Shown, nearest_on_screen, other_handles, shown_handles};
pub(crate) use mark::paint_mark;
pub use mark::{AnchorsShown, HitMark, SegmentMark};
use mark::{Fill, paint_handle, segment_path, stroke};
use model::SelectedAnchors;
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) use model::reads;
pub use model::{AnchorDelete, EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit, PathSelection};
pub use style::BezierStyle;
pub use words::BezierWords;
@@ -381,6 +384,8 @@ struct Scene {
items: Vec<Item>,
/// Over [`MAX_ANCHORS`] or hidden: outlines only.
limited: bool,
/// The anchors the selection selects (none when `limited`).
selected: SelectedAnchors,
}
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
@@ -470,10 +475,12 @@ impl<'a> BezierOverlay<'a> {
let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::<usize>() > MAX_ANCHORS;
let mut items = Vec::new();
if limited {
return Scene { items, limited };
return Scene { items, limited, selected: SelectedAnchors::default() };
}
let selected = SelectedAnchors::of(self.selection);
let near = rect.expand(reach);
let shown = if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, self.handles, view) };
let shown =
if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, &selected, self.handles, view) };
let mut handles = shown.iter().peekable();
for (at, path) in paths.iter().enumerate() {
let count = path.anchor_count();
@@ -551,7 +558,7 @@ impl<'a> BezierOverlay<'a> {
}
}
}
Scene { items, limited }
Scene { items, limited, selected }
}
/// Whether the press on `item` is the tool's.
@@ -1308,7 +1315,7 @@ impl Component for BezierOverlay<'_> {
for item in &scene.items {
let press = self.takes(item);
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
let selected = item.kind == Kind::Anchor && self.selection.has_anchor(item.key, item.knot);
let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot);
let part = cx.part(item.part(), item.shape.clone()).priority(item.priority());
let part = if press { part.sense(PRESS) } else { part };
let part = if keyboard {
@@ -1416,7 +1423,7 @@ impl Component for BezierOverlay<'_> {
draw_end(path, item.knot, item.at, fill);
}
Kind::Anchor if item.shown => {
let fill = if self.selection.draws_selected(path.key, item.knot) {
let fill = if scene.selected.draws_selected(path.key, item.knot) {
Fill::Path(style.line)
} else {
Fill::Style(if cx.part_if_declared(item.part()).is_some() {
@@ -1433,7 +1440,7 @@ impl Component for BezierOverlay<'_> {
// The handles of anchors selected in paths the overlay does not edit: drawn, never parts.
if !circles {
for (at, path) in paths.iter().enumerate() {
for shown in other_handles(paths, at, self.selection, self.handles, &view) {
for shown in other_handles(paths, at, self.selection, &scene.selected, self.handles, &view) {
draw_end(path, shown.knot, shown.at, Fill::Style(cx.resolve(handle_fill)));
}
}
+79
View File
@@ -2,6 +2,8 @@
//! the overlays report. The host converts its own path type to these each frame and applies the
//! edits to its own.
use std::collections::HashSet;
use craft_theme::Srgba;
use kurbo::{BezPath, CubicBez, Point, Vec2};
@@ -235,6 +237,8 @@ impl PathSelection {
/// Whether `knot` of `path` draws selected: a selected anchor of the path being edited, or one listed in `others`.
pub fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
#[cfg(all(test, feature = "screen-testing"))]
reads::add(self.others.iter().map(|(key, anchors)| if *key == path { 1 + anchors.len() } else { 1 }).sum());
self.has_anchor(path, knot) || self.others.iter().any(|(key, anchors)| *key == path && anchors.contains(&knot))
}
@@ -245,6 +249,8 @@ impl PathSelection {
/// Whether `knot` of `path` is a selected anchor.
pub fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
#[cfg(all(test, feature = "screen-testing"))]
reads::add(if self.path == Some(path) { self.anchors.len() } else { 0 });
self.path == Some(path) && self.anchors.contains(&knot)
}
@@ -268,6 +274,79 @@ impl PathSelection {
}
}
/// The anchors a [`PathSelection`] selects, gathered into sets once so that the overlay asks about each knot it lays
/// out or draws without searching the selection's lists. A path that `others` lists more than once is treated as one
/// path holding every anchor listed for it.
#[derive(Default)]
pub(super) struct SelectedAnchors {
path: Option<u64>,
anchors: HashSet<KnotRef>,
others: HashSet<(u64, KnotRef)>,
listed: HashSet<u64>,
others_len: usize,
}
impl SelectedAnchors {
/// The anchors `sel` selects.
pub(super) fn of(sel: &PathSelection) -> Self {
let others_len = sel.others.iter().map(|(_, anchors)| anchors.len()).sum();
#[cfg(all(test, feature = "screen-testing"))]
reads::add(sel.anchors.len() + others_len);
Self {
path: sel.path,
anchors: sel.anchors.iter().copied().collect(),
others: sel.others.iter().flat_map(|(key, anchors)| anchors.iter().map(|knot| (*key, *knot))).collect(),
listed: sel.others.iter().map(|(key, _)| *key).collect(),
others_len,
}
}
/// Whether `knot` of `path` is a selected anchor of the path being edited ([`PathSelection::has_anchor`]).
pub(super) fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.path == Some(path) && self.anchors.contains(&knot)
}
/// Whether `knot` of `path` draws selected ([`PathSelection::draws_selected`]).
pub(super) fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
self.has_anchor(path, knot) || self.others.contains(&(path, knot))
}
/// Whether `knot` is one of the anchors `others` lists for `path`.
pub(super) fn listed_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.others.contains(&(path, knot))
}
/// Whether `others` lists `path`, with or without anchors.
pub(super) fn lists(&self, path: u64) -> bool {
self.listed.contains(&path)
}
/// The number of anchors `others` lists over every path.
pub(super) fn others_len(&self) -> usize {
self.others_len
}
}
/// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work.
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) mod reads {
use std::cell::Cell;
thread_local! {
static READS: Cell<usize> = const { Cell::new(0) };
}
/// Counts `n` entries read.
pub(crate) fn add(n: usize) {
READS.with(|reads| reads.set(reads.get() + n));
}
/// The entries read since the last call, and starts the count again.
pub(crate) fn take() -> usize {
READS.with(|reads| reads.replace(0))
}
}
/// Which of a knot's two direction handles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
+12 -9
View File
@@ -6,7 +6,7 @@ use craft_behavior::Value;
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft_theme::Srgba;
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
@@ -549,31 +549,34 @@ impl DivideSlicesDialog {
}
}
/// One axis: its check box, then (while it is on) what the value counts and the value.
/// One axis: its check box, then (while it is on) what the value counts and the value. Both axes show the same Divide
/// By and value labels, so those rows describe their controls, and each control is named by its label and the axis's
/// caption.
fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &Label, words: &SliceWords, lengths: LengthUnits) {
Field::new(caption.clone()).show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut axis.on)).label(caption.clone()).show(ui);
});
let in_axis = |control: &Label| Label::from(words.axis_control.fill(&[("control", control.as_str()), ("axis", caption.as_str())]));
let unit = if axis.by_size { words.size.clone() } else { words.count.clone() };
Field::new(words.divide_by.clone()).enabled(axis.on).show(ui, |ui, _| {
RadioGroup::new(words.divide_by.clone(), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
let describes = || SideLabel::new().role(FieldLabelRole::Describes);
Field::new(words.divide_by.clone()).side(describes()).enabled(axis.on).show(ui, |ui, _| {
RadioGroup::new(in_axis(&words.divide_by), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
Radio::new(false).label(words.count.clone()).show(ui);
Radio::new(true).label(words.size.clone()).show(ui);
});
});
});
Field::new(unit).enabled(axis.on).show(ui, |ui, _| {
let value_name = in_axis(&unit);
Field::new(unit).side(describes()).enabled(axis.on).show(ui, |ui, _| {
if axis.by_size {
let field =
NumberField::length(words.divide_value.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
let field = NumberField::length(value_name.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
if let Some(Some(size)) = field.value().copied() {
axis.size = AxisState::size_of(size, axis.size);
}
} else {
let max = f64::from(AxisState::MAX_COUNT);
let field =
NumberField::new(words.divide_value.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
let field = NumberField::new(value_name.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
if let Some(Some(count)) = field.value().copied() {
axis.count = count.round().clamp(1.0, max) as u32;
}
+3
View File
@@ -72,5 +72,8 @@ craft_ui::words! {
count: "slice.count" = "slices, evenly spaced";
size: "slice.size" = "per slice";
divide_value: "slice.divideValue" = "Value";
/// The name a screen reader reads for one axis's Divide By group and value field: `{control}` the row's
/// visible label, `{axis}` the axis's caption.
axis_control: template "slice.axisControl" = "{control}, {axis}";
}
}
+16 -6
View File
@@ -71,7 +71,7 @@ impl Outcome for StrokeEditorOutput {
/// with a line sample drawn at opacity 1; the row matching [`StrokeStyle::line_style`] is selected, none for Custom.
/// Picking one applies [`StrokeStyle::with_line_style`].
/// - Rows: Alignment (Inside, Center, Outside; enabled only when [`closed`](Self::closed)); Caps (Butt / Flat, Round,
/// Square; disabled for a solid closed path); Corners (Miter, Round, Bevel; enabled only with
/// Square; disabled for a solid closed path unless [`caps_on_closed`](Self::caps_on_closed)); Corners (Miter, Round, Bevel; enabled only with
/// [`corners`](Self::corners)); the app's [`rows`](Self::rows); Miter limit (1–500, `×`; enabled only for Miter
/// corners); Opacity ([`StrokeSections::OPACITY`], 0–100 %, stored 0..=1). Choices are selects, or segmented icon
/// buttons with [`StrokeSections::ICONS`]. Under the rows of an open path: "Open paths use centered strokes".
@@ -96,6 +96,7 @@ pub struct StrokeEditor<'a> {
value: Bind<'a, StrokeStyle>,
sections: StrokeSections,
closed: bool,
caps_on_closed: bool,
corners: bool,
mixed: StrokeMixed,
rows: &'a [StrokeChoiceRow<'a>],
@@ -109,6 +110,7 @@ impl<'a> StrokeEditor<'a> {
value,
sections: StrokeSections::default(),
closed: true,
caps_on_closed: false,
corners: true,
mixed: StrokeMixed::default(),
rows: &[],
@@ -121,13 +123,20 @@ impl<'a> StrokeEditor<'a> {
self
}
/// Whether the stroked path is closed: alignment applies and caps need dashes.
/// True by default.
/// Whether the stroked path is closed: alignment applies and caps need dashes, unless
/// [`caps_on_closed`](Self::caps_on_closed) is set. True by default.
pub fn closed(mut self, closed: bool) -> Self {
self.closed = closed;
self
}
/// Whether the Caps row stays enabled on a closed path without dashes. False by default: the row is then disabled
/// for a solid closed path and enabled for an open or dashed one.
pub fn caps_on_closed(mut self, enabled: bool) -> Self {
self.caps_on_closed = enabled;
self
}
/// Whether the path has corners for the Corners and Miter limit rows (an ellipse has none). True by default.
pub fn corners(mut self, corners: bool) -> Self {
self.corners = corners;
@@ -148,7 +157,7 @@ impl<'a> StrokeEditor<'a> {
/// Shows the editor.
pub fn show(self, ui: &mut Ui) -> StrokeEditorOutput {
let StrokeEditor { label, mut value, sections, closed, corners, mixed, rows } = self;
let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows } = self;
let env = Env::of(ui);
let words = env.words::<StrokeWords>();
let name: Arc<str> = label.as_str().into();
@@ -164,7 +173,7 @@ impl<'a> StrokeEditor<'a> {
Some((base, draft)) if base == held => draft,
_ => held.clone(),
};
let body = Body { words: &words, style: &style, sections, closed, corners, mixed, rows, name: name.clone() };
let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, name: name.clone() };
body.show(ui, &mut found);
if !found.events.is_empty() {
for event in &found.events {
@@ -251,6 +260,7 @@ struct Body<'a> {
style: &'a StrokeStyle,
sections: StrokeSections,
closed: bool,
caps_on_closed: bool,
corners: bool,
mixed: StrokeMixed,
rows: &'a [StrokeChoiceRow<'a>],
@@ -325,7 +335,7 @@ impl Body<'_> {
fn grid(&self, ui: &mut Ui, found: &mut Found) {
let (style, mixed, words) = (self.style, self.mixed, self.words);
let solid_closed = self.closed && style.dashes.is_empty() && !mixed.dashes;
let solid_closed = self.closed && !self.caps_on_closed && style.dashes.is_empty() && !mixed.dashes;
let icons = self.sections.contains(StrokeSections::ICONS);
FieldGroup::new(words.title.clone()).show(ui, |ui, _| {
let align = [
+48
View File
@@ -465,6 +465,54 @@ fn one_anchor_shows_handles_only_while_one_anchor_is_selected_over_all_paths() {
assert!(!matches!(none, Some(BezierHit::Handle { .. })), "{none:?}");
}
// Under `OneAnchor` the handles of an anchor listed in `others` draw while it is the only selected anchor over all
// paths, as `Selected` draws them; with an anchor of a third path listed too, neither path's handles draw.
#[trial]
fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths() {
let painted_with = |selection: PathSelection, handles: HandlesShown| {
let mut other = path_b();
other.subpaths[0].knots[0] = Knot::smooth(p(60.0, 200.0), p(90.0, 170.0));
let third =
EditPath::new(3, vec![EditSubpath::new(vec![Knot::smooth(p(300.0, 220.0), p(330.0, 190.0)), Knot::corner(p(360.0, 260.0))], false)]);
let mut h = harness(vec![path_a(), other, third]);
h.update(|st| (st.selection, st.handles) = (selection, handles));
format!("{:?}", h.fixture.frame_shapes())
};
let one = || sel(1, &[]).also(2, vec![kr(0)]);
assert_eq!(painted_with(one(), HandlesShown::OneAnchor), painted_with(one(), HandlesShown::Selected));
let two = || sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]);
assert_ne!(painted_with(two(), HandlesShown::OneAnchor), painted_with(two(), HandlesShown::Selected));
assert_eq!(
painted_with(two(), HandlesShown::OneAnchor),
painted_with(sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]), HandlesShown::OneAnchor),
"painting is the same from frame to frame"
);
}
// A frame reads the selection's anchor lists a number of times that grows with the selection, not with its square:
// doubling the selected anchors of the edited path and the number of other paths listed at most doubles the entries
// read (a search of the lists for each anchor laid out or drawn quadruples them).
#[trial]
fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
let reads_for = |n: usize| {
let knot = |i: usize| Knot::smooth(p(20.0 + (i % 40) as f64 * 12.0, 20.0 + (i / 40) as f64 * 12.0), p(26.0 + (i % 40) as f64 * 12.0, 20.0));
let edited = EditPath::new(1, vec![EditSubpath::new((0..n).map(knot).collect(), false)]);
let others: Vec<EditPath> =
(0..n).map(|i| EditPath::new(2 + i as u64, vec![EditSubpath::new((0..4).map(|k| knot(i * 4 + k)).collect(), true)])).collect();
let mut selection = PathSelection::new(Some(1), (0..n).map(kr).collect(), None);
for other in &others {
selection = selection.also(other.key, (0..4).map(kr).collect());
}
let mut h = harness(std::iter::once(edited).chain(others).collect());
craft_draw::ui::pen::bezier::reads::take();
h.update(|st| st.selection = selection);
craft_draw::ui::pen::bezier::reads::take()
};
let (small, large) = (reads_for(60), reads_for(120));
assert!(small > 0, "the frame reads the selection");
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
}
// Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at.
// `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.
+41 -3
View File
@@ -4,11 +4,15 @@
use craft_behavior::geometry::Constraint;
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::ui::slice::{SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool, SliceToolSettings};
use craft_ui::contract::{CommandSet, Show as _};
use craft_draw::ui::slice::{
DivideBy, DivideSlices, DivideSlicesDialog, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool,
SliceToolSettings,
};
use craft_ui::contract::{CommandSet, Role, Show as _};
use craft_ui::dialog::DialogHost;
use craft_ui::runtime::commands::CommandRef;
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{ToolFixture, trial};
use craft_ui::testing::{Fixture, ToolFixture, access, trial};
use egui::{Key, Modifiers, Pos2, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
@@ -203,3 +207,37 @@ fn delete_takes_the_key_for_the_selected_slice() {
}
}
}
/// The names a screen reader reads for the nodes of `role` in the shown Divide Slice dialog, in tree order.
fn divide_names(divide: DivideSlices, role: Role) -> Vec<String> {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(900.0, 700.0));
host.borrow_mut().open(DivideSlicesDialog::new(divide));
fixture.idle(10);
let tree = fixture.tree();
fixture.by_role(role).iter().map(|target| access::name(tree, target.node).unwrap_or_default().to_owned()).collect()
}
/// Divide Slice's two axes show the same Divide By choice and value rows; each axis's radio group and value field
/// name their axis by its caption after their visible label, so a screen reader tells the rows from the columns.
#[trial]
fn divide_slice_names_each_axis_control_by_its_axis() {
let by_count = DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(3)));
let by_size = DivideSlices::new(Some(DivideBy::Size(72.0)), Some(DivideBy::Size(36.0)));
let cases = [
("the Divide By groups", by_count, Role::RADIO_GROUP, "Divide By"),
("the count fields", by_count, Role::SPIN_BUTTON, "slices, evenly spaced"),
("the size fields", by_size, Role::SPIN_BUTTON, "per slice"),
];
for (what, divide, role, label) in cases {
let names = divide_names(divide, role);
let [rows, columns] = names.as_slice() else { panic!("{what}: one for each axis, got {names:?}") };
assert_ne!(rows, columns, "{what} have different names");
for (name, axis) in [(rows, "Divide Horizontally Into"), (columns, "Divide Vertically Into")] {
assert!(name.starts_with(label), "{what}: {name:?} starts with the visible label {label:?}");
assert!(name.contains(axis), "{what}: {name:?} names its axis {axis:?}");
}
}
}
+36 -2
View File
@@ -1,7 +1,8 @@
//! The stroke editor's dash fields: typing in the blank after the pattern adds an entry, clearing a later field ends
//! the pattern there, and the first field never clears.
//! the pattern there, and the first field never clears. Its Caps row on a solid closed path: disabled by default,
//! enabled with `caps_on_closed`.
use craft_draw::ui::stroke::{StrokeEditor, StrokeSections, StrokeStyle};
use craft_draw::ui::stroke::{LineCap, StrokeEditor, StrokeSections, StrokeStyle};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
@@ -34,6 +35,39 @@ fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
fixture.idle(3);
}
/// The panel editor over a solid closed path, with `caps_on_closed` as given, and the style it writes through to.
fn closed_editor(caps_on_closed: bool) -> (Fixture, Rc<RefCell<StrokeStyle>>) {
let style = Rc::new(RefCell::new(StrokeStyle::default()));
let shown = Rc::clone(&style);
let mut fixture = Fixture::new(move |ui| {
let mut style = shown.borrow_mut();
let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style))
.sections(StrokeSections::PANEL)
.closed(true)
.caps_on_closed(caps_on_closed)
.show(ui);
});
fixture.settle();
(fixture, style)
}
#[trial]
fn caps_on_closed_keeps_the_cap_buttons_enabled_on_a_solid_closed_path() {
let (mut fixture, style) = closed_editor(false);
let square = fixture.by_label("Square").expect("the editor shows Square");
assert!(fixture.tree().is_disabled_key(square.node), "by default Caps is disabled for a solid closed path");
fixture.click(&square);
fixture.idle(3);
assert_ne!(style.borrow().cap, LineCap::Square, "a disabled cap button does not change the cap");
let (mut fixture, style) = closed_editor(true);
let square = fixture.by_label("Square").expect("the editor shows Square");
assert!(!fixture.tree().is_disabled_key(square.node), "with caps_on_closed Caps is enabled");
fixture.click(&square);
fixture.idle(3);
assert_eq!(style.borrow().cap, LineCap::Square, "the cap button sets the cap");
}
#[trial]
fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() {
let (mut fixture, style) = editor(vec![4.0, 2.0]);
+6 -2
View File
@@ -95,13 +95,17 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names (
- `embedded_elsewhere(&["Noto Sans Math", …])` names families another table of the app embeds,
so `check_text` and the catalog check count their characters as covered.
- `dir(path)` and `required(bool)` override the two environment variables.
- `tab_face()` also embeds Noto Sans Condensed SemiBold from `fonts/latin-manifest.txt`, with the
role `tab`. `scripts` and `filter` do not apply to it. A checkout without that manifest or its
row embeds the other faces and prints a warning, even with `CRAFT_FONTS_REQUIRED=1`.
`write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face
is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts,
index, bytes, role }` literals; any struct with those fields and that name in scope works too.
`role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")`, `Some("signature")` or
`None`; craft-ui's font stack leads the Monospace family with the `mono` face and the signature
family (`FontRef::signature()`) with the `signature` face. `EmbeddedFace` itself has `name()`,
`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace
family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature`
face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`,
`has_script(tag)`, `is_cjk()` and `weight()`.
## Document fonts
+94 -28
View File
@@ -9,7 +9,7 @@ use std::io;
use std::path::{Component, Path, PathBuf};
use crate::cmap::Cmap;
use crate::manifest::{ManifestEntry, ParseError, parse_manifest, script_matches};
use crate::manifest::{ManifestEntry, ParseError, TAB_FACE, TAB_ROLE, parse_manifest, script_matches};
const DIR_VAR: &str = "CRAFT_FONTS_DIR";
const REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED";
@@ -55,6 +55,35 @@ fn rerun_if_changed(cargo: &mut Vec<String>, path: &Path) -> Result<(), Error> {
Ok(())
}
/// `entry` of `manifest` as a face to embed, once its font file resolves to a file inside the checkout `root` and its
/// licence file, if it exists, does too.
fn checked_face(manifest: &Path, dir: &Path, root: &Path, entry: ManifestEntry, cut: bool, cargo: &mut Vec<String>) -> Result<Face, Error> {
let manifest = manifest.to_path_buf();
// A manifest path names a file in the checkout, and is served under the same name.
for file in [&entry.file, &entry.licence_file] {
if !file.is_empty() && !is_checkout_relative(file) {
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
}
}
let file = dir.join(&entry.file);
// `include_bytes!` resolves relative paths from the including source file.
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
// missing licence is only warned about when serving; one that exists must be inside.
if !path.starts_with(root) {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(root)) {
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
}
if !path.is_file() {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
rerun_if_changed(cargo, &path)?;
let (index, sha256) = (entry.index, entry.sha256.clone());
Ok(Face { entry, path, index, cut, sha256 })
}
/// Whether the build script is building for wasm32 (web builds usually embed fewer faces).
pub fn target_is_wasm() -> bool {
std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32")
@@ -75,6 +104,7 @@ pub struct Embed {
families: Option<Vec<String>>,
elsewhere: Vec<String>,
serve: Option<Serve>,
tab: bool,
}
/// Where [`Embed::serve`] copies the faces, and the URL prefix they are served under.
@@ -174,6 +204,18 @@ impl Embed {
self
}
/// Also embed the tab-title face, Noto Sans Condensed SemiBold ([`TAB_FACE`]), from the checkout's
/// `fonts/latin-manifest.txt`, with the `tab` role ([`TAB_ROLE`]); craft-ui's font stack leads its tab-title family
/// with it. [`Embed::scripts`] and [`Embed::filter`] do not apply to it. A checkout without that manifest, or a
/// manifest without the face's row, embeds the other faces and prints a `cargo::warning`, required or not. A
/// manifest that does not parse, or a row whose file is missing or outside the checkout, is an [`Error`] when
/// required and a `cargo::warning` otherwise; the other faces are embedded either way when not required. A
/// [`Embed::serve`] table carries no roles, so it leaves the face out and prints a `cargo::warning`.
pub fn tab_face(mut self) -> Self {
self.tab = true;
self
}
/// Read this checkout instead of `CRAFT_FONTS_DIR`.
pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.dir = Some(dir.into());
@@ -239,7 +281,7 @@ impl Embed {
let selected = match &dir {
None => Err(Error::NotSet),
Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
Some(dir) => self.select(dir, required, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
};
let mut selected = selected;
if let Ok(faces) = &mut selected {
@@ -278,8 +320,39 @@ impl Embed {
Ok(faces)
}
/// The tab-title face of `fonts/latin-manifest.txt` ([`TAB_FACE`]), with the [`TAB_ROLE`] role. A checkout without
/// that manifest, or a manifest without the face's row, gives `None` and a `cargo::warning`.
fn select_tab_face(&self, dir: &Path, root: &Path, cargo: &mut Vec<String>) -> Result<Option<Face>, Error> {
let manifest = dir.join("fonts/latin-manifest.txt");
let text = match read_text_bounded(&manifest, MAX_MANIFEST_BYTES) {
Ok(text) => text,
Err(source) if source.kind() == io::ErrorKind::NotFound => {
// Cargo treats a missing watched file as changed, so the build watches the folder the manifest would be in.
rerun_if_changed(cargo, &dir.join("fonts"))?;
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} does not exist", manifest.display()));
return Ok(None);
}
Err(source) => return Err(Error::Read { path: manifest, source }),
};
rerun_if_changed(cargo, &manifest)?;
let entries = parse_manifest(&text).map_err(|error| Error::Parse { manifest: manifest.clone(), error })?;
let (family, style) = TAB_FACE;
let Some(mut entry) = entries.into_iter().find(|entry| entry.family == family && entry.style == style) else {
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} has no {family} {style} row", manifest.display()));
return Ok(None);
};
entry.role = Some(TAB_ROLE.to_owned());
let file = dir.join(&entry.file);
if !file.exists() {
// Cargo treats a missing watched file as changed, so the build watches the nearest folder that exists.
let folder = file.ancestors().skip(1).find(|folder| folder.is_dir()).unwrap_or(dir);
rerun_if_changed(cargo, folder)?;
}
checked_face(&manifest, dir, root, entry, false, cargo).map(Some)
}
/// The wanted manifest entries with their canonical file paths.
fn select(&self, dir: &Path, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
fn select(&self, dir: &Path, required: bool, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
let manifest = dir.join("fonts/manifest.txt");
let text = read_text_bounded(&manifest, MAX_MANIFEST_BYTES).map_err(|source| Error::Read { path: manifest.clone(), source })?;
// Cargo treats a missing watched file as changed, which would rerun the build every time.
@@ -325,29 +398,17 @@ impl Embed {
uncut.push(format!("{} {}", entry.family, entry.style));
continue;
}
// A manifest path names a file in the checkout, and is served under the same name.
for file in [&entry.file, &entry.licence_file] {
if !file.is_empty() && !is_checkout_relative(file) {
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
}
faces.push(checked_face(&manifest, dir, &root, entry, cut, cargo)?);
}
if self.tab && self.serve.is_some() {
cargo.push("cargo::warning=craft-fonts: not serving the tab-title face: a served table carries no roles".to_owned());
} else if self.tab {
match self.select_tab_face(dir, &root, cargo) {
Ok(Some(face)) => faces.push(face),
Ok(None) => {}
Err(e) if required => return Err(e),
Err(e) => cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {e}")),
}
let file = dir.join(&entry.file);
// `include_bytes!` resolves relative paths from the including source file.
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
// missing licence is only warned about when serving; one that exists must be inside.
if !path.starts_with(&root) {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(&root)) {
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
}
if !path.is_file() {
return Err(Error::OutsideCheckout { manifest, file: entry.file });
}
rerun_if_changed(cargo, &path)?;
let (index, sha256) = (entry.index, entry.sha256.clone());
faces.push(Face { entry, path, index, cut, sha256 });
}
if !uncut.is_empty() {
let why = if self.catalogs.is_some() { "Embed::subset_to was given no translation catalogs" } else { "no translation catalogs" };
@@ -451,7 +512,8 @@ impl Embed {
}
/// Warn about each catalog's and [`Embed::check_text`] file's characters that neither an
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers.
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers. The tab-title face, which draws only tab titles,
/// covers none of them.
fn check_coverage(&self, faces: &[Face], dir: &Path, cargo: &mut Vec<String>) {
let files = self.checked_files();
if files.is_empty() {
@@ -460,6 +522,7 @@ impl Embed {
let elsewhere = self.elsewhere(dir, cargo);
let fonts: Vec<(&ManifestEntry, u32, Option<Vec<u8>>)> = faces
.iter()
.filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE))
.map(|face| (&face.entry, face.index, read_bounded(&face.path, MAX_FILE_BYTES).ok()))
.chain(elsewhere.iter().map(|entry| (entry, entry.index, read_bounded(&dir.join(&entry.file), MAX_FILE_BYTES).ok())))
.collect();
@@ -496,16 +559,19 @@ impl Embed {
}
}
/// `faces` when `fonts/manifest.txt` gave at least one, covering every script of [`Embed::scripts`]; the tab-title
/// face, which neither selection applies to, counts for neither.
fn check_required(&self, dir: &Path, faces: Vec<Face>) -> Result<Vec<Face>, Error> {
let manifest = dir.join("fonts/manifest.txt");
if faces.is_empty() {
let selected = || faces.iter().filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE));
if selected().next().is_none() {
return Err(Error::NoFaces { manifest });
}
let missing: Vec<String> = self
.scripts
.iter()
.flatten()
.filter(|tag| !faces.iter().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
.filter(|tag| !selected().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
.cloned()
.collect();
if missing.is_empty() { Ok(faces) } else { Err(Error::MissingScripts { manifest, scripts: missing }) }
+3 -3
View File
@@ -62,7 +62,7 @@ mod sha256;
mod tests;
pub use embed::{Embed, Error, target_is_wasm};
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, UI_ROLE, parse_manifest};
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, TAB_FACE, TAB_ROLE, UI_ROLE, parse_manifest};
/// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`.
///
@@ -81,8 +81,8 @@ pub struct EmbeddedFace {
/// The font file's bytes, from `include_bytes!`.
pub bytes: &'static [u8],
/// The manifest line's `role`: `Some("ui")` for an interface face ([`UI_ROLE`]), `Some("mono")` for the
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a
/// line without one.
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `Some("tab")`
/// for the tab-title face [`Embed::tab_face`] adds ([`TAB_ROLE`]), `None` for a line without one.
pub role: Option<&'static str>,
}
+10
View File
@@ -11,6 +11,8 @@
//! translation catalogs; `mono` for the monospace face, which leads an app's Monospace family; or
//! `signature` for the handwriting face, which leads the signature family.
//! Fields after the ninth are ignored, so a manifest that gains a field still embeds.
//! `fonts/latin-manifest.txt` has the same format; [`Embed::tab_face`](crate::Embed::tab_face)
//! reads one row of it and gives that face the `tab` role.
use std::fmt;
@@ -37,6 +39,7 @@ pub struct ManifestEntry {
pub source: String,
/// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the
/// monospace face, `Some("signature")` for the signature face, `None` when the line has no role.
/// [`Embed::tab_face`](crate::Embed::tab_face) sets `Some("tab")` on the face it adds.
pub role: Option<String>,
}
@@ -72,6 +75,13 @@ pub const MONO_ROLE: &str = "mono";
/// The `role` of a signature face: `FontRef::signature()` selects the embedded faces that have it.
pub const SIGNATURE_ROLE: &str = "signature";
/// The `role` [`Embed::tab_face`](crate::Embed::tab_face) gives the tab-title face it embeds from
/// `fonts/latin-manifest.txt`: the tab-title family leads with the embedded face that has it.
pub const TAB_ROLE: &str = "tab";
/// The family and style of the tab-title face in `fonts/latin-manifest.txt`.
pub const TAB_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold");
/// Script tags of the CJK faces, which craft-fonts also ships as interface faces. `Hant` covers
/// `Hant-HK`.
pub const CJK_SCRIPTS: &[&str] = &["Hans", "Hant", "Jpan", "Kore", "Hani"];
+72
View File
@@ -368,3 +368,75 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() {
let r = run(Embed::new(), Some(&dir), None);
assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo);
}
/// `Embed::tab_face` adds only the Noto Sans Condensed SemiBold row of `fonts/latin-manifest.txt`, with the `tab` role.
/// A checkout without that manifest or row keeps its other faces, required or not; a broken manifest or row is an
/// error only when required. The face counts for none of the scripts a required build asks for and covers none of the
/// characters of a checked text, and a served table leaves it out.
#[test]
fn the_tab_face_comes_from_the_latin_manifest_with_the_tab_role() {
let scratch = Scratch::new("tab-face");
let dir = checkout(&scratch, &[("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x627, 0x627, None)], &[]))]);
std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap();
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
std::fs::write(dir.join("fonts/inter.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
let latin = dir.join("fonts/latin-manifest.txt");
let row = |family: &str, style: &str, file: &str| format!("{family} | {style} | {file} | Latn | OFL-1.1 | fonts/OFL.txt | 00 | src\n");
let both = row("Inter", "SemiBold", "fonts/inter.ttf") + &row("Noto Sans", "Condensed SemiBold", "fonts/condensed.ttf");
std::fs::write(&latin, &both).unwrap();
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
assert!(r.table.contains(r#"family: "Noto Sans", style: "Condensed SemiBold""#) && r.table.contains(r#"role: Some("tab")"#), "{}", r.table);
assert!(!r.table.contains("Inter"), "{}", r.table);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", latin.display())), "{:?}", r.cargo);
// Scripts and the filter narrow only the main manifest's faces.
let r = run(Embed::new().scripts(&["Arab"]).filter(|f| f.has_script("Arab")).tab_face(), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
// The tab-title face does not stand in for a required script the main manifest lacks.
let r = run(Embed::new().scripts(&["Latn"]).tab_face(), Some(&dir), Some("1"));
assert!(matches!(&r.result, Err(Error::NoFaces { .. })), "{:?}", r.result);
let r = run(Embed::new().scripts(&["Arab", "Latn"]).tab_face(), Some(&dir), Some("1"));
assert!(matches!(&r.result, Err(Error::MissingScripts { scripts, .. }) if scripts == &["Latn"]), "{:?}", r.result);
let r = run(Embed::new(), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
// A served table carries no roles, so it leaves the face out.
let r = run(Embed::new().tab_face().serve(scratch.0.join("served"), "fonts/"), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
assert!(warnings(&r).iter().any(|w| w.contains("not serving the tab-title face")), "{:?}", r.cargo);
// Only tab titles draw in the face, so it covers none of the characters of a checked text.
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None), (0x4E00, 0x4E00, None)], &[])).unwrap();
let text = scratch.0.join("text.ftl");
std::fs::write(&text, "x = \u{4E00}\n").unwrap();
let r = run(Embed::new().tab_face().check_text([&text]), Some(&dir), Some("1"));
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
assert!(warnings(&r).iter().any(|w| w.contains("1 character no embedded face covers (\u{4E00})")), "{:?}", r.cargo);
// No row for the face, or no latin manifest at all: the other faces and a warning, even when required.
std::fs::write(&latin, row("Inter", "SemiBold", "fonts/inter.ttf")).unwrap();
for required in [None, Some("1")] {
let r = run(Embed::new().tab_face(), Some(&dir), required);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
assert!(warnings(&r).iter().any(|w| w.contains("has no Noto Sans Condensed SemiBold row")), "{:?}", r.cargo);
}
std::fs::remove_file(&latin).unwrap();
for required in [None, Some("1")] {
let r = run(Embed::new().tab_face(), Some(&dir), required);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
assert!(warnings(&r).iter().any(|w| w.contains("latin-manifest.txt does not exist")), "{:?}", r.cargo);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
}
// A manifest line that does not parse, or a row whose file is missing.
for broken in ["Noto Sans | Condensed SemiBold | fonts/condensed.ttf\n".to_owned(), row("Noto Sans", "Condensed SemiBold", "fonts/gone.ttf")] {
std::fs::write(&latin, &broken).unwrap();
let r = run(Embed::new().tab_face(), Some(&dir), None);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"], "{broken}");
assert!(warnings(&r).iter().any(|w| w.contains("not embedding the tab-title face")), "{broken}: {:?}", r.cargo);
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
assert!(matches!(r.result, Err(Error::Parse { .. } | Error::Read { .. })), "{broken}: {:?}", r.result);
}
// The build reruns when the missing file is added: it watches the folder the file would be in.
let r = run(Embed::new().tab_face(), Some(&dir), None);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
}
+7 -2
View File
@@ -19,6 +19,8 @@
use std::cmp::Reverse;
use std::collections::VecDeque;
use std::hash::Hash;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::{self, ThreadId};
@@ -94,14 +96,17 @@ pub enum QueueOrder {
impl QueueOptions {
/// Lanes for this machine: the number of cores less one, at least 2 and at most 8 (4 when
/// the core count is unknown); 0 on wasm32.
/// the core count is unknown); 0 on wasm32. The core count is read once per process.
// lightcraft: crates/preview/src/pool.rs:104 `default_threads` (cores − 1 clamped to 2..=8;
// ours is 0 on wasm32 instead of 1, because wasm runs jobs only through `run_inline`).
pub fn default_lanes() -> usize {
#[cfg(target_arch = "wasm32")]
return 0;
#[cfg(not(target_arch = "wasm32"))]
thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8))
{
static LANES: OnceLock<usize> = OnceLock::new();
*LANES.get_or_init(|| thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8)))
}
}
}
+2 -1
View File
@@ -310,7 +310,8 @@ impl Component for Histogram<'_> {
let accent = super::data::color32(colors.data.selection);
let warn = cx.tone(craft_theme::variant::Tone::Warn);
HistogramStyle {
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, tall)),
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
metrics: Metrics::new().min_size(Vec2::new(0.0, tall)),
focus: cx.focus_look(),
caption: TextLook::new(TypeRole::Caption, Stateful::new(cx.color(colors.text.normal))),
stale: IconLook::new(cx.tokens.size.icon.sm, Stateful::new(warn)),
+5 -2
View File
@@ -137,7 +137,9 @@ app translates. The dialog never opens a file dialog or touches the file system.
## Windows, Linux and web: the in-window bar
`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a
`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by
side (`MenuBarOutput`). A host that puts controls after the titles on the same row compares that
width with the room it leaves the bar. Show it inside a
`Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold
into "…".
Each item is a command row: its enabled state, check mark and chord follow the command in the
@@ -227,7 +229,8 @@ While a menu is open, a click or Escape in the window closes it and does not rea
canvas gesture, no tool action); pointer moves pass through. Only one click is kept this way
until the menu reports closed, so a menu wrongly reported open costs one click. Menu updates wait
until the menu closes; the end of tracking wakes egui, and that frame applies them. A rebuild that
fails keeps the menus as they were.
fails keeps the menus as they were, and the same menus are tried once more a second later, with no
input needed (`RebuildRetry`). When that fails too, the next change to the menus tries again.
AppKit's `NSMenuDidBeginTracking` and `NSMenuDidEndTracking` notifications say whether a menu is
open (`craft_window::native_menu::menu_tracking()`, safe from any thread). Each begin comes back
+8 -5
View File
@@ -48,11 +48,11 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform {
/// A replay at another place moves the titles' rect with the bar.
impl craft_ui::runtime::Shift for MenuBarOutput {
fn shifted(&self, by: &egui::RecordShift) -> Self {
MenuBarOutput { titles: by.rect(self.titles), opened: self.opened }
MenuBarOutput { titles: by.rect(self.titles), natural: self.natural, opened: self.opened }
}
fn snapped(&self, to: &Self, within: f32) -> Self {
MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), opened: self.opened }
MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), natural: self.natural, opened: self.opened }
}
}
@@ -63,6 +63,9 @@ pub struct MenuBarOutput {
/// The menu titles alone, without the room the bar leaves after them
/// ([`craft_ui::menu::MenuBarOutput::titles`]).
pub titles: Rect,
/// The width every title takes side by side with none in "…", whatever room the bar had
/// ([`craft_ui::menu::MenuBarOutput::natural`]). Zero when the bar shows nothing.
pub natural: f32,
/// True in the one pass where a menu of the bar opened while none was open
/// ([`craft_ui::menu::MenuBarOutput::opened`]).
pub opened: bool,
@@ -167,7 +170,7 @@ impl<'a> MenuBarUi<'a> {
icons: self.icons,
compact: self.compact,
};
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, opened: false })
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, natural: 0.0, opened: false })
}
}
@@ -214,8 +217,8 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput {
if let Some(menu) = props.help {
bar = bar.help(MenuHelp::new(menu, &entries));
}
let out = bar.show(ui);
MenuBarOutput { titles: out.titles, opened: out.opened }
let shown = bar.show(ui);
MenuBarOutput { titles: shown.titles, natural: shown.natural, opened: shown.opened }
}
/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics,
+62
View File
@@ -3,6 +3,7 @@
use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
use craft_keymap::{Chord, CommandRef, Key, Mods};
use craft_ui::contract::{MemoKey, MemoProps};
@@ -203,6 +204,67 @@ pub trait Backend {
fn attach(&mut self, dispatch: Dispatch);
}
/// How long a backend waits after a failed rebuild before it tries the same menus once more
/// ([`RebuildRetry`]).
pub const REBUILD_RETRY: Duration = Duration::from_secs(1);
/// When a backend tries again to build menus the platform could not build. New menus are always
/// built. When their build fails, the same menus are tried once more [`REBUILD_RETRY`] after the
/// failure; when that fails too, they are not tried again until they change.
///
/// The driver syncs a backend only when the menus' key, the gate or a menu event calls for it
/// ([`NativeMenu::sync_with`]), so a backend keeps the menus it could not build and tries them
/// again itself, for example from [`Backend::drain`], asking egui for a frame when the retry is
/// due.
#[derive(Debug)]
pub struct RebuildRetry<B> {
/// The menus whose build failed, and when to try them again (`None`: their retry failed too).
failed: Option<(B, Option<Instant>)>,
}
impl<B> Default for RebuildRetry<B> {
fn default() -> RebuildRetry<B> {
RebuildRetry { failed: None }
}
}
/// What [`RebuildRetry::attempt`] did.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attempt {
/// The menus were built.
Built,
/// The menus were not built: their build failed, or their retry is not due yet. Try them again
/// after this long.
Retry(Duration),
/// The build failed and so did its retry: these menus are not built again until they change.
Failed,
}
impl<B: Clone + PartialEq> RebuildRetry<B> {
/// Build `bar` with `build` (which returns whether it succeeded) unless `bar` failed before
/// and its retry is not due, and record the outcome. `clock` gives the time. It is read again
/// after a failed build, so the delay starts when the build fails.
pub fn attempt(&mut self, bar: &B, clock: impl Fn() -> Instant, build: impl FnOnce() -> bool) -> Attempt {
let now = clock();
let retrying = match &self.failed {
Some((failed, at)) if failed == bar => match at {
Some(at) if now < *at => return Attempt::Retry(at.saturating_duration_since(now)),
Some(_) => true,
None => return Attempt::Failed,
},
_ => false,
};
if build() {
self.failed = None;
return Attempt::Built;
}
let at = if retrying { None } else { clock().checked_add(REBUILD_RETRY) };
self.failed = Some((bar.clone(), at));
if at.is_some() { Attempt::Retry(REBUILD_RETRY) } else { Attempt::Failed }
}
}
/// The native menu bar, while the app uses one (its in-window menus are hidden then).
pub struct NativeMenu {
backend: Box<dyn Backend>,
+1 -1
View File
@@ -126,7 +126,7 @@ pub use craft_keymap::{Chord, CommandRef};
pub use craft_ui::menu::Alternate;
pub use customize::Customization;
pub use documents::DOCUMENT_COMMAND_PREFIX;
pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu};
pub use driver::{Attempt, Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, REBUILD_RETRY, RebuildRetry};
pub use help::{HelpCommand, HelpLabels, HelpLink, HelpMenu};
pub use keymap::{ItemState, apply_keymap, apply_state};
pub use keytips::{KeytipControl, Keytips, KeytipsOutput};
+27 -5
View File
@@ -26,16 +26,20 @@
//! Hide Others and Minimize built-ins use the system's localized titles when the app supplies no
//! translation, that is when the label is still the English name.
//! - While a menu is open, changes wait until it closes.
//! - When AppKit refuses a rebuild, the menus as they were stay up and the same menus are tried
//! once more a second later ([`RebuildRetry`]), with no input needed; when that fails too, the
//! next change to the menus tries again.
use std::collections::HashMap;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Instant;
use craft_keymap::{Chord, CommandRef, Key, Mods};
use craft_ui::menu::Alternate;
use craft_window::native_menu as native;
use crate::driver::{Backend, Dispatch, Event, NativeMenu, native_ok};
use crate::driver::{Attempt, Backend, Dispatch, Event, NativeMenu, RebuildRetry, native_ok};
use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key};
/// Install the native menu bar for `bar` (a [`crate::mac_layout`] result) and return the driver
@@ -83,7 +87,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
});
let installed = native::NativeBar::install(&spec, native::Options::default().window_list(options.window_list), wake)?;
let (tx, rx) = channel();
let backend = Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None };
let backend =
Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None, retry: RebuildRetry::default() };
// `NativeMenu::new` attaches the driver's dispatch, which points the handler at this menu.
Some(NativeMenu::new(Box::new(backend)))
}
@@ -135,15 +140,32 @@ struct Native {
targets: Targets,
tx: Sender<Event>,
rx: Receiver<Event>,
/// The latest menus, waiting for the open menu to close.
/// The latest menus, waiting for the open menu to close, or for the retry of a rebuild that
/// failed.
pending: Option<MenuBar>,
/// Menus AppKit could not build, and when to try them again.
retry: RebuildRetry<native::Bar>,
}
impl Native {
/// Bring the native menus in step with `bar`. When the rebuild fails and a retry is to come,
/// `bar` waits in `pending` and egui is asked for a frame when the retry is due: the driver
/// does not sync the same menus again.
fn update(&mut self, bar: &MenuBar) {
let (spec, targets) = lower(bar);
if self.bar.apply(&spec) {
*lock(&self.targets) = targets;
let (native, live) = (&mut self.bar, &self.targets);
let attempt = self.retry.attempt(&spec, Instant::now, || {
let rebuilt = native.apply(&spec);
if rebuilt {
*lock(live) = targets;
}
!native.failed()
});
// egui keeps no repaint delay from one pass to the next, so a frame before the retry is
// due asks again.
if let Attempt::Retry(wait) = attempt {
self.pending = Some(bar.clone());
self.ctx.request_repaint_after(wait);
}
}
}
+5 -5
View File
@@ -19,7 +19,7 @@ use craft_ui::primitives::textures::{Revision, ThumbSource, Thumbnails};
use craft_ui::primitives::{ContentPainterCx, HAlign, PaintShape, TextRun};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::focus::KeyUse;
use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx, TypeRole};
use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, TypeRole};
use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::{ColorImage, CornerRadius, Rect, Response, Ui, Vec2};
@@ -189,7 +189,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
fn sizes(&self, cx: &MeasureCx<'_, Self>) -> Sizes {
let words = cx.env.words::<GalleryWords>();
let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()));
let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact));
Sizes { tile: cx.face(GalleryTile::blank(self.aspect, self.thumb_size, self.captioned())), button, gap: cx.gap() }
}
}
@@ -723,9 +723,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1));
draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2));
}
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0));
ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last));
ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()));
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0).glyphs(GlyphRole::Compact));
ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last).glyphs(GlyphRole::Compact));
ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact));
}
/// The context request is recorded after `update`, so `finish` reads it: a secondary click on a tile, or the Menu
+11 -4
View File
@@ -23,6 +23,7 @@ use craft_ui::contract::{BodyCx, CollectionEvent, Props as _, Scroll, Show as _,
use craft_ui::display::Icon;
use craft_ui::layout_components::{Grid, Row, Stack};
use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::motion::Animate as _;
use craft_ui::tabs::{Tab, TabKind, TabStrip};
use egui::Ui;
@@ -111,10 +112,10 @@ impl DisplayOrder<usize> for Titles<'_> {
impl ItemSource<usize> for Titles<'_> {}
/// A strip of text tabs over `titles` with `shown` selected; the tab picked this pass.
pub(super) fn tab_strip(ui: &mut Ui, name: &'static str, titles: &[String], shown: usize) -> Option<usize> {
/// A strip of text tabs named `name`, keyed by `id`, over `titles` with `shown` selected; the tab picked this pass.
pub(super) fn tab_strip(ui: &mut Ui, id: &'static str, name: impl Into<Label>, titles: &[String], shown: usize) -> Option<usize> {
let strip = TabStrip::new(name)
.id_salt(name)
.id_salt(id)
.kind(TabKind::Text)
.shown(shown)
.show_items(ui, &Titles(titles), &mut |key, _| Tab::new(titles[*key].clone()).id_salt(("tab", *key)));
@@ -139,7 +140,13 @@ fn app_tabs(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> Option<u
state.set_tab(None);
}
let shown = current.map_or(0, |i| i + 1);
let picked = Stack::new().fill_width().enabled(!state.modal()).show(ui, |ui, _| tab_strip(ui, "shortcuts.tab", &titles, shown)).inner.flatten();
let name = env.title();
let picked = Stack::new()
.fill_width()
.enabled(!state.modal())
.show(ui, |ui, _| tab_strip(ui, "shortcuts.tab", name.clone(), &titles, shown))
.inner
.flatten();
let shown = match picked {
Some(i) => {
state.set_tab(i.checked_sub(1).and_then(|k| ids.get(k).copied()));
+4 -4
View File
@@ -23,7 +23,7 @@ const HOLD_DELAY_STEP: f64 = 0.05;
/// The header for one pass.
pub(super) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, now: f64, env: &mut Env<'_>, state: &mut DialogState) {
if env.options.area_tabs {
area_tabs(ui, state);
area_tabs(ui, env, state);
}
Row::new().show(ui, |ui, _| {
if !env.options.area_tabs {
@@ -66,11 +66,11 @@ fn holds(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) {
}
}
/// Show as tabs.
fn area_tabs(ui: &mut Ui, state: &mut DialogState) {
/// Show as tabs, named like the Show select.
fn area_tabs(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) {
let titles: Vec<String> = state.areas.iter().map(|area| area.label.clone()).collect();
let shown = state.areas.iter().position(|area| area.id == state.area).unwrap_or(0);
if let Some(i) = tab_strip(ui, "shortcuts.area", &titles, shown)
if let Some(i) = tab_strip(ui, "shortcuts.area", env.text.words().show.clone(), &titles, shown)
&& let Some(area) = state.areas.get(i)
{
let id = area.id.clone();
+56 -2
View File
@@ -5,11 +5,12 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use craft_keymap::Mods;
use craft_menu::{
Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu, apply_state,
mac_layout, structure_key,
Alternate, Attempt, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu,
REBUILD_RETRY, RebuildRetry, apply_state, mac_layout, structure_key,
};
use craft_ui::contract::{Props as _, Show as _, Tracked};
use craft_ui::testing::focus::key_release;
@@ -379,3 +380,56 @@ fn apply_state_with_no_change_keeps_the_revision() {
apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new")));
assert_eq!(model.revision(), moved, "and the same changed state again does not");
}
/// Menus whose build failed are not built again before their retry is due, are built once when it
/// is due, and are not built again after that fails too; changed menus are built and get their own
/// retry.
#[trial]
fn a_failed_rebuild_is_tried_once_more() {
let (first, second) = (sample(false, true), sample(true, true));
let mut retry = RebuildRetry::default();
let start = Instant::now();
let clock = Cell::new(start);
let builds = Cell::new(0);
let fail = || {
builds.set(builds.get() + 1);
false
};
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Retry(REBUILD_RETRY), "a failed build waits for its retry");
clock.set(start + REBUILD_RETRY / 2);
let Attempt::Retry(left) = retry.attempt(&first, || clock.get(), fail) else { panic!("the retry is not due yet") };
assert!(left < REBUILD_RETRY, "a sync before the retry learns the time left: {left:?}");
assert_eq!(builds.get(), 1, "nothing is built before the retry is due");
clock.set(start + REBUILD_RETRY);
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Failed, "the retry fails too");
clock.set(start + REBUILD_RETRY * 10);
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Failed);
assert_eq!(builds.get(), 2, "the same menus are tried once more, and only once");
assert_eq!(retry.attempt(&second, || clock.get(), fail), Attempt::Retry(REBUILD_RETRY), "changed menus are built and get their own retry");
assert_eq!(builds.get(), 3);
clock.set(start + REBUILD_RETRY * 11);
assert_eq!(retry.attempt(&second, || clock.get(), || true), Attempt::Built, "the retry builds them");
assert_eq!(retry.attempt(&second, || clock.get(), || true), Attempt::Built, "built menus can be built again");
}
/// A build that fails slowly gets the whole delay, counted from when it failed.
#[trial]
fn a_retry_waits_from_when_the_build_failed() {
let bar = sample(false, true);
let mut retry = RebuildRetry::default();
let start = Instant::now();
let clock = Cell::new(start);
let slow = Duration::from_millis(1200);
let slow_failure = || {
clock.set(start + slow);
false
};
assert_eq!(retry.attempt(&bar, || clock.get(), slow_failure), Attempt::Retry(REBUILD_RETRY));
clock.set(start + REBUILD_RETRY);
let Attempt::Retry(left) = retry.attempt(&bar, || clock.get(), || panic!("built before the retry was due")) else {
panic!("the retry is not due a delay after the build began")
};
assert_eq!(left, slow, "the delay runs from the failure, not from when the build began");
clock.set(start + slow + REBUILD_RETRY);
assert_eq!(retry.attempt(&bar, || clock.get(), || true), Attempt::Built, "the retry runs when it is due");
}
+7
View File
@@ -145,6 +145,13 @@ fn own_areas_show_only_the_apps_entries_and_open_on_the_first() {
assert_eq!(area(&rig), "all");
}
/// Show as tabs is a tab list named like the Show select it replaces.
#[trial]
fn area_tabs_are_named_show() {
let rig = Rig::tuned(Platform::Mac, |options| options.area_tabs = true);
assert_eq!(rig.names_with(Role::TAB_LIST, ""), ["Show:"]);
}
/// A dialog opened with a command selected, with Show listing only the app's entries, opens on the entry that lists it.
#[trial]
fn own_areas_open_on_the_selected_commands_entry() {
+10
View File
@@ -74,6 +74,16 @@ fn app_tabs_show_full_labels_at_125_percent_and_switch_pages() {
}
}
#[trial]
fn app_tabs_are_named_after_the_dialog() {
let (mut frames, mut show) = dialog_at_125_percent("Toolbar");
frames.idle(12, &mut show);
let tree = frames.tree();
let lists: Vec<&str> =
tree.keys().into_iter().filter(|&key| tree.role_of(key) == Some(Role::TAB_LIST)).filter_map(|key| tree.name_of(key)).collect();
assert_eq!(lists, ["Keyboard Shortcuts and Menus"]);
}
#[trial]
fn app_tabs_keep_overflow_when_the_labels_do_not_fit() {
let long_label = "Toolbar ".repeat(200);
+29 -1
View File
@@ -1,6 +1,7 @@
//! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title
//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack`
//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge.
//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. In any room the bar
//! reports the width its titles take side by side.
use std::cell::Cell;
use std::rc::Rc;
@@ -131,3 +132,30 @@ fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_i
fixture.click(&more).settle();
assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu");
}
/// The bar reports the width every title takes side by side: in a stack that holds them all it is the titles' width,
/// and in a stack too narrow for them it is the same width while the drawn titles are narrower.
#[trial]
fn the_bar_reports_the_width_every_title_takes_in_a_wide_and_a_narrow_stack() {
let mut reports = Vec::new();
for width in [1520.0, 240.0] {
let bar = Rc::new(model());
let seen = Rc::new(Cell::new((0.0, 0.0)));
let out = Rc::clone(&seen);
let mut fixture = Fixture::new(move |ui| {
let bar = Rc::clone(&bar);
let out = Rc::clone(&out);
Stack::new().show(ui, move |ui, _| {
let shown = MenuBarUi::new(&bar).target(Target::Windows).show(ui);
out.set((shown.natural, shown.titles.width()));
});
});
fixture.os(Os::Windows).room(vec2(width, 600.0)).settle();
reports.push(seen.get());
}
let [(wide, wide_titles), (narrow, narrow_titles)] = [reports[0], reports[1]];
assert!(wide > 0.0, "the bar reports a width");
assert!((wide - wide_titles).abs() < 0.5, "with room for every title the natural width {wide} is the titles' width {wide_titles}");
assert!((narrow - wide).abs() < 0.5, "a narrow bar reports the same natural width {narrow} as a wide one {wide}");
assert!(narrow_titles < narrow, "a narrow bar draws titles {narrow_titles} narrower than its natural width {narrow}");
}
+25 -5
View File
@@ -25,8 +25,8 @@ pub(crate) mod stories;
use craft_behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed};
use craft_ui::contract::{
Bind, CollectionEvent, ColumnSpec, ContextMenuRequest, ListDrag, NoValue, Outcome, ReorderMove, ReorderRule, SelectMode, ShowCollection as _,
ShowContainer as _, request_rename,
Bind, CollectionEvent, ColumnSpec, ContextMenuRequest, ListDrag, NoValue, Outcome, Props as _, ReorderMove, ReorderRule, SelectMode,
ShowCollection as _, ShowContainer as _, request_rename,
};
use craft_ui::list::{ListRow, RowEvent, TrailingFace, TrailingPart};
use craft_ui::primitives::IconSpec;
@@ -197,13 +197,26 @@ pub struct PageList<'a> {
picked: &'a mut Selection<usize>,
active: usize,
rename: Option<usize>,
document: Option<u64>,
}
impl<'a> PageList<'a> {
/// A list named `label` of `rows`, with `picked` as the selection and `active` as the page or artboard being
/// edited.
pub fn new(label: impl Into<Label>, rows: &'a [PageListRow], picked: &'a mut Selection<usize>, active: usize) -> Self {
PageList { label: label.into(), rows, picked, active, rename: None }
PageList { label: label.into(), rows, picked, active, rename: None, document: None }
}
/// The document the list shows, so the list's own state (rename, scroll, lead) is per document: a rename left
/// open in one document does not open on the row with the same number in another. Without it every document
/// shares one.
#[must_use]
pub fn document(mut self, key: impl std::hash::Hash) -> Self {
use std::hash::Hasher as _;
let mut hasher = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut hasher);
self.document = Some(hasher.finish());
self
}
/// Starts renaming `row` (the app's Rename command): its field opens at the list's next pass.
@@ -215,7 +228,14 @@ impl<'a> PageList<'a> {
/// Shows the list and returns its response and the events for the app to apply.
pub fn show(self, ui: &mut Ui) -> PageListOutput {
let PageList { label, rows, picked, active, rename } = self;
let PageList { label, rows, picked, active, rename, document } = self;
// Row numbers restart in every document, so with a document the list's state (the panel's scroll and the
// table inside it) is keyed by the list's label and the document.
let panel = Panel::new(label.clone());
let panel = match document {
Some(document) => panel.id(ui.scope_id().with(("page-list", label.as_str(), document))),
None => panel,
};
let env = Env::of(ui);
let words = env.words::<PageListWords>();
let unlocked = |from: &[usize]| from.iter().copied().filter(|&row| rows.get(row).is_some_and(|r| !r.locked)).collect::<Vec<_>>();
@@ -235,7 +255,7 @@ impl<'a> PageList<'a> {
let after = ReorderMove::new(active, vec![active], to, false);
PageListEvent::Reorder(EditEvent::set(Mixed::Same(before), after, Arc::from(label.as_str()), None))
};
let response = Panel::new(label.clone())
let response = panel
.footer(|ui, _| {
let list = *list_id.borrow();
let ours = move |drag: &ListDrag<usize>| Some(drag.list) == list;
+2 -1
View File
@@ -290,7 +290,8 @@ impl Component for ReadingView<'_> {
fn style(cx: &StyleCx<'_>, _: ReadingViewStyleKey) -> ReadingViewStyle {
ReadingViewStyle {
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, cx.tokens.size.plot.height)),
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
metrics: Metrics::new().min_size(Vec2::new(0.0, cx.tokens.size.plot.height)),
focus: cx.focus_look(),
gap: cx.tokens.space.gap.section,
reach: cx.tokens.size.hit.target,
+106
View File
@@ -0,0 +1,106 @@
//! `PageList`: with a document, a rename left open and the scroll position do not carry over to another document.
use craft_behavior::Selection;
use craft_pages::ui::{PageList, PageListEvent, PageListRow};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// The room of the list: wide enough for the names, tall enough for a few rows and the footer.
const PANEL: Vec2 = Vec2::new(320.0, 300.0);
type Seen = Rc<RefCell<Vec<PageListEvent>>>;
/// The list over the rows of the document the trial sets, with the events it reports.
struct Rig {
fixture: Fixture,
seen: Seen,
document: Rc<Cell<u32>>,
}
/// The list over `rows(document)`, starting in document 0.
fn rig(rows: fn(u32) -> Vec<PageListRow>) -> Rig {
let seen: Seen = Rc::default();
let document = Rc::new(Cell::new(0_u32));
let picked = Rc::new(RefCell::new(Selection::single(0_usize)));
let (sink, shown, choice) = (Rc::clone(&seen), Rc::clone(&document), Rc::clone(&picked));
let mut fixture = Fixture::new(move |ui| {
let rows = rows(shown.get());
let mut picked = choice.borrow_mut();
let out = PageList::new("Artboards", &rows, &mut picked, 0).document(shown.get()).show(ui);
sink.borrow_mut().extend(out.events);
});
fixture.room(PANEL);
fixture.settle();
Rig { fixture, seen, document }
}
/// Two rows, named apart in each document.
fn two_rows(document: u32) -> Vec<PageListRow> {
let names = if document == 0 { ["Cover", "Back"] } else { ["Front", "Inside"] };
names.into_iter().map(PageListRow::new).collect()
}
/// Forty rows, more than the panel shows, named by document and number.
fn many_rows(document: u32) -> Vec<PageListRow> {
let prefix = if document == 0 { "Sheet" } else { "Page" };
(1..=40).map(|n| PageListRow::new(format!("{prefix} {n}"))).collect()
}
/// The renames reported since the last call, as row and name.
fn renames(seen: &Seen) -> Vec<(usize, String)> {
seen.borrow_mut()
.drain(..)
.filter_map(|event| if let PageListEvent::Rename { row, text, .. } = event { Some((row, text)) } else { None })
.collect()
}
/// Row numbers restart in every document, so the rename field of row 2 in one document is not the field of row 2 in
/// another: a switch with the field open renames nothing in the document switched to.
#[trial]
fn a_rename_left_open_does_not_carry_over_to_another_document() {
let mut rig = rig(two_rows);
let back = rig.fixture.by_label("Back").expect("the second row shows");
rig.fixture.click(&back);
rig.fixture.idle(2);
rig.fixture.key(Key::F2, Modifiers::NONE);
rig.fixture.idle(2);
rig.fixture.type_text("X");
rig.fixture.idle(2);
assert!(renames(&rig.seen).is_empty(), "typing in the field renames nothing yet");
rig.document.set(1);
rig.fixture.idle(3);
assert!(rig.fixture.by_label("Inside").is_some(), "the other document's rows show");
rig.fixture.type_text("Y");
rig.fixture.key(Key::Enter, Modifiers::NONE);
rig.fixture.idle(2);
let other = renames(&rig.seen);
assert!(other.is_empty(), "the field of the first document does not open on the second's row 2: {other:?}");
rig.document.set(0);
rig.fixture.idle(3);
rig.fixture.key(Key::Enter, Modifiers::NONE);
rig.fixture.idle(2);
let back = renames(&rig.seen);
assert!(back.iter().all(|(_, name)| !name.contains('Y')), "a rename back in the first document has nothing typed in the second: {back:?}");
}
/// A list scrolled down in one document shows another document's list from its own position, the top.
#[trial]
fn the_scroll_position_does_not_carry_over_to_another_document() {
let mut rig = rig(many_rows);
let first = rig.fixture.by_label("Sheet 1").expect("the first row shows");
rig.fixture.click(&first);
rig.fixture.idle(2);
rig.fixture.key(Key::End, Modifiers::NONE);
rig.fixture.idle(3);
// A row is in view when its rect is inside the room the list is shown in.
let shown = |rig: &Rig, name: &str| rig.fixture.by_label(name).is_some_and(|row| rig.fixture.shown().contains_rect(row.rect));
assert!(shown(&rig, "Sheet 40") && !shown(&rig, "Sheet 1"), "End scrolls the first document's list to its last row");
rig.document.set(1);
rig.fixture.idle(3);
assert!(shown(&rig, "Page 1"), "the second document's list shows its first row");
}
+1
View File
@@ -1,6 +1,7 @@
//! The screen tests of craft-pages, folded into the lib's test target.
pub(crate) mod access;
pub(crate) mod list;
pub(crate) mod range;
pub(crate) mod rulers;
pub(crate) mod setup;
+1 -1
View File
@@ -23,7 +23,7 @@ pull in heavier dependencies.
| always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. |
| always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. |
| always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. |
| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. |
| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` gives a file an access list of the user and SYSTEM only, `create_private_dir` and `create_private_file` create a folder or file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. |
| always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. |
| `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). |
| `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. |
+483 -58
View File
@@ -4,12 +4,14 @@
//! a new folder at a drive root, `C:\Users\Public` or `C:\ProgramData` let every signed-in user
//! read what is created in them. `restrict_to_owner` replaces the whole list with the current
//! user and SYSTEM only, makes that user the owner, and checks the result. `create_private_dir`
//! does the same for a new folder whose list the files created in it inherit, so a file can be
//! private from the moment it exists. `read_with_sddl` reads a file and its security descriptor
//! creates a folder with that owner and list from the start, which the files created in it
//! inherit, so a file can be private from the moment it exists. `read_with_sddl` reads a file and its security descriptor
//! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts
//! by SID and so reads the same in every Windows language, and says why another user could have
//! written or could read the file. They run the tools Windows ships rather than calling the
//! security API directly, which would need `unsafe`.
//! security API directly, which would need `unsafe`. A run of a tool that takes longer than
//! `TOOL_LIMIT` (10 s) is ended, and the function fails with an error of kind
//! [`std::io::ErrorKind::TimedOut`].
/// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL or
/// as `read_with_sddl` writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no
@@ -21,6 +23,18 @@
/// file over. `restrict_to_owner` never grants it, so the app's own file always passes; a file
/// that inherited it from a user's folder is refused.
pub fn foreign_access(sddl: &str, me: &str) -> Option<String> {
foreign(sddl, me, false)
}
/// [`foreign_access`] for a folder's descriptor: an inherit-only entry (`IO`) counts too, since
/// every file and folder created in the folder gets it.
#[cfg(any(test, windows))]
fn foreign_folder_access(sddl: &str, me: &str) -> Option<String> {
foreign(sddl, me, true)
}
/// [`foreign_access`], counting inherit-only entries when `inherit_only` is set.
fn foreign(sddl: &str, me: &str, inherit_only: bool) -> Option<String> {
let me = me.trim();
let owner = section(sddl, "O:");
match owner {
@@ -41,7 +55,7 @@ pub fn foreign_access(sddl: &str, me: &str) -> Option<String> {
let (Some(kind), Some(flags)) = (parts.first(), parts.get(1)) else { continue };
// Deny entries take access away, and inherit-only entries apply to children, not the file.
let allows = matches!(*kind, "A" | "OA" | "XA" | "ZA");
if !allows || flags.contains("IO") {
if !allows || (flags.contains("IO") && !inherit_only) {
continue;
}
// An entry that grants access but names no account can't be shown to be the user's.
@@ -146,11 +160,129 @@ fn system_tool(relative: &str) -> std::process::Command {
command
}
/// How long one run of a tool may take before it is ended. Each tool finishes in a second or two.
/// On some computers a new process is left suspended (security software holding it), and without
/// a limit the caller would wait on it for as long as it stays that way.
#[cfg(windows)]
pub const TOOL_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
/// How often [`run_until`] checks whether the tool has exited.
#[cfg(any(test, windows))]
const POLL: std::time::Duration = std::time::Duration::from_millis(20);
/// How many more checks [`run_until`] makes for a tool it has ended to exit before it stops
/// waiting on it.
#[cfg(any(test, windows))]
const EXIT_POLLS: u32 = 50;
/// How a run of [`run_until`] ended.
#[cfg(any(test, windows))]
enum Ran {
/// The tool exited by itself: its status and output, and how writing its standard input went.
Exited(std::process::Output, std::io::Result<()>),
/// The time was up first and the tool was ended. `exited` is whether it was then seen to exit.
Ended { exited: bool },
}
/// Start `command` with its standard input, output and error piped, hand its standard input to
/// `feed` on a thread of its own, and wait for it to exit. Between checks, `expired` gets what
/// the tool has written to its standard output so far; when it answers `true` first, the tool is
/// ended ([`std::process::Child::kill`]). Standard output and error are read on threads of their
/// own, so a tool that writes more than a pipe holds is not stopped by it.
#[cfg(any(test, windows))]
fn run_until(
mut command: std::process::Command,
feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static,
mut expired: impl FnMut(&[u8]) -> bool,
) -> std::io::Result<Ran> {
use std::io::Read as _;
use std::process::Stdio;
let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
let fed = child.stdin.take().map(|stdin| std::thread::spawn(move || feed(stdin)));
let (chunks, received) = std::sync::mpsc::channel::<Vec<u8>>();
if let Some(mut out) = child.stdout.take() {
std::thread::spawn(move || {
let mut buf = [0u8; 4096];
while let Ok(n @ 1..) = out.read(&mut buf) {
if chunks.send(buf.get(..n).unwrap_or_default().to_vec()).is_err() {
break;
}
}
});
}
let errors = child.stderr.take().map(|mut err| {
std::thread::spawn(move || {
let mut text = Vec::new();
let _ = err.read_to_end(&mut text);
text
})
});
let mut stdout = Vec::new();
loop {
stdout.extend(received.try_iter().flatten());
if let Some(status) = child.try_wait()? {
// The pipes close when the tool exits, which ends both readers.
stdout.extend(received.iter().flatten());
let stderr = errors.and_then(|e| e.join().ok()).unwrap_or_default();
let sent = match fed.map(std::thread::JoinHandle::join) {
Some(Ok(sent)) => sent,
Some(Err(_)) => Err(std::io::Error::other("the thread writing the standard input stopped")),
None => Err(std::io::Error::other("the standard input could not be opened")),
};
return Ok(Ran::Exited(std::process::Output { status, stdout, stderr }, sent));
}
if expired(&stdout) {
let _ = child.kill();
let mut exited = false;
for _ in 0..EXIT_POLLS {
if child.try_wait().ok().flatten().is_some() {
exited = true;
break;
}
std::thread::sleep(POLL);
}
return Ok(Ran::Ended { exited });
}
std::thread::sleep(POLL);
}
}
/// Run `command`, with nothing on its standard input, for at most [`TOOL_LIMIT`]: its status and
/// output, or an error of kind [`std::io::ErrorKind::TimedOut`] when it was ended.
#[cfg(windows)]
fn run(command: std::process::Command) -> std::io::Result<std::process::Output> {
let deadline = std::time::Instant::now() + TOOL_LIMIT;
let program = tool_name(&command);
let close = |stdin: std::process::ChildStdin| {
drop(stdin);
Ok(())
};
match run_until(command, close, |_| std::time::Instant::now() >= deadline)? {
Ran::Exited(out, _) => Ok(out),
Ran::Ended { .. } => Err(timed_out(&program)),
}
}
/// The file name of the program `command` starts, for messages.
#[cfg(windows)]
fn tool_name(command: &std::process::Command) -> String {
let program = std::path::Path::new(command.get_program());
program.file_name().unwrap_or(program.as_os_str()).to_string_lossy().into_owned()
}
/// The error for a run of `program` that [`run_until`] ended.
#[cfg(windows)]
fn timed_out(program: &str) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{program} did not finish within {} s and was ended", TOOL_LIMIT.as_secs()))
}
/// The current user's SID (`whoami /user`). It starts a process, so a caller that needs it for
/// several steps reads it once and passes it to each.
#[cfg(windows)]
pub fn current_user_sid() -> std::io::Result<String> {
let out = system_tool(WHOAMI).args(["/user", "/fo", "csv", "/nh"]).output()?;
let mut whoami = system_tool(WHOAMI);
whoami.args(["/user", "/fo", "csv", "/nh"]);
let out = run(whoami)?;
if !out.status.success() {
return Err(std::io::Error::other("whoami /user failed"));
}
@@ -177,32 +309,177 @@ fn sid_from_whoami(text: &str) -> Option<String> {
/// replace it, while setting the owner needs the Full control it grants (a folder may give Modify).
#[cfg(windows)]
pub fn restrict_to_owner(path: &std::path::Path, me: &str) -> std::io::Result<()> {
set_access_list(path, me, Kind::File)?;
set_access_list(path, me)?;
icacls(path, &["/setowner".into(), format!("*{me}")])?;
still_foreign(&sddl_of(path)?, me)
}
/// Create the folder `dir`, which must not exist yet, and give it an access list of user `me` (as
/// for [`restrict_to_owner`]) and SYSTEM only, which every file created in it inherits; then make
/// that user its owner and check the result as [`restrict_to_owner`] does. A file created in it is
/// private from the moment it exists. Restricting a file after creating it leaves a window in which another user
/// whom the parent folder lets read it can open a handle, and Windows checks access only when a
/// handle is opened, so a later change of the list doesn't revoke it. A handle on the folder
/// itself, opened during the folder's own window, gives no access to the files created in it
/// later. The folder is removed again when it can't be restricted.
/// Create the folder `dir`, which must not exist yet and whose parent must, with user `me` (as for
/// [`restrict_to_owner`]) as its owner and an access list of that user and SYSTEM only, which every
/// file created in it inherits, given to Windows in the call that creates the folder. The folder
/// never has its parent's access list, and a file created in it is private from the moment it
/// exists. The folder is created beside `dir` under a name of its own
/// (`.<name>.<process id>.<count>.tmp`) and then moved to `dir`, which fails when `dir` exists.
/// Then check its descriptor, inherit-only entries included. An existing `dir` is an error of kind
/// [`std::io::ErrorKind::AlreadyExists`] and a missing parent one of kind
/// [`std::io::ErrorKind::NotFound`]; the folder is removed again when the check fails.
///
/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error
/// of kind [`std::io::ErrorKind::TimedOut`]; the folder under its own name is then removed once
/// PowerShell has exited. A folder PowerShell had already moved to `dir` stays there, with the
/// access list it was created with: this call can't tell it from a folder another process put at
/// `dir` since, so it doesn't remove what is there.
#[cfg(windows)]
pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()> {
std::fs::create_dir(dir)?;
fn restrict(dir: &std::path::Path, me: &str) -> std::io::Result<()> {
set_access_list(dir, me, Kind::Folder)?;
icacls(dir, &["/setowner".into(), format!("*{me}")])?;
still_foreign(&sddl_of(dir)?, me)
use std::sync::atomic::{AtomicU64, Ordering};
/// Numbers the staged folders of this process.
static COUNT: AtomicU64 = AtomicU64::new(0);
// No double quotes: the command line would strip them. `Directory.CreateDirectory` also creates
// a missing parent and returns an existing folder as it is, hence the checks before it.
// `Directory.Move` doesn't replace an existing folder (`std::fs::rename` does, when it is
// empty).
const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \
if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \
if (-not [IO.Directory]::Exists([IO.Path]::GetDirectoryName($env:CRAFT_ACL_PATH))) { exit 4 }; \
if (Test-Path -LiteralPath $env:CRAFT_ACL_STAGED) { exit 5 }; \
$s = New-Object Security.AccessControl.DirectorySecurity; \
$s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)'); \
[void][IO.Directory]::CreateDirectory($env:CRAFT_ACL_STAGED, $s); \
try { [IO.Directory]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \
catch { [IO.Directory]::Delete($env:CRAFT_ACL_STAGED); if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; throw }";
// A relative `dir` such as `private` has no parent in its text; the script needs one.
let dir = &std::path::absolute(dir)?;
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let staged = dir.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
let mut powershell = system_tool(POWERSHELL);
powershell
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
.env("CRAFT_ACL_PATH", dir)
.env("CRAFT_ACL_STAGED", &staged)
.env("CRAFT_ACL_USER", me);
let deadline = std::time::Instant::now() + TOOL_LIMIT;
let close = |stdin: std::process::ChildStdin| {
drop(stdin);
Ok(())
};
let out = match run_until(powershell, close, |_| std::time::Instant::now() >= deadline)? {
Ran::Exited(out, _) => out,
Ran::Ended { exited } => {
if exited {
let _ = std::fs::remove_dir(&staged);
}
return Err(timed_out("powershell.exe"));
}
};
match out.status.code() {
Some(3) => return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the folder already exists")),
Some(4) => return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "the folder's parent does not exist")),
_ if !out.status.success() => {
return Err(std::io::Error::other(format!(
"PowerShell could not create the folder for its owner only: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
_ => {}
}
let restricted = restrict(dir, me);
if restricted.is_err() {
let checked = sddl_of(dir).and_then(|sddl| match foreign_folder_access(&sddl, me) {
None => Ok(()),
Some(problem) => Err(std::io::Error::other(format!("the folder could not be restricted to its owner: {problem}"))),
});
if checked.is_err() {
let _ = std::fs::remove_dir(dir);
}
restricted
checked
}
/// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`])
/// as its owner and an access list of that user and SYSTEM only, given to Windows in the call that
/// creates the file, so the file never has its folder's access list, and write `contents` through
/// that handle, opened unshared. The file is created beside `path` under a name of its own
/// (`.<name>.<process id>.<count>.tmp`) and takes the name `path` only once `contents` are
/// written, so `path` never holds a partly written file. Then check the file's descriptor as
/// [`restrict_to_owner`] does. An existing `path` is an error of kind
/// [`std::io::ErrorKind::AlreadyExists`] and is left as it is. A file that was created but could
/// not be written or checked is removed again. `contents` reach PowerShell through its standard
/// input, never as script text or an environment variable.
///
/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error
/// of kind [`std::io::ErrorKind::TimedOut`]. The file under its own name is then removed. If
/// PowerShell is not seen to exit after being ended, that file may stay, and a file PowerShell had
/// already moved to `path` stays there: this call can't tell it from a file another process put at
/// `path` since. Either still has the access list given when it was created.
#[cfg(windows)]
pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
let deadline = std::time::Instant::now() + TOOL_LIMIT;
let contents = contents.to_vec();
create_private_file_until(path, me, move |mut stdin| stdin.write_all(&contents), |_| std::time::Instant::now() >= deadline)
}
/// [`create_private_file`], with `feed` writing the contents to PowerShell's standard input and
/// `expired` saying when to end it, as [`run_until`] takes them.
#[cfg(windows)]
fn create_private_file_until(
path: &std::path::Path,
me: &str,
feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static,
expired: impl FnMut(&[u8]) -> bool,
) -> std::io::Result<()> {
use std::sync::atomic::{AtomicU64, Ordering};
/// The exit code the script ends with when the file already exists.
const EXISTS: i32 = 3;
/// Numbers the staged files of this process.
static COUNT: AtomicU64 = AtomicU64::new(0);
// No double quotes: the command line would strip them. -2147024816 and -2147024713 are the
// HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. `File.Move` fails when the
// destination exists.
const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \
if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \
$s = New-Object Security.AccessControl.FileSecurity; \
$s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)'); \
$fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_STAGED, [IO.FileMode]::CreateNew, \
[Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s); \
try { [Console]::OpenStandardInput().CopyTo($fs); $fs.Flush($true); $fs.Dispose() } \
catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_STAGED); throw }; \
try { [IO.File]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \
catch { [IO.File]::Delete($env:CRAFT_ACL_STAGED); $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \
if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }";
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
let mut powershell = system_tool(POWERSHELL);
powershell
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
.env("CRAFT_ACL_PATH", path)
.env("CRAFT_ACL_STAGED", &staged)
.env("CRAFT_ACL_USER", me);
// A script that stops before reading (the file exists) closes the pipe; its exit code says why.
let ran = run_until(powershell, feed, expired);
// The staged name is this call's own, so removing it never removes another process's file.
// PowerShell holds the staged file open unshared until it exits.
let (out, sent) = match ran? {
Ran::Exited(out, sent) => (out, sent),
Ran::Ended { exited } => {
if exited {
let _ = std::fs::remove_file(&staged);
}
return Err(timed_out("powershell.exe"));
}
};
if out.status.code() == Some(EXISTS) {
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"));
}
if !out.status.success() {
let _ = std::fs::remove_file(&staged);
return Err(std::io::Error::other(format!(
"PowerShell could not create the file for its owner only: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
let checked = sent.and_then(|()| sddl_of(path)).and_then(|sddl| still_foreign(&sddl, me));
if checked.is_err() {
let _ = std::fs::remove_file(path);
}
checked
}
/// `Err` naming the problem when the descriptor read back after restricting still isn't `me`'s
@@ -215,37 +492,18 @@ fn still_foreign(sddl: &str, me: &str) -> std::io::Result<()> {
}
}
/// What [`set_access_list`] restricts: a file, or a folder whose entries the files and folders
/// created in it inherit.
/// Set file `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected
/// from inheritance. Only the list is written, not the owner. `me` and the path reach PowerShell
/// through environment variables, never as script text.
#[cfg(windows)]
#[derive(Clone, Copy)]
enum Kind {
File,
Folder,
}
/// Set `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected from
/// inheritance; on a folder, what is created in it inherits the two entries. Only the list is
/// written, not the owner. `me` and the path reach PowerShell through environment variables, never
/// as script text.
#[cfg(windows)]
fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Result<()> {
fn set_access_list(path: &std::path::Path, me: &str) -> std::io::Result<()> {
// No double quotes: the command line would strip them.
const FILE: &str = "$s = New-Object Security.AccessControl.FileSecurity; \
const SCRIPT: &str = "$s = New-Object Security.AccessControl.FileSecurity; \
$s.SetSecurityDescriptorSddlForm('D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)', 'Access'); \
[IO.File]::SetAccessControl($env:CRAFT_ACL_PATH, $s)";
const FOLDER: &str = "$s = New-Object Security.AccessControl.DirectorySecurity; \
$s.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)', 'Access'); \
[IO.Directory]::SetAccessControl($env:CRAFT_ACL_PATH, $s)";
let script = match kind {
Kind::File => FILE,
Kind::Folder => FOLDER,
};
let out = system_tool(POWERSHELL)
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.env("CRAFT_ACL_PATH", path)
.env("CRAFT_ACL_USER", me)
.output()?;
let mut powershell = system_tool(POWERSHELL);
powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me);
let out = run(powershell)?;
if out.status.success() {
Ok(())
} else {
@@ -255,7 +513,9 @@ fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Res
#[cfg(windows)]
fn icacls(path: &std::path::Path, args: &[String]) -> std::io::Result<()> {
let out = system_tool(ICACLS).arg(path).args(args).output()?;
let mut icacls = system_tool(ICACLS);
icacls.arg(path).args(args);
let out = run(icacls)?;
if out.status.success() {
Ok(())
} else {
@@ -294,27 +554,30 @@ pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(Stri
);
// Bounded so the script's `[int]` and buffer stay small; a token file is far below this.
let max = max.min(1 << 20);
let out = system_tool(POWERSHELL)
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
.env("CRAFT_ACL_PATH", path)
.env("CRAFT_ACL_MAX", max.to_string())
.output()?;
let mut powershell = system_tool(POWERSHELL);
powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_MAX", max.to_string());
let out = run(powershell)?;
let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None };
read.ok_or_else(|| std::io::Error::other("PowerShell could not read the file with its owner and access list"))
}
/// The security descriptor of `path` as [`read_with_sddl`] writes it, read by name without opening
/// the file's contents, so it works on a file that is open for writing (an app restricts its
/// token file before writing the token through the handle it created).
/// token file before writing the token through the handle it created). A folder is read as a
/// folder, so its inherit-only entries are included (`IO`); a file's reading leaves them out.
#[cfg(windows)]
pub fn sddl_of(path: &std::path::Path) -> std::io::Result<String> {
const SCRIPT: &str = concat!(
// Stop: a failed read (a missing file) must end the script with an error, not print `O:`.
"$ErrorActionPreference = 'Stop'; $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @([IO.File]::GetAccessControl($env:CRAFT_ACL_PATH).GetSecurityDescriptorBinaryForm(), 0); ",
"$ErrorActionPreference = 'Stop'; $p = $env:CRAFT_ACL_PATH; \
if ([IO.Directory]::Exists($p)) { $sec = [IO.Directory]::GetAccessControl($p) } else { $sec = [IO.File]::GetAccessControl($p) }; \
$raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @($sec.GetSecurityDescriptorBinaryForm(), 0); ",
describe_raw!(),
"[Console]::Out.Write($sddl + [char]10)"
);
let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).output()?;
let mut powershell = system_tool(POWERSHELL);
powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path);
let out = run(powershell)?;
let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None };
read.map(|(sddl, _)| sddl).ok_or_else(|| std::io::Error::other("PowerShell could not read the file's owner and access list"))
}
@@ -410,6 +673,15 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
assert!(foreign_access("D:(A;;FA;;;SY)", ME).unwrap().contains("owner"));
}
/// An inherit-only entry doesn't apply to a file, but does to what's created in a folder.
#[test]
fn an_inherit_only_entry_counts_for_a_folder_only() {
let sddl = format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FR;;;BU)");
assert_eq!(foreign_access(&sddl, ME), None, "{sddl}");
assert!(foreign_folder_access(&sddl, ME).is_some_and(|p| p.contains("BU")), "{sddl}");
assert_eq!(foreign_folder_access(&format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FA;;;SY)"), ME), None);
}
/// A conditional entry can hold a `:` in a string; the access list doesn't end there, so the
/// entry after it is still checked.
#[test]
@@ -495,6 +767,159 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
let _ = std::fs::remove_dir_all(&dir);
}
/// A folder's inherit-only entries are read, and the folder check counts them: every file
/// created in the folder would get them.
#[cfg(windows)]
#[test]
fn a_folders_inherit_only_entries_are_read_and_refused() {
let dir = std::env::temp_dir().join(format!("craft-owner-only-inherit-only-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)(IO)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let sddl = sddl_of(&dir).unwrap();
assert!(sddl.contains(";IO;") && sddl.contains(";S-1-5-32-545)"), "the inherit-only entry for Users is read: {sddl}");
let me = current_user_sid().unwrap();
assert!(foreign_folder_access(&sddl, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}");
let _ = std::fs::remove_dir_all(&dir);
}
/// `create_private_dir` gives the folder its owner and list in the call that creates it, so in
/// a folder that lets Users read what's created in it, no step leaves the new folder with that
/// entry: the folder is moved to its name only after it was created with its own list. An
/// existing name and a missing parent are refused.
#[cfg(windows)]
#[test]
fn a_private_folder_has_its_list_from_the_start() {
let dir = std::env::temp_dir().join(format!("craft-owner-only-private-dir-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let me = current_user_sid().unwrap();
let private = dir.join("staging");
let made = create_private_dir(&private, &user());
assert!(made.is_ok(), "{made:?}");
let folder = sddl_of(&private).unwrap();
assert_eq!((section(&folder, "O:"), foreign_folder_access(&folder, &me)), (Some(me.as_str()), None), "{folder}");
assert!(!folder.contains(";S-1-5-32-545)") && !folder.contains(";BU)"), "Users must not inherit read access: {folder}");
let names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(names, ["staging"], "no folder is left under its own name");
let again = create_private_dir(&private, &user()).unwrap_err();
assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}");
let orphan = create_private_dir(&dir.join("missing").join("staging"), &user()).unwrap_err();
assert_eq!(orphan.kind(), std::io::ErrorKind::NotFound, "{orphan}");
assert!(!dir.join("missing").exists());
let _ = std::fs::remove_dir_all(&dir);
}
/// A file created by `create_private_file` in a folder that lets Users read what's in it is the
/// user's alone as soon as it exists, with nothing written to it yet; one created with contents
/// holds them, and an existing file is refused and left as it is.
#[cfg(windows)]
#[test]
fn a_private_file_is_private_from_the_start() {
let dir = std::env::temp_dir().join(format!("craft-owner-only-private-file-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let me = current_user_sid().unwrap();
let empty = dir.join("empty.token");
create_private_file(&empty, &user(), b"").unwrap();
let sddl = sddl_of(&empty).unwrap();
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
assert_eq!(std::fs::read(&empty).unwrap(), b"");
let file = dir.join("ctl.token");
create_private_file(&file, &user(), b"secret\n").unwrap();
let sddl = sddl_of(&file).unwrap();
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
assert_eq!(std::fs::read(&file).unwrap(), b"secret\n");
let again = create_private_file(&file, &user(), b"other\n").unwrap_err();
assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}");
assert_eq!(std::fs::read(&file).unwrap(), b"secret\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// A command that writes `ready` to its standard output and then reads its standard input until
/// it closes.
fn waiting_reader() -> std::process::Command {
#[cfg(windows)]
let command = {
let mut powershell = system_tool(POWERSHELL);
powershell.args([
"-NoProfile",
"-NonInteractive",
"-Command",
"[Console]::Out.Write('ready'); [Console]::Out.Flush(); $null = [Console]::In.ReadToEnd()",
]);
powershell
};
#[cfg(not(windows))]
let command = {
let mut sh = std::process::Command::new("sh");
sh.args(["-c", "printf ready; cat >/dev/null"]);
sh
};
command
}
/// A tool still running when the time is up is ended and exits. The time is up once the tool
/// has said it is waiting (a handshake, not a clock).
/// The same tool, given its input, exits by itself and nothing ends it.
#[test]
fn a_tool_that_does_not_finish_in_time_is_ended() {
let (keep, kept) = std::sync::mpsc::channel();
// The standard input stays open, so the tool waits until it is ended.
let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other);
match run_until(waiting_reader(), hold, |out| out == b"ready").unwrap() {
Ran::Ended { exited } => assert!(exited, "the tool was ended but is still running"),
Ran::Exited(out, _) => panic!("the tool exited by itself: {out:?}"),
}
drop(kept);
let close = |stdin: std::process::ChildStdin| {
drop(stdin);
Ok(())
};
match run_until(waiting_reader(), close, |_| false).unwrap() {
Ran::Exited(out, sent) => {
assert!(out.status.success(), "{out:?}");
assert_eq!(out.stdout, b"ready");
sent.unwrap();
}
Ran::Ended { .. } => panic!("the tool was ended"),
}
}
/// PowerShell that has created the file but not written it when the time is up is ended, the
/// call fails as timed out, and the file it created is removed; nothing took the name. A file
/// that was at the name before is another's, and it is left as it is whenever the time runs out.
#[cfg(windows)]
#[test]
fn a_private_file_whose_create_does_not_finish_in_time_is_removed() {
let dir = std::env::temp_dir().join(format!("craft-owner-only-limit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("ctl.token");
let entries = || std::fs::read_dir(&dir).unwrap().count();
let (keep, kept) = std::sync::mpsc::channel();
let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other);
// The time is up once the script has created its file and waits for the contents.
let late = create_private_file_until(&file, &user(), hold, |_| entries() > 0).unwrap_err();
drop(kept);
assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "{late}");
assert_eq!(entries(), 0, "the file PowerShell created is removed");
std::fs::write(&file, b"other\n").unwrap();
let (keep, kept) = std::sync::mpsc::channel();
let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other);
let refused = create_private_file_until(&file, &user(), hold, |_| true).unwrap_err();
drop(kept);
assert!(matches!(refused.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::AlreadyExists), "{refused}");
assert_eq!(std::fs::read(&file).unwrap(), b"other\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// A folder may give its user Modify but not Full control, so a file created there doesn't let
/// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list,
/// though, and the user's Full control on it then allows setting the owner.
+40 -3
View File
@@ -155,6 +155,19 @@ fn picked_color(rgb: [f64; 3]) -> Result<Capture, ScreenError> {
Ok(Capture::Color(rgb.map(|v| v as f32)))
}
/// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> {
use zbus::zvariant::Value;
match value {
Value::Structure(s) => match s.fields() {
[Value::F64(r), Value::F64(g), Value::F64(b)] => Some([*r, *g, *b]),
_ => None,
},
_ => None,
}
}
/// The most pixels one monitor image may hold (64 M); larger captures fail with `Failed`.
pub const MAX_PIXELS: usize = 64 * 1024 * 1024;
@@ -231,7 +244,10 @@ fn unpack_rgba(
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
mod backend {
use super::{Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, usable_scale};
use super::{
Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, portal_color,
usable_scale,
};
const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024;
/// Length limit of the property reads, in 32-bit units.
@@ -437,8 +453,7 @@ mod backend {
_ => return Err(failed("the desktop color picker could not sample this screen")),
}
let value = values.get("color").ok_or_else(|| failed("the desktop color picker returned no color"))?;
let (r, g, b): (f64, f64, f64) = value.try_clone().map_err(failed)?.try_into().map_err(|e: zbus::zvariant::Error| failed(e))?;
picked_color([r, g, b])
picked_color(portal_color(value).ok_or_else(|| failed("the desktop color picker returned no color"))?)
}
}
@@ -724,4 +739,26 @@ mod tests {
assert!(unpack_rgba(&[0; 3], 1, 1, 4, [0, 1, 2, 3], false, true).is_err());
assert!(checked_stride(1, 1, usize::MAX).is_err());
}
/// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array)
/// gives no colour; a `(ddd)` value gives its channels.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
#[test]
fn a_color_of_another_shape_is_not_read() {
use zbus::zvariant::Value;
let malformed = [
Value::from((0.5f64,)),
Value::from((0.5f64, 0.25f64)),
Value::from((0.5f64, 0.25f64, 1u32)),
Value::from(("red".to_string(), 0.25f64, 0.75f64)),
Value::from((0.5f64, 0.25f64, 0.75f64, 1.0f64)),
Value::from("red"),
Value::from(vec![0.5f64, 0.25, 0.75]),
];
for color in malformed {
let shape = color.value_signature().to_string();
assert_eq!(portal_color(&color), None, "{shape}");
}
assert_eq!(portal_color(&Value::from((0.5f64, 0.25f64, 0.75f64))), Some([0.5, 0.25, 0.75]));
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "craft-shared-vec"
description = "An ordered, indexed list whose clones share storage: a counted B-tree of shared blocks, so an edit copies only the blocks on its path, with share-aware byte counts for undo history."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[features]
default = []
# Serialize and Deserialize as a plain sequence, the same as `Vec<T>`.
serde = ["dep:serde"]
[dependencies]
serde = { workspace = true, optional = true }
[dev-dependencies]
craft-shared-vec = { path = ".", features = ["serde"] }
proptest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+89
View File
@@ -0,0 +1,89 @@
# Craft Shared Vec
`craft-shared-vec` provides `SharedVec<T>`, an ordered and indexed list whose clones share their
storage. It is meant for document trees that keep earlier versions in an undo history, where each
container holds its children in a list.
A tree that keeps its children as `Arc<Vec<Arc<Node>>>` and edits them with `Arc::make_mut` copies
the whole child list on every edit while an earlier version still holds it. On a layer of 100,000
objects, one edit copies 100,000 handles (800 KB on a 64-bit build), and an undo history that
charges each copy reaches a 512 MiB limit after about 670 edits. `SharedVec` copies only the blocks on
the path to the edited element.
## Structure
- Elements sit in leaves of up to 64; branches hold up to 64 children and the length of each.
Every node except the root holds at least 32, and every leaf is at the same depth.
- Every block sits behind an `Arc`. `clone` copies one handle. An edit copies each block on its path
that another list still holds.
- `get`, `set`, `get_mut`, `insert`, `remove`, `push` and `pop` take O(log n) and copy one leaf and
one branch per level. A removal that leaves a node too small also copies the neighbor it merges
with or takes elements from.
- `append`, `split_off`, `truncate`, `splice` and `retain` make their changes as single edits when
they remove or insert only a few elements. When they change more, they rebuild the branches from
the leaves: they keep every leaf they do not cut or change, and copy O(n / 64) handles. A rebuild
is chosen only when the single edits could copy as many blocks, so a loop that removes one element
at a time through `splice` or `retain` copies about one path per removal, as `remove` does.
- An empty list does not allocate.
- If `T::clone` panics during an edit, the list stays memory-safe, but which elements it holds
afterwards is unspecified. A panic in the iterator passed to `splice`, or in the closure passed to
`retain`, leaves the list as it was.
- `iter` is double-ended and exact-size; `fold` and `rfold` run a leaf slice at a time. `chunks`
returns the leaves as slices.
## Counting retained bytes
`list.bytes_not_in(&other)` returns the bytes of the blocks that `list` holds and `other` does not:
what keeping both versions costs over keeping `other` alone. A block's bytes are the sizes it asks
the allocator for (the `Arc` counts, its fields and each buffer's capacity); the allocator's own
rounding and bookkeeping are not included. It walks the two trees level by level
and leaves out every block that both hold, so after one edit it visits about one block per level.
`bytes_not_in_with(&other, key, payload)` adds the heap bytes of the elements that are new: an
element is counted when `other` holds no element with the same `key` (for an `Arc`, its address).
The unchanged elements of a copied leaf, and elements that an edit moved to another leaf, are not
counted.
`blocks()` lists every block with its id, kind, slot count and bytes, so a test can check which
blocks an edit copied.
## Serde
With the `serde` feature, a `SharedVec<T>` serializes and deserializes as a plain sequence, the same
as a `Vec<T>`. A field changed from `Vec<T>` to `SharedVec<T>` reads the same files and writes the
same bytes. The reader does not use the length an input announces for an allocation.
## Usage
```rust
use craft_shared_vec::SharedVec;
let before: SharedVec<u32> = (0..100_000).collect();
let mut after = before.clone();
after.set(50_000, 7).ok();
assert_eq!(before.get(50_000), Some(&50_000));
// One leaf and two branches are new.
assert!(after.bytes_not_in(&before) < 4_000);
```
## Benchmarks
`cargo run --release -p craft-shared-vec --example bench` times 2,000 edits, each beside a kept
snapshot, and iteration. On both sides the timer covers the edit alone; the snapshot is taken
before it starts and dropped after it stops. The bytes per edit are computed rather than measured:
the new vector's capacity times the element size for `Vec`, and `bytes_not_in` for `SharedVec`.
Results on a 128-core x86-64 Linux host (Rust 1.100.0), with `Arc<u64>` elements for the edits:
| Elements | `Arc<Vec<_>>` copied on write | `SharedVec` |
|---|---|---|
| 1,000 | 3.0 µs and 8,000 B per edit | 0.24 µs and 1,000 B per edit |
| 10,000 | 30 µs and 80,000 B per edit | 0.38 µs and 2,025 B per edit |
| 100,000 | 296 µs and 800,000 B per edit | 0.55 µs and 2,796 B per edit |
Removing one element of the 100,000 with `splice` or `retain` counts 2,808 B.
Summing 100,000 `u64` values takes 0.08 ns per element with `Vec::iter().fold`, 0.18 ns with
`SharedVec::iter().fold`, and 0.84 ns with a `for` loop over a `SharedVec` (0.39 ns over a `Vec`).
## License
MIT OR Apache-2.0, like the rest of the workspace.
+120
View File
@@ -0,0 +1,120 @@
//! Times single edits and iteration on `SharedVec` against a shared `Vec` copied on write.
//!
//! `cargo run --release -p craft-shared-vec --example bench`
//!
//! Each edit sets one element of a list that a snapshot still holds, as an undo history does: the
//! `Vec` is `Arc<Vec<_>>` changed with `Arc::make_mut`, which copies every element, and the
//! `SharedVec` copies the blocks on the edited path. On both sides the timer covers the edit alone:
//! the snapshot is taken before it starts and dropped after it stops. The bytes per edit are
//! computed, not measured: the new vector's capacity times the element size for `Vec`, and
//! `bytes_not_in` for `SharedVec`.
use std::hint::black_box;
use std::sync::Arc;
use std::time::{Duration, Instant};
use craft_shared_vec::SharedVec;
/// The element type: one handle, as a document tree's child list holds.
type Handle = Arc<u64>;
const EDITS: usize = 2_000;
fn per_edit(total: Duration) -> f64 {
total.as_secs_f64() * 1e9 / EDITS as f64
}
fn edits(count: usize) {
let values: Vec<Handle> = (0..count as u64).map(Arc::new).collect();
let step = count / EDITS + 1;
let mut vec = Arc::new(values.clone());
let mut vec_bytes = 0usize;
let mut vec_time = Duration::ZERO;
for edit in 0..EDITS {
let snapshot = Arc::clone(&vec);
let start = Instant::now();
let list = Arc::make_mut(&mut vec);
if let Some(slot) = list.get_mut(edit * step % count) {
*slot = Arc::new(edit as u64);
}
vec_time += start.elapsed();
vec_bytes += list.capacity() * size_of::<Handle>();
black_box(&snapshot);
}
let mut shared: SharedVec<Handle> = values.into();
let mut shared_bytes = 0usize;
let mut shared_time = Duration::ZERO;
for edit in 0..EDITS {
let snapshot = shared.clone();
let start = Instant::now();
let _ = shared.set(edit * step % count, Arc::new(edit as u64));
shared_time += start.elapsed();
shared_bytes += shared.bytes_not_in(&snapshot);
black_box(&snapshot);
}
// One element removed through the range edits, beside the list before it.
let mut spliced = shared.clone();
spliced.splice(count / 2..count / 2 + 1, []);
let mut retained = shared.clone();
let gone = retained.get(count / 2).cloned();
retained.retain(|value| gone.as_ref().is_none_or(|gone| !Arc::ptr_eq(value, gone)));
println!(
"{count:>7} elements | Vec {:>10.0} ns/edit {:>9} B/edit | SharedVec {:>7.0} ns/edit {:>6} B/edit | one-element splice {} B, retain {} B",
per_edit(vec_time),
vec_bytes / EDITS,
per_edit(shared_time),
shared_bytes / EDITS,
spliced.bytes_not_in(&shared),
retained.bytes_not_in(&shared),
);
}
fn iteration(count: usize) {
let values: Vec<u64> = (0..count as u64).collect();
let shared: SharedVec<u64> = values.iter().copied().collect();
let rounds = (20_000_000 / count).max(1);
let time = |f: &dyn Fn() -> u64| {
let start = Instant::now();
for _ in 0..rounds {
black_box(f());
}
start.elapsed().as_secs_f64() * 1e9 / (rounds * count) as f64
};
let vec_ns = time(&|| values.iter().fold(0u64, |sum, value| sum.wrapping_add(*value)));
let iter_ns = time(&|| shared.iter().fold(0u64, |sum, value| sum.wrapping_add(*value)));
let rev_ns = time(&|| shared.iter().rev().fold(0u64, |sum, value| sum.wrapping_add(*value)));
let chunk_ns = time(&|| shared.chunks().flatten().fold(0u64, |sum, value| sum.wrapping_add(*value)));
// A `for` loop takes one element at a time through `next`.
let vec_loop_ns = time(&|| {
let mut sum = 0u64;
for value in &values {
sum = sum.wrapping_add(black_box(*value));
}
sum
});
let loop_ns = time(&|| {
let mut sum = 0u64;
for value in &shared {
sum = sum.wrapping_add(black_box(*value));
}
sum
});
println!(
"{count:>7} elements | ns/element: fold Vec {vec_ns:.2}, SharedVec {iter_ns:.2}, reversed {rev_ns:.2}, chunks {chunk_ns:.2} | for loop Vec {vec_loop_ns:.2}, SharedVec {loop_ns:.2}"
);
}
fn main() {
println!("One edit beside a kept snapshot, {EDITS} edits:");
for count in [1_000, 10_000, 100_000] {
edits(count);
}
println!("Iteration:");
for count in [1_000, 10_000, 100_000] {
iteration(count);
}
}
+181
View File
@@ -0,0 +1,181 @@
//! Block identity and share-aware byte counts.
use std::collections::HashSet;
use std::hash::Hash;
use std::mem::size_of;
use crate::SharedVec;
use crate::node::{Branch, Node};
/// The identity of one block of a list. Two lists hold the same block exactly when they report the
/// same id for it, while both are alive.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BlockId(usize);
/// One block of a list, as [`SharedVec::blocks`] reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Block {
pub id: BlockId,
/// Whether the block holds elements (a leaf) rather than child blocks (a branch).
pub is_leaf: bool,
/// The number of elements (a leaf) or child blocks (a branch) it holds.
pub slots: usize,
/// The bytes of its allocation, as [`SharedVec::bytes_not_in`] counts them. Elements' own heap
/// allocations are not included.
pub bytes: usize,
}
/// The reference counts in front of an `Arc`'s value.
const ARC_HEADER: usize = 2 * size_of::<usize>();
fn node_bytes<T>(node: &Node<T>) -> usize {
match node {
Node::Leaf(leaf) => ARC_HEADER + size_of::<Vec<T>>() + leaf.capacity() * size_of::<T>(),
Node::Branch(branch) => {
ARC_HEADER + size_of::<Branch<T>>() + branch.lens.capacity() * size_of::<usize>() + branch.children.capacity() * size_of::<Node<T>>()
}
}
}
impl<T> SharedVec<T> {
/// Every block of the list, the root first and each block before its children. An empty list
/// has none.
pub fn blocks(&self) -> Vec<Block> {
let mut out = Vec::new();
let mut stack: Vec<&Node<T>> = self.root.iter().collect();
while let Some(node) = stack.pop() {
let (is_leaf, slots) = match node {
Node::Leaf(leaf) => (true, leaf.len()),
Node::Branch(branch) => {
stack.extend(branch.children.iter().rev());
(false, branch.children.len())
}
};
out.push(Block { id: BlockId(node.addr()), is_leaf, slots, bytes: node_bytes(node) });
}
out
}
/// The bytes of the blocks this list holds and `other` does not: what keeping both lists costs
/// over keeping `other` alone. A list compared with an empty list counts all of its blocks; a
/// list compared with a clone of itself counts none. Each block is counted once.
///
/// The count covers the blocks themselves (element storage, child handles and lengths), not
/// heap memory the elements own; [`bytes_not_in_with`](Self::bytes_not_in_with) adds that. A
/// block's bytes are the sizes it asks the allocator for: the `Arc` counts, the block's fields
/// and each buffer's capacity. The allocator's own rounding and bookkeeping are not included.
pub fn bytes_not_in(&self, other: &Self) -> usize {
let (total, _, _) = self.unshared(other);
total
}
/// [`bytes_not_in`](Self::bytes_not_in) plus the heap bytes of the elements this list holds and
/// `other` does not.
///
/// `key` names an element's heap allocation (for an `Arc`, its address through `Arc::as_ptr`),
/// and `payload` returns that allocation's bytes. An element is counted when it sits in a leaf
/// that `other` does not hold and `other` has no element with the same key in the leaves it
/// does not share with this list, so the unchanged elements of a copied leaf, and elements that
/// an edit moved to another leaf, are not counted. Each key is counted once.
///
/// The element count errs high: it never leaves out an element that `other` does not hold. An
/// element that `other` holds only in leaves both lists share, and that this list also holds in
/// a new leaf (a handle cloned into a second place, without removing it from the first), is
/// counted. Finding it would mean reading every leaf of `other`.
///
/// The walk visits only the blocks that the two lists do not share and their children, so after
/// one edit it costs about one block per level of the tree.
pub fn bytes_not_in_with<K, P>(&self, other: &Self, mut key: impl FnMut(&T) -> K, mut payload: P) -> usize
where
K: Hash + Eq,
P: FnMut(&T) -> usize,
{
let (mut total, ours, theirs) = self.unshared(other);
let theirs: HashSet<K> = theirs.iter().flat_map(|leaf| leaf.iter()).map(&mut key).collect();
let mut counted: HashSet<K> = HashSet::new();
for value in ours.iter().flat_map(|leaf| leaf.iter()) {
let id = key(value);
if !theirs.contains(&id) && counted.insert(id) {
total += payload(value);
}
}
total
}
/// The bytes of this list's blocks that `other` does not hold, those leaves of this list, and
/// the leaves of `other` that this list does not hold.
fn unshared<'a>(&'a self, other: &'a Self) -> (usize, Vec<&'a [T]>, Vec<&'a [T]>) {
let mut total = 0;
let mut ours: Vec<&Node<T>> = self.root.iter().collect();
let mut theirs: Vec<&Node<T>> = other.root.iter().collect();
let mut our_height = self.root.as_ref().map_or(0, Node::height);
let mut their_height = other.root.as_ref().map_or(0, Node::height);
let mut counted: HashSet<usize> = HashSet::new();
let mut our_leaves = Vec::new();
// Above the other tree's root, no block of ours can be one of its blocks.
while our_height > their_height {
ours = count_and_descend(ours, &HashSet::new(), &mut counted, &mut total, &mut our_leaves);
our_height -= 1;
}
while their_height > our_height {
theirs = descend(theirs, &HashSet::new());
their_height -= 1;
}
// Level by level, blocks both trees hold at the same height are shared with everything
// under them, and are left out on both sides. The last level holds the leaves.
let mut their_leaves = Vec::new();
while !ours.is_empty() {
let their_set: HashSet<usize> = theirs.iter().map(|node| node.addr()).collect();
let our_set: HashSet<usize> = ours.iter().map(|node| node.addr()).collect();
ours = count_and_descend(ours, &their_set, &mut counted, &mut total, &mut our_leaves);
if ours.is_empty() {
for node in &theirs {
if let Node::Leaf(leaf) = node
&& !our_set.contains(&node.addr())
{
their_leaves.push(leaf.as_slice());
}
}
}
theirs = descend(theirs, &our_set);
}
(total, our_leaves, their_leaves)
}
}
/// Counts each block of `level` that is not in `shared` (once each), keeps its leaves, and returns
/// the children of its branches.
fn count_and_descend<'a, T>(
level: Vec<&'a Node<T>>,
shared: &HashSet<usize>,
counted: &mut HashSet<usize>,
total: &mut usize,
leaves: &mut Vec<&'a [T]>,
) -> Vec<&'a Node<T>> {
let mut next = Vec::new();
for node in level {
let addr = node.addr();
if shared.contains(&addr) || !counted.insert(addr) {
continue;
}
*total += node_bytes(node);
match node {
Node::Leaf(leaf) => leaves.push(leaf.as_slice()),
Node::Branch(branch) => next.extend(branch.children.iter()),
}
}
next
}
/// The children of each block of `level` that is not in `shared`.
fn descend<'a, T>(level: Vec<&'a Node<T>>, shared: &HashSet<usize>) -> Vec<&'a Node<T>> {
let mut next = Vec::new();
for node in level {
if let Node::Branch(branch) = node
&& !shared.contains(&node.addr())
{
next.extend(branch.children.iter());
}
}
next
}
+212
View File
@@ -0,0 +1,212 @@
//! Iterators over a [`SharedVec`](crate::SharedVec).
use std::iter::FusedIterator;
use std::sync::Arc;
use crate::node::{self, Node};
/// The levels a walk keeps, the root's included, so it handles trees up to height `DEPTH - 1`.
/// The root holds at least 2 slots and every other node at least 32, so a tree of height 11 holds
/// at least 2 * 32^11 = 2^56 elements in 2^51 leaves, far more than fit in memory.
const DEPTH: usize = 12;
/// The leaves under a node in order, or in reverse order, without allocating.
struct LeafWalk<'a, T> {
/// The children still to visit at each level, from the root down; `levels[..depth]` are live.
levels: [std::slice::Iter<'a, Node<T>>; DEPTH],
depth: usize,
reverse: bool,
}
impl<'a, T> LeafWalk<'a, T> {
fn new(root: Option<&'a Node<T>>, reverse: bool) -> Self {
let mut levels: [std::slice::Iter<'a, Node<T>>; DEPTH] = std::array::from_fn(|_| <&[Node<T>]>::default().iter());
levels[0] = root.map_or(&[][..], std::slice::from_ref).iter();
LeafWalk { levels, depth: 1, reverse }
}
fn next_leaf(&mut self) -> Option<&'a [T]> {
loop {
let level = self.levels.get_mut(self.depth.checked_sub(1)?)?;
let node = if self.reverse { level.next_back() } else { level.next() };
match node {
None => self.depth -= 1,
Some(Node::Branch(branch)) => {
*self.levels.get_mut(self.depth)? = branch.children.iter();
self.depth += 1;
}
Some(Node::Leaf(leaf)) if leaf.is_empty() => {}
Some(Node::Leaf(leaf)) => return Some(leaf.as_slice()),
}
}
}
}
impl<T> Clone for LeafWalk<'_, T> {
fn clone(&self) -> Self {
LeafWalk { levels: self.levels.clone(), depth: self.depth, reverse: self.reverse }
}
}
/// The elements of a list in order, by reference. Made by [`SharedVec::iter`](crate::SharedVec::iter).
pub struct Iter<'a, T> {
root: Option<&'a Node<T>>,
/// The index of the next element from the front.
front: usize,
/// One past the index of the next element from the back.
back: usize,
/// The leaves after the one `front_leaf` came from.
front_leaves: LeafWalk<'a, T>,
/// The leaves before the one `back_leaf` came from.
back_leaves: LeafWalk<'a, T>,
/// The rest of the leaf that holds `front`.
front_leaf: std::slice::Iter<'a, T>,
/// The start of the leaf that holds `back - 1`, up to `back`.
back_leaf: std::slice::Iter<'a, T>,
}
impl<'a, T> Iter<'a, T> {
pub(crate) fn new(root: Option<&'a Node<T>>) -> Self {
Iter {
root,
front: 0,
back: root.map_or(0, Node::len),
front_leaves: LeafWalk::new(root, false),
back_leaves: LeafWalk::new(root, true),
front_leaf: <&[T]>::default().iter(),
back_leaf: <&[T]>::default().iter(),
}
}
}
impl<T> Clone for Iter<'_, T> {
fn clone(&self) -> Self {
Iter {
root: self.root,
front: self.front,
back: self.back,
front_leaves: self.front_leaves.clone(),
back_leaves: self.back_leaves.clone(),
front_leaf: self.front_leaf.clone(),
back_leaf: self.back_leaf.clone(),
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
if self.front >= self.back {
return None;
}
if self.front_leaf.len() == 0 {
self.front_leaf = self.front_leaves.next_leaf()?.iter();
}
let value = self.front_leaf.next()?;
self.front += 1;
Some(value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let left = self.back - self.front;
(left, Some(left))
}
/// Folds a leaf slice at a time, which runs as fast as folding a slice.
fn fold<B, F: FnMut(B, &'a T) -> B>(self, init: B, mut f: F) -> B {
match self.root {
Some(root) => root.fold_range(self.front, self.back, init, &mut f),
None => init,
}
}
}
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
/// Folds a leaf slice at a time from the back.
fn rfold<B, F: FnMut(B, &'a T) -> B>(self, init: B, mut f: F) -> B {
match self.root {
Some(root) => root.rfold_range(self.front, self.back, init, &mut f),
None => init,
}
}
fn next_back(&mut self) -> Option<&'a T> {
if self.front >= self.back {
return None;
}
if self.back_leaf.len() == 0 {
self.back_leaf = self.back_leaves.next_leaf()?.iter();
}
let value = self.back_leaf.next_back()?;
self.back -= 1;
Some(value)
}
}
impl<T> ExactSizeIterator for Iter<'_, T> {}
impl<T> FusedIterator for Iter<'_, T> {}
/// The blocks of a list as slices, in order. Made by [`SharedVec::chunks`](crate::SharedVec::chunks).
pub struct Chunks<'a, T> {
leaves: LeafWalk<'a, T>,
}
impl<'a, T> Chunks<'a, T> {
pub(crate) fn new(root: Option<&'a Node<T>>) -> Self {
Chunks { leaves: LeafWalk::new(root, false) }
}
}
impl<T> Clone for Chunks<'_, T> {
fn clone(&self) -> Self {
Chunks { leaves: self.leaves.clone() }
}
}
impl<'a, T> Iterator for Chunks<'a, T> {
type Item = &'a [T];
fn next(&mut self) -> Option<&'a [T]> {
self.leaves.next_leaf()
}
}
impl<T> FusedIterator for Chunks<'_, T> {}
/// The elements of a list in order, by value. Made by `SharedVec::into_iter`.
pub struct IntoIter<T> {
leaves: std::vec::IntoIter<Arc<Vec<T>>>,
current: std::vec::IntoIter<T>,
left: usize,
}
impl<T> IntoIter<T> {
pub(crate) fn new(leaves: Vec<Arc<Vec<T>>>) -> Self {
let left = leaves.iter().map(|leaf| leaf.len()).sum();
IntoIter { leaves: leaves.into_iter(), current: Vec::new().into_iter(), left }
}
}
impl<T: Clone> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
loop {
if let Some(value) = self.current.next() {
self.left -= 1;
return Some(value);
}
self.current = node::unwrap_vec(self.leaves.next()?).into_iter();
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.left, Some(self.left))
}
}
impl<T: Clone> ExactSizeIterator for IntoIter<T> {}
impl<T: Clone> FusedIterator for IntoIter<T> {}
+512
View File
@@ -0,0 +1,512 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
//! An ordered, indexed list whose clones share storage.
//!
//! [`SharedVec<T>`] holds its elements in blocks of up to 64, under a counted B-tree whose nodes
//! also hold up to 64 children. Blocks sit behind `Arc`, so cloning a list copies one handle, and an
//! edit to a list that shares its blocks with a clone copies only the blocks on the path to the
//! edited element: one leaf and one branch per level. A `Vec<T>` that is shared the same way
//! (`Arc<Vec<T>>` with `Arc::make_mut`) copies every element on each edit. An empty list does not
//! allocate.
//!
//! - **Reads:** [`get`](SharedVec::get), [`first`](SharedVec::first), [`last`](SharedVec::last),
//! [`iter`](SharedVec::iter) (double-ended) and [`chunks`](SharedVec::chunks) (the blocks as
//! slices).
//! - **Single edits**, O(log n): [`set`](SharedVec::set), [`get_mut`](SharedVec::get_mut),
//! [`insert`](SharedVec::insert), [`remove`](SharedVec::remove), [`push`](SharedVec::push) and
//! [`pop`](SharedVec::pop). A removal that leaves a block under half full also copies the
//! neighbor it merges with or takes elements from.
//! - **Range edits:** [`append`](SharedVec::append), [`split_off`](SharedVec::split_off),
//! [`truncate`](SharedVec::truncate), [`splice`](SharedVec::splice) and
//! [`retain`](SharedVec::retain). A range edit that removes or inserts only a few elements makes
//! them as single edits. One that changes more rebuilds the branches from the leaves: it copies
//! O(n / 64) handles and keeps every leaf it does not cut or change. A rebuild is chosen only when
//! the single edits could copy as many blocks, so the blocks a range edit copies stay within
//! about one path per element it removes or inserts.
//! - **Accounting:** [`bytes_not_in`](SharedVec::bytes_not_in) counts the bytes of the blocks one
//! list holds and another does not, for an undo history that keeps both;
//! [`bytes_not_in_with`](SharedVec::bytes_not_in_with) adds the heap bytes of the elements
//! that the other list does not hold.
//! - **Serde** (feature `serde`): a list reads and writes as a plain sequence, the same as a
//! `Vec<T>`.
//!
//! If `T::clone` panics during an edit, the list stays memory-safe, but which elements it holds
//! afterwards is unspecified. A panic in the iterator passed to [`splice`](SharedVec::splice), or
//! in the closure passed to [`retain`](SharedVec::retain), leaves the list as it was.
//!
//! ```
//! use craft_shared_vec::SharedVec;
//!
//! let before: SharedVec<u32> = (0..10_000).collect();
//! let mut after = before.clone();
//! assert_eq!(after.set(5_000, 7), Ok(5_000));
//! assert_eq!(before.get(5_000), Some(&5_000));
//! assert_eq!(after.get(5_000), Some(&7));
//! // Only the blocks on the edited path are new; the edit copied a few hundred bytes, not 40 KB.
//! assert!(after.bytes_not_in(&before) < 4_000);
//! ```
mod bytes;
mod iter;
mod node;
#[cfg(feature = "serde")]
mod serde_impl;
#[cfg(test)]
mod tests;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;
pub use bytes::{Block, BlockId};
pub use iter::{Chunks, IntoIter, Iter};
use node::{Leaves, Node};
/// An ordered, indexed list of `T` whose clones share their blocks (see the [crate] docs).
pub struct SharedVec<T> {
/// `None` for an empty list, so an empty list does not allocate.
root: Option<Node<T>>,
}
impl<T> SharedVec<T> {
/// An empty list. It does not allocate.
pub const fn new() -> Self {
SharedVec { root: None }
}
/// The number of elements.
pub fn len(&self) -> usize {
self.root.as_ref().map_or(0, Node::len)
}
/// Whether the list has no elements.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// The element at `index`, or `None` past the end.
pub fn get(&self, index: usize) -> Option<&T> {
self.root.as_ref()?.get(index)
}
/// The first element.
pub fn first(&self) -> Option<&T> {
self.get(0)
}
/// The last element.
pub fn last(&self) -> Option<&T> {
self.len().checked_sub(1).and_then(|last| self.get(last))
}
/// The elements in order. The iterator is double-ended and knows its length.
pub fn iter(&self) -> Iter<'_, T> {
Iter::new(self.root.as_ref())
}
/// The blocks as slices, in order. Together they hold every element once.
pub fn chunks(&self) -> Chunks<'_, T> {
Chunks::new(self.root.as_ref())
}
/// Whether the two lists are the same tree: a clone that neither list has edited since, or two
/// empty lists. Lists that compare equal need not be the same tree.
pub fn ptr_eq(&self, other: &Self) -> bool {
match (&self.root, &other.root) {
(None, None) => true,
(Some(ours), Some(theirs)) => ours.addr() == theirs.addr(),
_ => false,
}
}
/// Removes every element.
pub fn clear(&mut self) {
self.root = None;
}
/// Whether `count` single edits copy no more blocks than a rebuild of the branches does. A
/// single edit copies at most one block per level; a tree of `len` elements has at most about
/// `len / (MIN * MIN)` branches, since every node other than the root holds at least `MIN`.
fn few(&self, count: usize) -> bool {
let levels = self.root.as_ref().map_or(0, Node::height) + 1;
count.saturating_mul(levels) <= self.len() / (node::MIN * node::MIN)
}
}
impl<T: Clone> SharedVec<T> {
/// The element at `index`, to change in place, or `None` past the end. The blocks on its path
/// that the list shares with a clone are copied first.
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
self.root.as_mut()?.get_mut(index)
}
/// Replaces the element at `index` and returns the old one. Past the end, returns `value` as
/// the error and leaves the list unchanged.
pub fn set(&mut self, index: usize, value: T) -> Result<T, T> {
match self.get_mut(index) {
Some(slot) => Ok(std::mem::replace(slot, value)),
None => Err(value),
}
}
/// Inserts `value` at `index`, moving the elements after it one place on. An `index` past the
/// length returns `value` as the error and leaves the list unchanged.
pub fn insert(&mut self, index: usize, value: T) -> Result<(), T> {
if index > self.len() {
return Err(value);
}
let Some(root) = self.root.as_mut() else {
self.root = Some(Node::Leaf(Arc::new(vec![value])));
return Ok(());
};
let split = root.insert(index, value);
if let Some(right) = split
&& let Some(left) = self.root.take()
{
self.root = Some(Node::Branch(Arc::new(node::Branch::new(vec![left, right]))));
}
Ok(())
}
/// Removes and returns the element at `index`, or `None` past the end.
pub fn remove(&mut self, index: usize) -> Option<T> {
let removed = self.root.as_mut()?.remove(index)?;
self.collapse_root();
Some(removed)
}
/// Appends `value` at the end.
pub fn push(&mut self, value: T) {
let end = self.len();
// An insertion at the length always succeeds.
let _ = self.insert(end, value);
}
/// Removes and returns the last element.
pub fn pop(&mut self) -> Option<T> {
let last = self.len().checked_sub(1)?;
self.remove(last)
}
/// Moves every element of `other` onto the end of this list, leaving `other` empty. Both lists'
/// blocks are kept, except where a short block at the join has to merge with its neighbor.
pub fn append(&mut self, other: &mut Self) {
if other.is_empty() {
return;
}
if self.is_empty() {
std::mem::swap(self, other);
return;
}
if self.few(other.len()) {
for value in std::mem::take(other) {
self.push(value);
}
return;
}
if other.few(self.len()) {
let front: Vec<T> = std::mem::take(self).into();
for value in front.into_iter().rev() {
let _ = other.insert(0, value);
}
std::mem::swap(self, other);
return;
}
let mut leaves = self.take_leaves();
leaves.extend(other.take_leaves());
self.root = node::build(leaves);
}
/// Splits the list at `at`: this list keeps `[0, at)` and the rest is returned. An `at` past the
/// length returns an empty list.
pub fn split_off(&mut self, at: usize) -> Self {
let len = self.len();
if at >= len {
return SharedVec::new();
}
if self.few(len - at) {
let mut back = Vec::with_capacity(len - at);
for _ in at..len {
back.extend(self.pop());
}
back.reverse();
return back.into();
}
if self.few(at) {
let mut front = Vec::with_capacity(at);
for _ in 0..at {
front.extend(self.remove(0));
}
return std::mem::replace(self, front.into());
}
let (front, back) = cut(self.take_leaves(), at);
self.root = node::build(front);
SharedVec { root: node::build(back) }
}
/// Keeps the first `len` elements and drops the rest. A `len` at or past the length leaves the
/// list unchanged.
pub fn truncate(&mut self, len: usize) {
let old = self.len();
if len >= old {
return;
}
if self.few(old - len) {
for _ in len..old {
self.pop();
}
return;
}
let (front, _) = cut(self.take_leaves(), len);
self.root = node::build(front);
}
/// Replaces the elements in `range` with `replace_with` and returns the removed elements in
/// order. The range is clamped to the list: a start past the end inserts at the end.
pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Vec<T>
where
R: RangeBounds<usize>,
I: IntoIterator<Item = T>,
{
let len = self.len();
let start = match range.start_bound() {
Bound::Included(&start) => start,
Bound::Excluded(&start) => start.saturating_add(1),
Bound::Unbounded => 0,
}
.min(len);
let end = match range.end_bound() {
Bound::Included(&end) => end.saturating_add(1),
Bound::Excluded(&end) => end,
Bound::Unbounded => len,
}
.clamp(start, len);
// The new elements are read before the list changes, so a panic while reading them leaves
// the list as it was.
let inserted: Vec<T> = replace_with.into_iter().collect();
if self.few((end - start).saturating_add(inserted.len())) {
let mut removed = Vec::with_capacity(end - start);
for _ in start..end {
removed.extend(self.remove(start));
}
for (offset, value) in inserted.into_iter().enumerate() {
let _ = self.insert(start + offset, value);
}
return removed;
}
let (mut leaves, rest) = cut(self.take_leaves(), start);
let (middle, back) = cut(rest, end - start);
let removed: Vec<T> = middle.into_iter().flat_map(node::unwrap_vec).collect();
node::chunk(inserted, &mut leaves);
leaves.extend(back);
self.root = node::build(leaves);
removed
}
/// Keeps the elements for which `keep` returns `true`, in order. `keep` sees each element once,
/// in order, before the list changes. Blocks that keep every element are kept as they are.
pub fn retain<F: FnMut(&T) -> bool>(&mut self, mut keep: F) {
let dropped: Vec<usize> = self.iter().enumerate().filter(|(_, value)| !keep(value)).map(|(index, _)| index).collect();
if dropped.is_empty() {
return;
}
if self.few(dropped.len()) {
for &index in dropped.iter().rev() {
self.remove(index);
}
return;
}
let mut dropped = dropped.into_iter().peekable();
let mut leaves = Vec::new();
let mut start = 0;
for leaf in self.leaves() {
let end = start + leaf.len();
if dropped.peek().is_some_and(|&index| index < end) {
let mut kept = Vec::with_capacity(leaf.len());
for (offset, value) in leaf.iter().enumerate() {
if dropped.next_if_eq(&(start + offset)).is_none() {
kept.push(value.clone());
}
}
if !kept.is_empty() {
leaves.push(Arc::new(kept));
}
} else {
leaves.push(leaf);
}
start = end;
}
// Drop the old tree first, so leaves no other list holds can be merged without a copy.
self.root = None;
self.root = node::build(leaves);
}
/// Copies the elements into a `Vec`.
pub fn to_vec(&self) -> Vec<T> {
let mut out = Vec::with_capacity(self.len());
for chunk in self.chunks() {
out.extend_from_slice(chunk);
}
out
}
fn leaves(&self) -> Vec<Arc<Vec<T>>> {
let mut leaves = Vec::with_capacity(self.len().div_ceil(node::MIN));
if let Some(root) = &self.root {
root.collect_leaves(&mut leaves);
}
leaves
}
/// Empties the list and returns its leaves. A leaf that no clone holds is then held only by the
/// returned run, so it can be merged or cut without a copy.
fn take_leaves(&mut self) -> Vec<Arc<Vec<T>>> {
let mut leaves = Vec::with_capacity(self.len().div_ceil(node::MIN));
if let Some(root) = self.root.take() {
root.collect_leaves(&mut leaves);
}
leaves
}
/// Replaces a root branch that has one child with that child, and an empty root with `None`.
fn collapse_root(&mut self) {
loop {
let only = match &self.root {
Some(Node::Branch(branch)) if branch.children.len() == 1 => branch.children.first().cloned(),
_ => None,
};
match only {
Some(child) => self.root = Some(child),
None => break,
}
}
if self.is_empty() {
self.root = None;
}
}
}
impl<T> Clone for SharedVec<T> {
/// Copies one handle; the clone shares every block.
fn clone(&self) -> Self {
SharedVec { root: self.root.clone() }
}
}
impl<T> Default for SharedVec<T> {
fn default() -> Self {
SharedVec::new()
}
}
impl<T: fmt::Debug> fmt::Debug for SharedVec<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<T: PartialEq> PartialEq for SharedVec<T> {
fn eq(&self, other: &Self) -> bool {
self.len() == other.len() && self.iter().eq(other.iter())
}
}
impl<T: Eq> Eq for SharedVec<T> {}
impl<T: PartialOrd> PartialOrd for SharedVec<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.iter().partial_cmp(other.iter())
}
}
impl<T: Ord> Ord for SharedVec<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.iter().cmp(other.iter())
}
}
impl<T: Hash> Hash for SharedVec<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.len().hash(state);
for value in self {
value.hash(state);
}
}
}
impl<T: Clone> FromIterator<T> for SharedVec<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut leaves = Vec::new();
node::chunk(iter, &mut leaves);
SharedVec { root: node::build(leaves) }
}
}
impl<T: Clone> Extend<T> for SharedVec<T> {
/// Pushes each element in turn, so the list keeps every block it had.
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
for value in iter {
self.push(value);
}
}
}
impl<T: Clone> From<Vec<T>> for SharedVec<T> {
fn from(values: Vec<T>) -> Self {
values.into_iter().collect()
}
}
impl<T: Clone> From<&[T]> for SharedVec<T> {
fn from(values: &[T]) -> Self {
values.iter().cloned().collect()
}
}
impl<T: Clone> From<SharedVec<T>> for Vec<T> {
fn from(list: SharedVec<T>) -> Self {
list.into_iter().collect()
}
}
impl<'a, T> IntoIterator for &'a SharedVec<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<T: Clone> IntoIterator for SharedVec<T> {
type Item = T;
type IntoIter = IntoIter<T>;
/// Moves the elements out of blocks no other list holds, and clones them out of shared ones.
fn into_iter(mut self) -> IntoIter<T> {
IntoIter::new(self.take_leaves())
}
}
/// The leaves before `at` and from `at` on, cutting the leaf that holds `at` in two.
fn cut<T: Clone>(leaves: Leaves<T>, at: usize) -> (Leaves<T>, Leaves<T>) {
let mut front = Vec::new();
let mut back = Vec::new();
let mut start = 0;
for leaf in leaves {
let end = start + leaf.len();
if end <= at {
front.push(leaf);
} else if start >= at {
back.push(leaf);
} else {
let mut head = node::unwrap_vec(leaf);
let tail = head.split_off(at - start);
front.push(Arc::new(head));
back.push(Arc::new(tail));
}
start = end;
}
(front, back)
}
+472
View File
@@ -0,0 +1,472 @@
//! The counted B-tree under [`SharedVec`](crate::SharedVec).
//!
//! Every leaf is at the same depth. A leaf holds up to [`MAX`] elements and a branch up to [`MAX`]
//! children, each with its length. Every node except the root holds at least [`MIN`]. Blocks sit
//! behind `Arc`, so a clone of the tree shares all of them, and an edit copies only the blocks on
//! its path (`Arc::make_mut`).
use std::sync::Arc;
/// The most elements in a leaf, and the most children in a branch.
pub(crate) const MAX: usize = 64;
/// The fewest elements or children in a node other than the root.
pub(crate) const MIN: usize = MAX / 2;
/// A run of leaves in order.
pub(crate) type Leaves<T> = Vec<Arc<Vec<T>>>;
pub(crate) enum Node<T> {
Leaf(Arc<Vec<T>>),
Branch(Arc<Branch<T>>),
}
impl<T> Clone for Node<T> {
fn clone(&self) -> Self {
match self {
Node::Leaf(leaf) => Node::Leaf(Arc::clone(leaf)),
Node::Branch(branch) => Node::Branch(Arc::clone(branch)),
}
}
}
pub(crate) struct Branch<T> {
/// The number of elements under this branch.
pub(crate) len: usize,
/// The number of elements under each child.
pub(crate) lens: Vec<usize>,
pub(crate) children: Vec<Node<T>>,
}
impl<T> Clone for Branch<T> {
fn clone(&self) -> Self {
Branch { len: self.len, lens: self.lens.clone(), children: self.children.clone() }
}
}
impl<T> Branch<T> {
pub(crate) fn new(children: Vec<Node<T>>) -> Self {
let lens: Vec<usize> = children.iter().map(Node::len).collect();
Branch { len: lens.iter().sum(), lens, children }
}
}
impl<T> Node<T> {
/// The number of elements under this node.
pub(crate) fn len(&self) -> usize {
match self {
Node::Leaf(leaf) => leaf.len(),
Node::Branch(branch) => branch.len,
}
}
/// The number of elements (a leaf) or children (a branch) in this node.
fn slots(&self) -> usize {
match self {
Node::Leaf(leaf) => leaf.len(),
Node::Branch(branch) => branch.children.len(),
}
}
/// The address of this node's block, which two trees share exactly when they hold the same block.
pub(crate) fn addr(&self) -> usize {
match self {
Node::Leaf(leaf) => Arc::as_ptr(leaf).cast::<()>() as usize,
Node::Branch(branch) => Arc::as_ptr(branch).cast::<()>() as usize,
}
}
/// The number of levels below this node: 0 for a leaf.
pub(crate) fn height(&self) -> usize {
let mut height = 0;
let mut node = self;
while let Node::Branch(branch) = node {
let Some(first) = branch.children.first() else { break };
node = first;
height += 1;
}
height
}
pub(crate) fn get(&self, mut index: usize) -> Option<&T> {
let mut node = self;
loop {
match node {
Node::Leaf(leaf) => return leaf.get(index),
Node::Branch(branch) => {
let (child, rest) = locate(&branch.lens, index)?;
node = branch.children.get(child)?;
index = rest;
}
}
}
}
/// Folds the elements `[start, end)` under this node in order, a leaf slice at a time.
pub(crate) fn fold_range<'a, B, F: FnMut(B, &'a T) -> B>(&'a self, start: usize, end: usize, acc: B, f: &mut F) -> B {
match self {
Node::Leaf(leaf) => leaf.get(start..end.min(leaf.len())).unwrap_or_default().iter().fold(acc, f),
Node::Branch(branch) => {
let mut acc = acc;
let mut offset = 0;
for (child, &len) in branch.children.iter().zip(&branch.lens) {
if offset >= end {
break;
}
if offset + len > start {
acc = child.fold_range(start.saturating_sub(offset), (end - offset).min(len), acc, f);
}
offset += len;
}
acc
}
}
}
/// Folds the elements `[start, end)` under this node from the back, a leaf slice at a time.
pub(crate) fn rfold_range<'a, B, F: FnMut(B, &'a T) -> B>(&'a self, start: usize, end: usize, acc: B, f: &mut F) -> B {
match self {
Node::Leaf(leaf) => leaf.get(start..end.min(leaf.len())).unwrap_or_default().iter().rfold(acc, f),
Node::Branch(branch) => {
let mut acc = acc;
let mut offset = branch.len;
for (child, &len) in branch.children.iter().zip(&branch.lens).rev() {
offset -= len;
if offset + len <= start {
break;
}
if offset < end {
acc = child.rfold_range(start.saturating_sub(offset), (end - offset).min(len), acc, f);
}
}
acc
}
}
}
/// Appends every leaf under this node, in order.
pub(crate) fn collect_leaves(&self, out: &mut Vec<Arc<Vec<T>>>) {
match self {
Node::Leaf(leaf) => {
if !leaf.is_empty() {
out.push(Arc::clone(leaf));
}
}
Node::Branch(branch) => {
for child in &branch.children {
child.collect_leaves(out);
}
}
}
}
}
impl<T: Clone> Node<T> {
pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut T> {
match self {
Node::Leaf(leaf) => {
if index >= leaf.len() {
return None;
}
Arc::make_mut(leaf).get_mut(index)
}
Node::Branch(branch) => {
let (child, rest) = locate(&branch.lens, index)?;
Arc::make_mut(branch).children.get_mut(child)?.get_mut(rest)
}
}
}
/// Inserts `value` at `index` (at most this node's length). Returns the new right sibling when
/// the node had to split.
pub(crate) fn insert(&mut self, index: usize, value: T) -> Option<Node<T>> {
match self {
Node::Leaf(leaf) => {
// Grow towards one past a full leaf, never past it.
let target = (leaf.len() * 2).clamp(4, MAX + 1).max(leaf.len() + 1);
if Arc::get_mut(leaf).is_none() {
// A shared leaf is copied once, straight into a block with room for the new element.
let mut copy = Vec::with_capacity(target);
copy.extend_from_slice(leaf);
*leaf = Arc::new(copy);
}
let leaf = Arc::make_mut(leaf);
if leaf.len() == leaf.capacity() {
leaf.reserve_exact(target - leaf.len());
}
leaf.insert(index.min(leaf.len()), value);
if leaf.len() > MAX {
let right = leaf.split_off(leaf.len() / 2);
return Some(Node::Leaf(Arc::new(right)));
}
None
}
Node::Branch(branch) => {
let branch = Arc::make_mut(branch);
let (child, rest) = locate_insert(&branch.lens, index);
let split = branch.children.get_mut(child)?.insert(rest, value);
branch.len += 1;
if let Some(right) = split {
if let Some(left) = branch.children.get(child) {
let left_len = left.len();
if let Some(slot) = branch.lens.get_mut(child) {
*slot = left_len;
}
}
branch.lens.insert(child + 1, right.len());
branch.children.insert(child + 1, right);
} else if let Some(slot) = branch.lens.get_mut(child) {
*slot += 1;
}
if branch.children.len() > MAX {
let half = branch.children.len() / 2;
let children = branch.children.split_off(half);
let lens = branch.lens.split_off(half);
let moved: usize = lens.iter().sum();
branch.len -= moved;
return Some(Node::Branch(Arc::new(Branch { len: moved, lens, children })));
}
None
}
}
}
/// Removes the element at `index`. A child left below [`MIN`] is merged with a sibling or
/// takes some of its slots; this node itself may be left below [`MIN`] for its parent to fix.
pub(crate) fn remove(&mut self, index: usize) -> Option<T> {
match self {
Node::Leaf(leaf) => {
if index >= leaf.len() {
return None;
}
Some(Arc::make_mut(leaf).remove(index))
}
Node::Branch(branch) => {
let (child, rest) = locate(&branch.lens, index)?;
let branch = Arc::make_mut(branch);
let removed = branch.children.get_mut(child)?.remove(rest)?;
branch.len -= 1;
if let Some(slot) = branch.lens.get_mut(child) {
*slot -= 1;
}
if branch.children.get(child).is_some_and(|c| c.slots() < MIN) {
rebalance(branch, child);
}
Some(removed)
}
}
}
}
/// The child that holds `index`, and the position of `index` in it.
fn locate(lens: &[usize], mut index: usize) -> Option<(usize, usize)> {
for (child, &len) in lens.iter().enumerate() {
if index < len {
return Some((child, index));
}
index -= len;
}
None
}
/// The child an insertion at `index` goes into: like [`locate`], except that the end of the last
/// child belongs to it.
fn locate_insert(lens: &[usize], mut index: usize) -> (usize, usize) {
let last = lens.len().saturating_sub(1);
for (child, &len) in lens.iter().enumerate() {
if index < len || child == last {
return (child, index.min(len));
}
index -= len;
}
(0, 0)
}
/// Brings `branch.children[child]` back to at least [`MIN`] slots by merging it with a neighbor,
/// or, when both together are too many for one node, by sharing their slots evenly.
fn rebalance<T: Clone>(branch: &mut Branch<T>, child: usize) {
if branch.children.len() < 2 {
return;
}
let left = if child > 0 { child - 1 } else { child };
let right = left + 1;
if right >= branch.children.len() {
return;
}
let right_node = branch.children.remove(right);
branch.lens.remove(right);
let Some(left_node) = branch.children.get_mut(left) else { return };
let spill = join_pair(left_node, right_node);
let left_len = left_node.len();
if let Some(slot) = branch.lens.get_mut(left) {
*slot = left_len;
}
if let Some(spill) = spill {
branch.lens.insert(right, spill.len());
branch.children.insert(right, spill);
}
}
/// Moves the slots of `right` onto the end of `left`, two nodes of the same height. When that is
/// more than one node holds, splits the slots in half and returns the right half.
fn join_pair<T: Clone>(left: &mut Node<T>, right: Node<T>) -> Option<Node<T>> {
match (left, right) {
(Node::Leaf(left), Node::Leaf(right)) => {
let left = Arc::make_mut(left);
left.extend(unwrap_vec(right));
(left.len() > MAX).then(|| {
let half = left.len() / 2;
Node::Leaf(Arc::new(left.split_off(half)))
})
}
(Node::Branch(left), Node::Branch(right)) => {
let left = Arc::make_mut(left);
let right = Arc::try_unwrap(right).unwrap_or_else(|shared| (*shared).clone());
left.len += right.len;
left.lens.extend(right.lens);
left.children.extend(right.children);
(left.children.len() > MAX).then(|| {
let half = left.children.len() / 2;
let children = left.children.split_off(half);
let lens = left.lens.split_off(half);
let moved: usize = lens.iter().sum();
left.len -= moved;
Node::Branch(Arc::new(Branch { len: moved, lens, children }))
})
}
// The two heights always match; a mismatch keeps both nodes as they are.
(_, right) => Some(right),
}
}
/// The elements of a leaf: moved out when no other tree holds it, cloned otherwise.
pub(crate) fn unwrap_vec<T: Clone>(leaf: Arc<Vec<T>>) -> Vec<T> {
Arc::try_unwrap(leaf).unwrap_or_else(|shared| (*shared).clone())
}
/// Brings a run of leaves to [`MIN`]..=[`MAX`] elements each, keeping (sharing) every leaf that is
/// already in range and not next to one that is too small.
fn normalize<T: Clone>(leaves: Vec<Arc<Vec<T>>>) -> Vec<Arc<Vec<T>>> {
let mut out: Vec<Arc<Vec<T>>> = Vec::with_capacity(leaves.len());
let mut pending: Vec<T> = Vec::new();
for leaf in leaves {
if leaf.is_empty() {
continue;
}
if pending.is_empty() && (MIN..=MAX).contains(&leaf.len()) {
out.push(leaf);
continue;
}
pending.extend(unwrap_vec(leaf));
while pending.len() > MAX + MIN {
let rest = pending.split_off(MAX);
out.push(Arc::new(std::mem::replace(&mut pending, rest)));
}
if pending.len() >= MIN {
push_split(&mut out, std::mem::take(&mut pending));
}
}
if !pending.is_empty() {
match out.pop() {
Some(last) => {
let mut merged = unwrap_vec(last);
merged.extend(pending);
push_split(&mut out, merged);
}
None => out.push(Arc::new(pending)),
}
}
out
}
/// Pushes `elements` (at most `MAX + MIN` of them, at least `MIN` unless it is the only leaf) as one
/// leaf, or as two halves when that is more than a leaf holds.
fn push_split<T>(out: &mut Vec<Arc<Vec<T>>>, mut elements: Vec<T>) {
if elements.len() > MAX {
let right = elements.split_off(elements.len() / 2);
out.push(Arc::new(elements));
out.push(Arc::new(right));
} else {
out.push(Arc::new(elements));
}
}
/// Builds a balanced tree from a run of leaves in order, or `None` when they hold no element.
pub(crate) fn build<T: Clone>(leaves: Vec<Arc<Vec<T>>>) -> Option<Node<T>> {
let mut level: Vec<Node<T>> = normalize(leaves).into_iter().map(Node::Leaf).collect();
while level.len() > 1 {
let count = level.len();
let groups = count.div_ceil(MAX);
let mut next = Vec::with_capacity(groups);
let mut nodes = level.into_iter();
for group in 0..groups {
let size = count / groups + usize::from(group < count % groups);
next.push(Node::Branch(Arc::new(Branch::new(nodes.by_ref().take(size).collect()))));
}
level = next;
}
level.pop()
}
/// Checks the tree's shape: lengths add up, every node except the root holds [`MIN`]..=[`MAX`]
/// slots, a root branch holds at least two children, every leaf is at the same depth, and an empty
/// list has no root.
#[cfg(test)]
pub(crate) fn check<T>(root: &Option<Node<T>>) -> Result<(), String> {
fn walk<T>(node: &Node<T>, is_root: bool, depth: usize, leaf_depth: &mut Option<usize>) -> Result<usize, String> {
let slots = node.slots();
let low = match (is_root, node) {
(true, Node::Leaf(_)) => 0,
(true, Node::Branch(_)) => 2,
(false, _) => MIN,
};
if slots < low || slots > MAX {
return Err(format!("{slots} slots at depth {depth}"));
}
match node {
Node::Leaf(leaf) => {
if leaf_depth.get_or_insert(depth) != &depth {
return Err(format!("leaf at depth {depth}, others at {leaf_depth:?}"));
}
Ok(leaf.len())
}
Node::Branch(branch) => {
if branch.lens.len() != branch.children.len() {
return Err("lens and children differ in count".into());
}
let mut sum = 0;
for (child, &len) in branch.children.iter().zip(&branch.lens) {
let actual = walk(child, false, depth + 1, leaf_depth)?;
if actual != len {
return Err(format!("child length {actual}, recorded {len}"));
}
sum += actual;
}
if sum != branch.len {
return Err(format!("branch length {}, children hold {sum}", branch.len));
}
Ok(sum)
}
}
}
match root {
Some(root) if root.len() == 0 => Err("an empty root".into()),
Some(root) => walk(root, true, 0, &mut None).map(|_| ()),
None => Ok(()),
}
}
/// Cuts a run of elements into full leaves.
pub(crate) fn chunk<T, I: IntoIterator<Item = T>>(items: I, out: &mut Vec<Arc<Vec<T>>>) {
let mut items = items.into_iter();
loop {
let leaf: Vec<T> = items.by_ref().take(MAX).collect();
if leaf.is_empty() {
break;
}
let full = leaf.len() == MAX;
out.push(Arc::new(leaf));
if !full {
break;
}
}
}
+50
View File
@@ -0,0 +1,50 @@
//! A list reads and writes as a plain sequence, the same as `Vec<T>`.
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use serde::de::{SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::SharedVec;
use crate::node::{self, MAX};
impl<T: Serialize> Serialize for SharedVec<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
impl<'de, T: Deserialize<'de> + Clone> Deserialize<'de> for SharedVec<T> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_seq(SeqVisitor(PhantomData))
}
}
struct SeqVisitor<T>(PhantomData<T>);
impl<'de, T: Deserialize<'de> + Clone> Visitor<'de> for SeqVisitor<T> {
type Value = SharedVec<T>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a sequence")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<SharedVec<T>, A::Error> {
// The length the input announces is not used for an allocation: the elements go into
// blocks as they arrive.
let mut leaves = Vec::new();
let mut leaf = Vec::with_capacity(MAX);
while let Some(value) = seq.next_element()? {
leaf.push(value);
if leaf.len() == MAX {
leaves.push(Arc::new(std::mem::replace(&mut leaf, Vec::with_capacity(MAX))));
}
}
if !leaf.is_empty() {
leaves.push(Arc::new(leaf));
}
Ok(SharedVec { root: node::build(leaves) })
}
}
+224
View File
@@ -0,0 +1,224 @@
//! The tree's shape after every operation, against `Vec` as the model.
use proptest::prelude::*;
use crate::SharedVec;
use crate::node::{self, MAX};
#[derive(Clone, Debug)]
enum Op {
Push(u32),
Pop,
Insert(usize, u32),
Remove(usize),
Set(usize, u32),
SplitOffAndAppend(usize),
Truncate(usize),
Splice(usize, usize, Vec<u32>),
Retain(u32),
/// Removes the element at an index through `retain`.
RetainOne(usize),
/// Splits off a few elements from the front (`true`) or the back, and appends the rest again.
SplitOffFew(usize, bool),
/// Truncates a few elements.
TruncateFew(usize),
AppendClone,
Snapshot,
Clear,
}
fn op() -> impl Strategy<Value = Op> {
prop_oneof![
4 => any::<u32>().prop_map(Op::Push),
2 => Just(Op::Pop),
6 => (any::<usize>(), any::<u32>()).prop_map(|(at, value)| Op::Insert(at, value)),
6 => any::<usize>().prop_map(Op::Remove),
3 => (any::<usize>(), any::<u32>()).prop_map(|(at, value)| Op::Set(at, value)),
1 => any::<usize>().prop_map(Op::SplitOffAndAppend),
1 => any::<usize>().prop_map(Op::Truncate),
2 => (any::<usize>(), 0..200usize, prop::collection::vec(any::<u32>(), 0..200)).prop_map(|(at, len, with)| Op::Splice(at, len, with)),
1 => (2..40u32).prop_map(Op::Retain),
// Range edits of a few elements, which a large enough list makes as single edits.
2 => (any::<usize>(), 0..3usize, prop::collection::vec(any::<u32>(), 0..3)).prop_map(|(at, len, with)| Op::Splice(at, len, with)),
2 => any::<usize>().prop_map(Op::RetainOne),
2 => (0..3usize, any::<bool>()).prop_map(|(count, front)| Op::SplitOffFew(count, front)),
1 => (0..3usize).prop_map(Op::TruncateFew),
1 => Just(Op::AppendClone),
2 => Just(Op::Snapshot),
1 => Just(Op::Clear),
]
}
/// Runs `ops` on a list and on a `Vec`, checking the shape and the contents after each, and that
/// every snapshot taken along the way still holds what it held.
fn run(start: usize, ops: &[Op]) -> Result<(), TestCaseError> {
let mut model: Vec<u32> = (0..start as u32).collect();
let mut list: SharedVec<u32> = model.iter().copied().collect();
let mut snapshots: Vec<(SharedVec<u32>, Vec<u32>)> = Vec::new();
for op in ops {
let len = model.len();
match op.clone() {
Op::Push(value) => {
model.push(value);
list.push(value);
}
Op::Pop => prop_assert_eq!(list.pop(), model.pop()),
Op::Insert(at, value) => {
let at = at % (len + 1);
model.insert(at, value);
prop_assert_eq!(list.insert(at, value), Ok(()));
prop_assert_eq!(list.insert(len + 2, value), Err(value));
}
Op::Remove(at) => {
if len > 0 {
let at = at % len;
prop_assert_eq!(list.remove(at), Some(model.remove(at)));
}
prop_assert_eq!(list.remove(model.len()), None);
}
Op::Set(at, value) => {
if len > 0 {
let at = at % len;
let old = std::mem::replace(&mut model[at], value);
prop_assert_eq!(list.set(at, value), Ok(old));
}
prop_assert_eq!(list.set(len, value), Err(value));
}
Op::SplitOffAndAppend(at) => {
let at = at % (len + 1);
let mut back = list.split_off(at);
node::check(&list.root).map_err(TestCaseError::fail)?;
node::check(&back.root).map_err(TestCaseError::fail)?;
prop_assert_eq!(list.to_vec(), model[..at].to_vec());
prop_assert_eq!(back.to_vec(), model[at..].to_vec());
list.append(&mut back);
prop_assert!(back.is_empty());
}
Op::Truncate(to) => {
let to = to % (len + 1);
model.truncate(to);
list.truncate(to);
}
Op::Splice(at, count, with) => {
let start = at % (len + 1);
let end = (start + count).min(len);
let expected: Vec<u32> = model.splice(start..end, with.iter().copied()).collect();
prop_assert_eq!(list.splice(start..end, with), expected);
}
Op::Retain(modulus) => {
model.retain(|value| value % modulus != 0);
list.retain(|value| value % modulus != 0);
}
Op::RetainOne(at) => {
if len > 0 {
let at = at % len;
model.remove(at);
let mut index = 0;
list.retain(|_| {
index += 1;
index != at + 1
});
}
}
Op::SplitOffFew(count, front) => {
let at = if front { count.min(len) } else { len.saturating_sub(count) };
let mut back = list.split_off(at);
node::check(&list.root).map_err(TestCaseError::fail)?;
node::check(&back.root).map_err(TestCaseError::fail)?;
prop_assert_eq!(list.to_vec(), model[..at].to_vec());
prop_assert_eq!(back.to_vec(), model[at..].to_vec());
list.append(&mut back);
prop_assert!(back.is_empty());
}
Op::TruncateFew(count) => {
model.truncate(len.saturating_sub(count));
list.truncate(len.saturating_sub(count));
}
Op::AppendClone if len < 20_000 => {
let mut copy = list.clone();
list.append(&mut copy);
model.extend_from_within(..);
}
Op::AppendClone => {}
Op::Snapshot => snapshots.push((list.clone(), model.clone())),
Op::Clear => {
model.clear();
list.clear();
}
}
node::check(&list.root).map_err(TestCaseError::fail)?;
prop_assert_eq!(list.len(), model.len());
prop_assert!(list.iter().eq(model.iter()));
prop_assert!(list.iter().rev().eq(model.iter().rev()));
}
for (snapshot, expected) in &snapshots {
node::check(&snapshot.root).map_err(TestCaseError::fail)?;
prop_assert_eq!(&snapshot.to_vec(), expected);
}
prop_assert_eq!(Vec::from(list), model);
Ok(())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
#[test]
fn small_lists_match_vec(start in 0..300usize, ops in prop::collection::vec(op(), 1..120)) {
run(start, &ops)?;
}
// Past 64 * 64 elements the tree has two levels of branches.
#[test]
fn two_level_lists_match_vec(start in 4_000..9_000usize, ops in prop::collection::vec(op(), 1..60)) {
run(start, &ops)?;
}
#[test]
fn mixed_ends_of_the_iterator_meet_once(start in 0..3_000usize, picks in prop::collection::vec(any::<bool>(), 0..3_000)) {
let model: Vec<u32> = (0..start as u32).collect();
let list: SharedVec<u32> = model.iter().copied().collect();
let (mut ours, mut theirs) = (list.iter(), model.iter());
for from_back in picks {
let (a, b) = if from_back { (ours.next_back(), theirs.next_back()) } else { (ours.next(), theirs.next()) };
prop_assert_eq!(a, b);
prop_assert_eq!(ours.len(), theirs.len());
}
let collect = |acc: Vec<u32>, value: &u32| { let mut acc = acc; acc.push(*value); acc };
prop_assert_eq!(ours.clone().fold(Vec::new(), collect), theirs.clone().fold(Vec::new(), collect));
prop_assert_eq!(ours.clone().rfold(Vec::new(), collect), theirs.clone().rfold(Vec::new(), collect));
prop_assert!(ours.eq(theirs));
}
}
#[test]
fn a_three_level_tree_keeps_its_shape_through_removals_and_insertions() -> Result<(), String> {
let count = MAX * MAX * MAX + 5;
let mut model: Vec<u32> = (0..count as u32).collect();
let mut list: SharedVec<u32> = model.iter().copied().collect();
let before = list.clone();
let mut seed = 0x2545_f491_u64;
for step in 0..30_000u32 {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
let at = (seed % model.len() as u64) as usize;
if step % 3 == 0 {
model.insert(at, step);
list.insert(at, step).map_err(|_| "insert refused")?;
} else {
let removed = list.remove(at);
if removed != Some(model.remove(at)) {
return Err(format!("step {step}: removed {removed:?}"));
}
}
}
node::check(&list.root)?;
node::check(&before.root)?;
if !list.iter().eq(model.iter()) {
return Err("contents differ from the model".into());
}
if !before.iter().copied().eq(0..count as u32) {
return Err("the clone changed".into());
}
Ok(())
}
+167
View File
@@ -0,0 +1,167 @@
//! `bytes_not_in` counts the blocks one list holds and another does not, and never less.
use std::collections::HashSet;
use std::mem::size_of;
use std::sync::Arc;
use craft_shared_vec::{BlockId, SharedVec};
/// The bytes of the blocks of `after` that `before` does not hold, from the full block lists.
fn expected<T>(before: &SharedVec<T>, after: &SharedVec<T>) -> usize {
let old: HashSet<BlockId> = before.blocks().into_iter().map(|block| block.id).collect();
let mut seen = HashSet::new();
after.blocks().into_iter().filter(|block| !old.contains(&block.id) && seen.insert(block.id)).map(|block| block.bytes).sum()
}
#[test]
fn the_count_matches_the_blocks_each_edit_copied() {
let base: SharedVec<u64> = (0..100_000).collect();
type Edit = fn(&mut SharedVec<u64>);
let edits: [(&str, Edit); 10] = [
("set", |list| assert!(list.set(77_777, 1).is_ok())),
("insert", |list| assert!(list.insert(3, 1).is_ok())),
("remove", |list| assert!(list.remove(64 * 40).is_some())),
("push", |list| list.push(1)),
("pop", |list| assert!(list.pop().is_some())),
("splice", |list| assert_eq!(list.splice(10..5_000, [1, 2, 3]).len(), 4_990)),
("retain", |list| list.retain(|value| value % 1_000 != 0)),
("append", |list| list.append(&mut (0..500).collect())),
("append itself", |list| list.append(&mut list.clone())),
("truncate", |list| list.truncate(60_001)),
];
for (name, edit) in edits {
let mut after = base.clone();
edit(&mut after);
assert_eq!(after.bytes_not_in(&base), expected(&base, &after), "{name}");
// The other direction: what keeping the old list costs once the new one is kept.
assert_eq!(base.bytes_not_in(&after), expected(&after, &base), "{name}, reversed");
}
}
#[test]
fn a_list_costs_nothing_beside_its_clone_and_everything_beside_an_unrelated_list() {
let list: SharedVec<u64> = (0..10_000).collect();
assert_eq!(list.bytes_not_in(&list.clone()), 0);
let unrelated: SharedVec<u64> = (0..10_000).collect();
let all: usize = list.blocks().iter().map(|block| block.bytes).sum();
assert_eq!(list.bytes_not_in(&unrelated), all);
assert_eq!(list.bytes_not_in(&SharedVec::new()), all);
assert!(all >= 10_000 * size_of::<u64>());
}
#[test]
fn a_range_edit_of_one_element_costs_about_as_much_as_one_removal() {
let base: SharedVec<u64> = (0..100_000).collect();
let mut removed = base.clone();
assert!(removed.remove(50_000).is_some());
let single = removed.bytes_not_in(&base);
type Edit = fn(&mut SharedVec<u64>);
let edits: [(&str, Edit); 6] = [
("splice out", |list| assert_eq!(list.splice(50_000..50_001, []).len(), 1)),
("splice in", |list| assert!(list.splice(50_000..50_000, [7]).is_empty())),
("retain", |list| list.retain(|value| *value != 50_000)),
("truncate", |list| list.truncate(99_999)),
("split_off", |list| assert_eq!(list.split_off(99_999).len(), 1)),
("append", |list| list.append(&mut SharedVec::from(vec![7]))),
];
for (name, edit) in edits {
let mut after = base.clone();
edit(&mut after);
let cost = after.bytes_not_in(&base);
assert!(cost <= 2 * single, "{name}: {cost} bytes against {single} for one removal");
}
}
#[test]
fn an_empty_list_holds_no_blocks() {
let mut emptied: SharedVec<u64> = (0..5_000).collect();
emptied.retain(|_| false);
let read: SharedVec<u64> = serde_json::from_str("[]").unwrap_or_else(|error| panic!("{error}"));
for list in [&SharedVec::new(), &SharedVec::default(), &read, &emptied] {
assert!(list.blocks().is_empty());
assert_eq!(list.bytes_not_in(&SharedVec::new()), 0);
assert!(list.ptr_eq(&SharedVec::new()));
}
let mut popped: SharedVec<u64> = (0..3).collect();
while popped.pop().is_some() {}
assert!(popped.blocks().is_empty());
}
#[test]
fn one_edit_on_a_large_list_costs_a_small_fraction_of_a_vector_copy() {
for count in [1_000usize, 10_000, 100_000] {
let before: SharedVec<u64> = (0..count as u64).collect();
let mut after = before.clone();
assert!(after.set(count / 3, 0).is_ok());
let cost = after.bytes_not_in(&before);
let vector_copy = count * size_of::<u64>();
assert!(cost > 64 * size_of::<u64>(), "the copied leaf is counted");
if count >= 10_000 {
assert!(cost * 20 < vector_copy, "{count}: {cost} bytes against {vector_copy}");
}
}
}
type Payload = Arc<Vec<u8>>;
fn key(value: &Payload) -> *const Vec<u8> {
Arc::as_ptr(value)
}
fn payload(value: &Payload) -> usize {
value.capacity()
}
#[test]
fn a_large_new_payload_is_counted_in_full() {
let before: SharedVec<Payload> = (0..10_000).map(|_| Arc::new(vec![0u8; 16])).collect();
let mut after = before.clone();
assert!(after.set(4_321, Arc::new(vec![0u8; 10 << 20])).is_ok());
let charged = after.bytes_not_in_with(&before, key, payload);
assert!(charged >= 10 << 20);
assert!(charged < (10 << 20) + 4_096, "{charged}");
let fresh: SharedVec<Payload> = (0..100).map(|_| Arc::new(vec![0u8; 100 << 10])).collect();
assert!(fresh.bytes_not_in_with(&SharedVec::new(), key, payload) >= 100 * (100 << 10));
// The same allocation held twice is counted once.
let twice: SharedVec<Payload> = [Arc::new(vec![0u8; 1 << 20])].iter().cycle().take(2).cloned().collect();
assert!(twice.bytes_not_in_with(&SharedVec::new(), key, payload) < 2 << 20);
}
#[test]
fn unchanged_elements_of_a_copied_or_rebuilt_leaf_are_not_counted() {
let size = 16 << 10;
let before: SharedVec<Payload> = (0..1_000).map(|_| Arc::new(vec![0u8; size])).collect();
// A set copies a leaf of 64 elements; only the new element's payload is new.
let mut after = before.clone();
assert!(after.set(500, Arc::new(vec![0u8; size])).is_ok());
let charged = after.bytes_not_in_with(&before, key, payload);
assert!(charged >= size && charged < 2 * size, "{charged}");
// A removal moves elements between leaves without allocating any payload.
let mut after = before.clone();
after.retain(|value| !Arc::ptr_eq(value, &before.get(500).cloned().unwrap_or_default()));
after.truncate(900);
let removed = after.splice(10..20, []);
assert_eq!(removed.len(), 10);
let charged = after.bytes_not_in_with(&before, key, payload);
assert!(charged < size, "{charged}");
assert_eq!(charged, after.bytes_not_in(&before));
}
#[test]
fn many_edits_to_one_list_stay_far_below_vector_copies() {
// One edit per element of a 10,000-element list, each kept beside the one before it, the way an
// undo history keeps snapshots. A vector copied per edit would cost 10,000 * 80,000 bytes.
let count = 10_000usize;
let mut list: SharedVec<u64> = (0..count as u64).collect();
let mut charged = 0usize;
for index in 0..count {
let before = list.clone();
assert!(list.set(index, 0).is_ok());
charged += list.bytes_not_in(&before);
}
let vector_copies = count * count * size_of::<u64>();
assert!(charged * 20 < vector_copies, "{charged} bytes against {vector_copies}");
}
+5
View File
@@ -0,0 +1,5 @@
//! Integration tests: block sharing, share-aware byte counts and the sequence format.
mod bytes;
mod serde_seq;
mod sharing;
+52
View File
@@ -0,0 +1,52 @@
//! A list reads and writes as a plain sequence.
use craft_shared_vec::SharedVec;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Item {
id: u32,
name: String,
children: SharedVec<Item>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct PlainItem {
id: u32,
name: String,
children: Vec<PlainItem>,
}
#[test]
fn a_json_array_round_trips_byte_for_byte() {
let numbers: Vec<u32> = (0..5_000).map(|n| n * 7 % 1_013).collect();
let text = serde_json::to_string(&numbers).unwrap_or_default();
let list: SharedVec<u32> = serde_json::from_str(&text).unwrap_or_default();
assert!(list.iter().eq(numbers.iter()));
assert_eq!(serde_json::to_string(&list).ok(), Some(text));
for text in ["[]", "[[1]]", "[[1,2],[],[3]]"] {
let nested: SharedVec<SharedVec<u8>> = serde_json::from_str(text).unwrap_or_default();
assert_eq!(serde_json::to_string(&nested).ok().as_deref(), Some(text));
}
}
#[test]
fn a_tree_reads_and_writes_the_same_bytes_as_one_built_on_vec() {
let leaf = |id: u32| PlainItem { id, name: format!("item {id}"), children: Vec::new() };
let plain =
PlainItem { id: 0, name: "root".into(), children: (1..300).map(|id| PlainItem { children: vec![leaf(id * 1_000)], ..leaf(id) }).collect() };
for text in [serde_json::to_string(&plain).unwrap_or_default(), serde_json::to_string_pretty(&plain).unwrap_or_default()] {
let shared: Item = serde_json::from_str(&text).unwrap_or_else(|_| Item { id: u32::MAX, name: String::new(), children: SharedVec::new() });
assert_eq!(shared.children.len(), 299);
let again = if text.contains('\n') { serde_json::to_string_pretty(&shared) } else { serde_json::to_string(&shared) };
assert_eq!(again.ok(), Some(text));
}
}
#[test]
fn input_that_is_not_a_sequence_is_an_error() {
for text in ["{\"a\":1}", "7", "\"[1]\"", "[1,", "[1,\"two\"]"] {
assert!(serde_json::from_str::<SharedVec<u32>>(text).is_err(), "{text}");
}
}
+175
View File
@@ -0,0 +1,175 @@
//! An edit to a clone copies only the blocks it changes.
use std::collections::HashSet;
use craft_shared_vec::{BlockId, SharedVec};
fn ids(list: &SharedVec<u64>, leaves_only: bool) -> HashSet<BlockId> {
list.blocks().into_iter().filter(|block| block.is_leaf || !leaves_only).map(|block| block.id).collect()
}
/// The blocks of `after`, and of its leaves, that `before` does not hold.
fn new_blocks(before: &SharedVec<u64>, after: &SharedVec<u64>) -> (usize, usize) {
let old = ids(before, false);
let blocks = after.blocks();
let new: Vec<_> = blocks.iter().filter(|block| !old.contains(&block.id)).collect();
(new.len(), new.iter().filter(|block| block.is_leaf).count())
}
#[test]
fn a_set_copies_one_leaf_and_the_branches_above_it() {
for count in [1_000u64, 10_000, 100_000] {
let before: SharedVec<u64> = (0..count).collect();
let mut after = before.clone();
assert!(after.ptr_eq(&before));
assert_eq!(after.set(count as usize / 2, u64::MAX), Ok(count / 2));
assert!(!after.ptr_eq(&before));
let (blocks, leaves) = new_blocks(&before, &after);
assert_eq!(leaves, 1, "{count} elements");
// Up to 64 * 64 * 64 elements, a leaf has at most two branches above it.
assert!(blocks <= 3, "{count} elements: {blocks} new blocks");
assert_eq!(before.get(count as usize / 2), Some(&(count / 2)));
}
}
#[test]
fn a_get_mut_copies_the_same_path_as_a_set() {
let before: SharedVec<u64> = (0..50_000).collect();
let mut after = before.clone();
if let Some(value) = after.get_mut(31_000) {
*value += 1;
}
let (_, leaves) = new_blocks(&before, &after);
assert_eq!(leaves, 1);
assert_eq!(after.get(31_000), Some(&31_001));
assert_eq!(before.get(31_000), Some(&31_000));
}
#[test]
fn single_removals_at_the_front_middle_and_end_copy_at_most_two_leaves() {
let before: SharedVec<u64> = (0..100_000).collect();
for at in [0, 50_000, 99_999] {
let mut after = before.clone();
assert_eq!(after.remove(at), Some(at as u64));
let (_, leaves) = new_blocks(&before, &after);
// The leaf that lost the element, and a neighbor it merged with or took elements from.
assert!(leaves <= 2, "removal at {at} copied {leaves} leaves");
assert_eq!(after.len(), 99_999);
}
}
#[test]
fn removing_from_the_end_one_at_a_time_keeps_the_earlier_leaves() {
let start: SharedVec<u64> = (0..20_000).collect();
let mut list = start.clone();
for _ in 0..5_000 {
let before = list.clone();
list.pop();
let (_, leaves) = new_blocks(&before, &list);
assert!(leaves <= 2);
}
let kept = ids(&start, true);
let shared = ids(&list, true).intersection(&kept).count();
assert!(shared * 64 >= 14_000, "only {shared} of the first leaves are still shared");
}
#[test]
fn an_insertion_shares_the_leaves_it_does_not_touch() {
let before: SharedVec<u64> = (0..100_000).collect();
let mut after = before.clone();
assert_eq!(after.insert(0, 7), Ok(()));
let (_, leaves) = new_blocks(&before, &after);
// The leaf that took the element, and the second half when it split.
assert!(leaves <= 2);
assert_eq!(after.first(), Some(&7));
assert_eq!(after.get(1), Some(&0));
}
#[test]
fn retain_shares_every_leaf_it_keeps_whole() {
let before: SharedVec<u64> = (0..100_000).collect();
let mut after = before.clone();
after.retain(|&value| value != 40_000);
assert_eq!(after.len(), 99_999);
let total = ids(&after, true).len();
let (_, leaves) = new_blocks(&before, &after);
assert!(leaves <= 2, "{leaves} of {total} leaves are new");
// Nothing removed: the list is the same tree.
let mut unchanged = before.clone();
unchanged.retain(|_| true);
assert!(unchanged.ptr_eq(&before));
}
#[test]
fn append_and_split_off_keep_the_leaves_away_from_the_cut() {
let left: SharedVec<u64> = (0..10_000).collect();
let right: SharedVec<u64> = (10_000..20_000).collect();
let mut joined = left.clone();
joined.append(&mut right.clone());
assert!(joined.iter().copied().eq(0..20_000));
let original: HashSet<BlockId> = ids(&left, true).union(&ids(&right, true)).copied().collect();
let fresh = ids(&joined, true).difference(&original).count();
assert!(fresh <= 2, "{fresh} leaves were copied at the join");
let mut front = joined.clone();
let back = front.split_off(12_345);
assert!(front.iter().copied().eq(0..12_345));
assert!(back.iter().copied().eq(12_345..20_000));
let from_joined = ids(&joined, true);
let fresh = ids(&front, true).union(&ids(&back, true)).filter(|id| !from_joined.contains(id)).count();
assert!(fresh <= 4, "{fresh} leaves were copied at the cut");
}
#[test]
fn splice_replaces_a_range_and_keeps_the_rest_shared() {
let before: SharedVec<u64> = (0..10_000).collect();
let mut after = before.clone();
let removed = after.splice(5_000..5_010, [1, 2, 3]);
assert!(removed.iter().copied().eq(5_000..5_010));
assert_eq!(after.len(), 9_993);
assert!(after.iter().skip(5_000).take(3).copied().eq([1, 2, 3]));
let (_, leaves) = new_blocks(&before, &after);
assert!(leaves <= 4);
}
#[test]
fn a_splice_whose_replacement_panics_leaves_the_list_as_it_was() {
let mut list: SharedVec<u64> = (0..10_000).collect();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
list.splice(100..200, (0..10u64).map(|value| if value == 5 { panic!("replacement failed") } else { value }))
}));
assert!(result.is_err());
assert!(list.iter().copied().eq(0..10_000));
}
#[test]
fn a_list_holding_nan_is_not_equal_to_its_clone() {
let list: SharedVec<f64> = [1.0, f64::NAN].into_iter().collect();
assert!(list != list.clone());
assert_eq!(list.partial_cmp(&list.clone()), None);
let numbers: SharedVec<f64> = [1.0, 2.0].into_iter().collect();
assert!(numbers == numbers.clone());
}
#[test]
fn chunks_cover_every_element_once_in_order() {
let list: SharedVec<u64> = (0..10_007).collect();
let flat: Vec<u64> = list.chunks().flatten().copied().collect();
assert!(flat.iter().copied().eq(0..10_007));
assert!(list.chunks().all(|chunk| !chunk.is_empty()));
assert_eq!(SharedVec::<u64>::new().chunks().count(), 0);
}
#[test]
fn out_of_range_edits_leave_the_list_unchanged() {
let mut list: SharedVec<u64> = (0..100).collect();
let before = list.clone();
assert_eq!(list.set(100, 1), Err(1));
assert_eq!(list.insert(101, 1), Err(1));
assert_eq!(list.remove(100), None);
assert!(list.split_off(100).is_empty());
list.truncate(500);
assert!(list.get_mut(100).is_none());
assert!(list.ptr_eq(&before));
}
+5
View File
@@ -31,5 +31,10 @@ keyring = "4.2"
# machine-local persistence. `keyring` installs the platform store; this reads it.
keyring-core = "1"
# The account list is created with an access list of its user and SYSTEM only
# (`owner_only::create_private_file`).
[target.'cfg(windows)'.dependencies]
craft-platform = { workspace = true }
[dev-dependencies]
tempfile = "3"
+156 -20
View File
@@ -263,7 +263,10 @@ pub fn read(path: &Path) -> Result<Accounts, Error> {
/// [`Error::Malformed`] forever. Every mutation here reads the file first. There would be
/// nothing left to repair it with.
///
/// Readable by this user alone where the platform has file modes. The file holds no token. It does
/// Readable by this user alone: mode `0600` on Unix, and on Windows an access list of this user and
/// SYSTEM only from the moment the file exists, whatever folder a portable install or
/// [`crate::paths::ENV_VAR`] chose. On Windows the access list is protected, so a change to the
/// folder's list does not reach the file. The file holds no token. It does
/// say who is signed in. That is nobody else's business.
///
/// Refuses a list that would serialize past `MAX_BYTES`, before any file is touched. [`read`]
@@ -282,14 +285,17 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
)));
}
std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("couldn't create {} ({e})", dir.display())))?;
use std::io::Write;
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
let pid = std::process::id();
let tmp = dir.join(format!(".{}.{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"), stamp, pid));
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts");
let tmp_name = format!(".{file_name}.{stamp}.{pid}.tmp");
#[cfg(not(windows))]
let tmp = dir.join(&tmp_name);
#[cfg(unix)]
{
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut file = OpenOptions::new()
.write(true)
@@ -300,14 +306,16 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?;
}
#[cfg(not(unix))]
#[cfg(windows)]
let tmp = private_copy(path, dir, &tmp_name, &json)?;
#[cfg(not(any(unix, windows)))]
{
use std::fs::OpenOptions;
use std::io::Write;
let mut file =
OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?;
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?;
restrict(&tmp)?;
}
std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("couldn't replace {} ({e})", path.display())))?;
// The flush above persisted the file's bytes. The rename changed a directory entry, and that
@@ -324,19 +332,147 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
Ok(())
}
#[cfg(not(unix))]
fn restrict(_path: &Path) -> Result<(), Error> {
// A no-op today. That is a real gap this comment used to paper over. A new file in the
// platform configuration folder (the default `paths::Rule::Platform` home) inherits that
// folder's own, profile-scoped access rules. The account list is this user's alone there.
// `paths::Rule::Portable` and `paths::Rule::EnvVar` point `write` at whatever folder the
// caller named. A new file there inherits that folder's own Windows access control list,
// whatever it is. A shared or loosely permissioned folder in either of those two cases
// leaves the account list (subjects, display names, emails, never a token) readable by
// anyone else with access to it. Narrowing that needs a per-user Windows DACL on the file,
// set through the Win32 authorization API. Every binding for that API is an `unsafe fn`.
// This workspace forbids `unsafe_code` outright. Closing this for real needs either a
// maintainer-approved exception for one call site or a vetted dependency that wraps that API
// safely. Both are decisions for a dedicated PR. See `paths::Rule`.
Ok(())
/// Write `json` to a new file beside the list at `path`, in its folder `dir`, that only this user
/// and SYSTEM can open, and return its path for [`write`] to rename into place.
///
/// A new file on Windows takes its folder's access list, and a portable install or
/// [`crate::paths::ENV_VAR`] can name a folder that lets every local user read what is created in
/// it. Every copy is created by `owner_only::create_private_file`, which gives the file a protected
/// access list of this user and SYSTEM only in the call that creates it. The rename keeps that
/// list, and a later change to the folder's list does not reach it. That call runs PowerShell, so
/// [`prepare`] creates an empty copy before the accounts lock is taken, and this function writes
/// the list into it. Without a copy this thread prepared (a direct call, or a failed preparation),
/// the copy is created here, named `tmp_name`.
#[cfg(windows)]
fn private_copy(path: &Path, dir: &Path, tmp_name: &str, json: &[u8]) -> Result<std::path::PathBuf, Error> {
use std::io::Write;
if let Some((copy, mut file)) = take_prepared(path) {
match file.write_all(json).and_then(|()| file.sync_all()) {
Ok(()) => return Ok(copy),
Err(e) => {
drop(file);
let _ = std::fs::remove_file(&copy);
log::warn!("couldn't write a prepared copy of the account list ({e}); a new one is created");
}
}
}
let tmp = dir.join(tmp_name);
user_sid()
.and_then(|me| craft_platform::owner_only::create_private_file(&tmp, &me, json))
.map_err(|e| Error::Io(format!("couldn't create {} for its owner only ({e})", tmp.display())))?;
Ok(tmp)
}
/// Copies made by [`prepare`] that wait for [`private_copy`]: the thread that made the copy, the
/// list it is for, the copy, and the copy held open without delete sharing.
#[cfg(windows)]
type Prepared = Vec<(std::thread::ThreadId, std::path::PathBuf, std::path::PathBuf, std::fs::File)>;
/// The copy one [`prepare`] call made. Dropping it closes and removes the copy if no write took it.
#[cfg(windows)]
pub(crate) struct PreparedCopy(Option<std::path::PathBuf>);
#[cfg(windows)]
impl Drop for PreparedCopy {
fn drop(&mut self) {
let Some(copy) = self.0.take() else { return };
let mut waiting = prepared();
let Some(at) = waiting.iter().position(|(_, _, waiting, _)| *waiting == copy) else { return };
let (_, _, copy, file) = waiting.swap_remove(at);
drop(waiting);
drop(file);
let _ = std::fs::remove_file(&copy);
}
}
/// The copies waiting for [`private_copy`].
#[cfg(windows)]
fn prepared() -> std::sync::MutexGuard<'static, Prepared> {
static PREPARED: std::sync::Mutex<Prepared> = std::sync::Mutex::new(Vec::new());
PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// The copy of the list at `path` that this thread prepared, with its open handle, removed from the
/// waiting list. A copy another thread prepared is left for that thread's write.
#[cfg(windows)]
fn take_prepared(path: &Path) -> Option<(std::path::PathBuf, std::fs::File)> {
let me = std::thread::current().id();
let mut prepared = prepared();
let at = prepared.iter().position(|(thread, list, ..)| *thread == me && list == path)?;
let (_, _, copy, file) = prepared.swap_remove(at);
Some((copy, file))
}
/// This user's SID, read once per process (`whoami` is a process start).
#[cfg(windows)]
fn user_sid() -> std::io::Result<String> {
static SID: std::sync::OnceLock<String> = std::sync::OnceLock::new();
if let Some(sid) = SID.get() {
return Ok(sid.clone());
}
let sid = craft_platform::owner_only::current_user_sid()?;
Ok(SID.get_or_init(|| sid).clone())
}
/// Before the accounts lock is taken, create an empty copy of the list at `path` for its owner only
/// and keep it open for [`private_copy`], so that the PowerShell run it needs doesn't hold the lock
/// other processes wait on. The caller keeps the returned [`PreparedCopy`] until its change under
/// the lock is done; a change that writes nothing then has its copy removed. A failure here is left
/// for [`write`] to handle.
///
/// The copy is opened without delete sharing and then checked, so no other account can remove,
/// rename or replace it between the check and the write. A copy that fails the check is removed.
/// Empty copies beside the list that are at least a minute old, which ended processes left, are
/// removed first; a copy that a running process holds open can't be, since removing it needs
/// delete sharing.
#[cfg(windows)]
pub(crate) fn prepare(path: &Path) -> PreparedCopy {
use std::os::windows::fs::OpenOptionsExt as _;
use std::sync::atomic::{AtomicU64, Ordering};
use craft_platform::owner_only;
/// `FILE_SHARE_READ | FILE_SHARE_WRITE`: no `FILE_SHARE_DELETE`.
const SHARE_NO_DELETE: u32 = 0x1 | 0x2;
/// How old an empty copy that no process holds must be before it is removed. Another process
/// that is preparing its copy has it closed for a moment, between its creation and the open.
const LEFT_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
static COUNT: AtomicU64 = AtomicU64::new(0);
let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return PreparedCopy(None) };
let Ok(me) = user_sid() else { return PreparedCopy(None) };
let _ = std::fs::create_dir_all(dir);
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let left = entry.file_name();
let left = left.to_string_lossy();
if left.starts_with(&format!(".{name}."))
&& left.ends_with(".prepared.tmp")
&& entry.metadata().is_ok_and(|meta| {
meta.is_file() && meta.len() == 0 && meta.modified().ok().and_then(|at| at.elapsed().ok()).is_some_and(|age| age >= LEFT_AFTER)
})
{
let _ = std::fs::remove_file(entry.path());
}
}
let copy = dir.join(format!(".{name}.{}.{}.prepared.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
if let Err(e) = owner_only::create_private_file(&copy, &me, b"") {
log::warn!("couldn't prepare a copy of the account list for its owner only ({e})");
return PreparedCopy(None);
}
let checked = std::fs::OpenOptions::new().write(true).share_mode(SHARE_NO_DELETE).open(&copy).and_then(|file| {
match owner_only::foreign_access(&owner_only::sddl_of(&copy)?, &me) {
None => Ok(file),
Some(problem) => Err(std::io::Error::other(problem)),
}
});
match checked {
Ok(file) => {
prepared().push((std::thread::current().id(), path.to_path_buf(), copy.clone(), file));
PreparedCopy(Some(copy))
}
Err(e) => {
let _ = std::fs::remove_file(&copy);
log::warn!("a prepared copy of the account list is not this user's alone ({e}); it was removed");
PreparedCopy(None)
}
}
}
+2
View File
@@ -49,6 +49,8 @@ fn open_lock_file(path: &Path) -> io::Result<File> {
/// [`Error::Io`]; `f` may return any [`Error`].
pub(crate) fn with_lock<T>(path: &Path, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?;
#[cfg(windows)]
let _prepared = crate::accounts::prepare(path);
let start = Instant::now();
loop {
match lock.try_lock() {
+153
View File
@@ -521,6 +521,159 @@ fn write_leaves_a_previously_good_file_untouched_when_the_new_one_is_too_large()
assert_eq!(accounts::read(&path).unwrap(), good, "the earlier, readable file must still be exactly what was there before");
}
/// A portable install or `ARTCRAFT_SUITE_DIR` can put the list in a folder that lets every local
/// user read the files created in it, as a new folder at a drive root does. The list written there
/// has an access list of its user and SYSTEM only.
#[cfg(windows)]
#[test]
fn the_list_in_a_folder_users_can_read_is_still_this_users_alone() {
use craft_platform::owner_only;
let dir = tempfile::tempdir().unwrap();
let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stderr));
let path = dir.path().join(paths::FILE);
let list =
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
accounts::write(&path, &list).unwrap();
let me = owner_only::current_user_sid().unwrap();
let sddl = owner_only::sddl_of(&path).unwrap();
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}");
assert_eq!(accounts::read(&path).unwrap(), list);
// A second write, through a copy prepared before the lock as a `Store` does, leaves no copy behind.
let _copy = accounts::prepare(&path);
accounts::write(&path, &list).unwrap();
assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None);
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(names, [std::ffi::OsString::from(paths::FILE)], "no temporary file is left behind");
}
/// The list's access list is protected: a change to its folder's access list, which Windows hands
/// down to the files in the folder that inherit from it, does not reach the list, whether the list
/// was written directly or through a `Store`.
#[cfg(windows)]
#[test]
fn a_change_to_the_folders_access_list_does_not_reach_the_list() {
use craft_platform::owner_only;
let me = owner_only::current_user_sid().unwrap();
for through_store in [false, true] {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(paths::FILE);
if through_store {
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
} else {
let list = accounts::Accounts {
format: accounts::FORMAT,
accounts: vec![account_at("a", 0)],
active: Some("a".to_owned()),
tombstones: Vec::new(),
};
accounts::write(&path, &list).unwrap();
}
let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout));
let sddl = owner_only::sddl_of(&path).unwrap();
assert_eq!(owner_only::foreign_access(&sddl, &me), None, "through a Store: {through_store}; {sddl}");
}
}
/// A prepared copy that no write took is closed and removed when its change under the lock is
/// done, as for a discard of an account that is not in the list.
#[cfg(windows)]
#[test]
fn a_prepared_copy_no_write_took_is_removed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(paths::FILE);
let copy = accounts::prepare(&path);
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the copy is made");
drop(copy);
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "the copy is removed");
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
let names = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::<Vec<_>>();
let before = names();
let _ = store.discard("no such account");
assert_eq!(names(), before, "a change that writes nothing leaves no copy behind");
}
/// A write uses the copy its own thread prepared and leaves another thread's copy for that
/// thread, which would otherwise have to create one while it holds the accounts lock.
#[cfg(windows)]
#[test]
fn a_write_takes_only_the_copy_its_thread_prepared() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(paths::FILE);
let list =
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
let copies = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().path()).filter(|p| p != &path).collect::<Vec<_>>();
let prepared = std::sync::Barrier::new(2);
// The other thread keeps its copy until `done` is dropped, which a failed assertion does too.
let (done, wait) = std::sync::mpsc::channel::<()>();
std::thread::scope(|scope| {
let (list_path, prepared) = (&path, &prepared);
scope.spawn(move || {
let _other = accounts::prepare(list_path);
prepared.wait();
let _ = wait.recv();
});
prepared.wait();
let other = copies();
assert_eq!(other.len(), 1, "{other:?}");
let _mine = accounts::prepare(&path);
accounts::write(&path, &list).unwrap();
assert_eq!(copies(), other, "the other thread's copy is still waiting");
drop(done);
});
assert_eq!(copies(), Vec::<std::path::PathBuf>::new());
}
/// A prepared copy is created with an access list of its user and SYSTEM only, and can't be
/// removed, renamed or replaced, nor its folder renamed, between its check and the write. An empty
/// copy that an ended process left a minute or more ago is removed by the next preparation; a
/// newer one, which another process may be about to open, is kept.
#[cfg(windows)]
#[test]
fn a_prepared_copy_is_private_and_cannot_be_swapped_before_the_write() {
use craft_platform::owner_only;
let me = owner_only::current_user_sid().unwrap();
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("suite");
std::fs::create_dir(&dir).unwrap();
let granted = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout));
let path = dir.join(paths::FILE);
let left = dir.join(format!(".{}.1.0.prepared.tmp", paths::FILE));
std::fs::File::create(&left).unwrap().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(120)).unwrap();
let fresh = dir.join(format!(".{}.2.0.prepared.tmp", paths::FILE));
std::fs::write(&fresh, b"").unwrap();
let _copy = accounts::prepare(&path);
assert!(!left.exists(), "an old empty copy that no process holds is removed");
assert!(fresh.exists(), "a new empty copy, which another process may be about to open, is kept");
let copies: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != fresh).collect();
assert_eq!(copies.len(), 1, "{copies:?}");
let copy = &copies[0];
let sddl = owner_only::sddl_of(copy).unwrap();
assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}");
assert!(std::fs::remove_file(copy).is_err(), "the checked copy must stay in place");
assert!(std::fs::rename(copy, dir.join("moved")).is_err(), "the checked copy must not be renamed away");
assert!(std::fs::rename(&dir, root.path().join("moved")).is_err(), "its folder must not be renamed away");
let list =
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
accounts::write(&path, &list).unwrap();
assert!(!copy.exists(), "the write used the prepared copy");
assert_eq!(accounts::read(&path).unwrap(), list);
assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None);
}
#[test]
fn a_sign_in_with_an_oversized_display_name_fails_without_bricking_the_list() {
let dir = tempfile::tempdir().unwrap();
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff. Show more