Merge remote-tracking branch 'upstream/next' into pr-2809-merge

# Conflicts:
#	crates/automation/Cargo.toml
#	crates/automation/src/access.rs
#	crates/automation/src/synthetic.rs
#	crates/automation/tests/it/access.rs
#	crates/automation/tests/it/synthetic.rs
#	crates/behavior/src/codec.rs
#	crates/behavior/src/edit_history.rs
#	crates/behavior/src/lib.rs
#	crates/behavior/src/wheel.rs
#	crates/color-ui/src/ui/paint_chip.rs
#	crates/color-ui/src/ui/pair.rs
#	crates/color-ui/src/ui/palette.rs
#	crates/color-ui/src/ui/palette/stories.rs
#	crates/dialogs/src/service.rs
#	crates/draw/src/ui/transform/transform_box.rs
#	crates/draw/src/ui/transform/transform_box/stories.rs
#	crates/draw/tests/it/transform_box.rs
#	crates/font-manager/src/glyphs.rs
#	crates/font-manager/src/picker.rs
#	crates/font-manager/src/picker/rank.rs
#	crates/font-manager/src/picker/rows.rs
#	crates/font-manager/src/picker/stories.rs
#	crates/font-manager/tests/it/picker.rs
#	crates/host/src/lib.rs
#	crates/menu/src/context.rs
#	crates/menu/src/mac.rs
#	crates/menu/src/model.rs
#	crates/pages/src/ui/view.rs
#	crates/platform/README.md
#	crates/platform/src/browser_files.rs
#	crates/print/src/ui/dialog.rs
#	crates/print/src/ui/mod.rs
#	crates/print/src/ui/panel.rs
#	crates/print/src/ui/stories.rs
#	crates/print/tests/it/dialog.rs
#	crates/text/src/ui/character.rs
#	crates/text/src/ui/character/rows.rs
#	crates/text/src/ui/editor.rs
#	crates/text/tests/it/editor.rs
#	crates/text/tests/it/main.rs
#	crates/ui-canvas/src/canvas/mod.rs
#	crates/ui-canvas/src/canvas/split/stories.rs
#	crates/ui-canvas/src/canvas/tool_host.rs
#	crates/ui-canvas/src/canvas_controls/outline/mod.rs
#	crates/ui-canvas/src/canvas_controls/task_bar.rs
#	crates/ui-canvas/src/canvas_controls/task_bar/stories.rs
#	crates/ui-canvas/tests/it/canvas/navigate.rs
#	crates/ui-canvas/tests/it/canvas/tool_keys.rs
#	crates/ui-canvas/tests/it/canvas_controls/task_bar.rs
#	crates/ui-contract/src/contract/collection/props.rs
#	crates/ui-contract/src/contract/cx/pointer.rs
#	crates/ui-contract/src/contract/items/access.rs
#	crates/ui-contract/src/contract/items/drag.rs
#	crates/ui-contract/src/contract/items/lead.rs
#	crates/ui-contract/src/contract/label.rs
#	crates/ui-contract/src/contract/mod.rs
#	crates/ui-contract/src/contract/run.rs
#	crates/ui-contract/src/contract/steps/report.rs
#	crates/ui-contract/src/contract/steps/update.rs
#	crates/ui-contract/src/primitives/mod.rs
#	crates/ui-contract/src/primitives/sensing.rs
#	crates/ui-contract/src/primitives/text_adapter.rs
#	crates/ui-contract/src/primitives/text_input.rs
#	crates/ui-contract/src/runtime/access/emit.rs
#	crates/ui-contract/src/runtime/access/text.rs
#	crates/ui-contract/src/runtime/commands/board.rs
#	crates/ui-contract/src/runtime/commands/mod.rs
#	crates/ui-contract/src/runtime/drag.rs
#	crates/ui-contract/src/runtime/egui/access.rs
#	crates/ui-contract/src/runtime/egui/access/tree.rs
#	crates/ui-contract/src/runtime/egui/input.rs
#	crates/ui-contract/src/runtime/env.rs
#	crates/ui-contract/src/runtime/focus/nav.rs
#	crates/ui-contract/src/runtime/frame.rs
#	crates/ui-contract/src/runtime/keys.rs
#	crates/ui-contract/src/runtime/keys/claims.rs
#	crates/ui-contract/src/runtime/keys/input.rs
#	crates/ui-contract/src/runtime/keys/route.rs
#	crates/ui-contract/src/runtime/pointer.rs
#	crates/ui-contract/src/runtime/windows.rs
#	crates/ui-contract/src/testing/fixture.rs
#	crates/ui-contract/src/testing/host_key_trials.rs
#	crates/ui-contract/tests/it/collection/rows.rs
#	crates/ui-contract/tests/it/drag/mod.rs
#	crates/ui-contract/tests/it/runtime/wheel.rs
#	crates/ui-macros/src/props.rs
#	crates/ui-panels/src/dialog/mod.rs
#	crates/ui-panels/src/dialog/prompts.rs
#	crates/ui-panels/src/dialog/recovery.rs
#	crates/ui-panels/src/dialog/trials.rs
#	crates/ui-panels/src/dialog/words.rs
#	crates/ui-panels/src/rails/drawer.rs
#	crates/ui-panels/src/rails/drawer/stories.rs
#	crates/ui-panels/src/rails/tool/trials.rs
#	crates/ui-panels/src/sections/footer.rs
#	crates/ui-panels/tests/it/rails/drawer.rs
#	crates/ui-patterns/src/patterns/dock/area.rs
#	crates/ui-patterns/src/patterns/form_dialogs/about.rs
#	crates/ui-patterns/src/patterns/form_dialogs/dialog.rs
#	crates/ui-patterns/src/patterns/form_dialogs/dialog/stories.rs
#	crates/ui-patterns/src/patterns/form_dialogs/host_requests.rs
#	crates/ui-patterns/src/patterns/form_dialogs/mod.rs
#	crates/ui-patterns/src/patterns/form_dialogs/param.rs
#	crates/ui-patterns/src/patterns/form_dialogs/properties.rs
#	crates/ui-patterns/src/patterns/form_dialogs/properties/stories.rs
#	crates/ui-patterns/src/patterns/form_dialogs/rows.rs
#	crates/ui-patterns/src/patterns/form_dialogs/rows/stories.rs
#	crates/ui-patterns/src/patterns/panels/history.rs
#	crates/ui-patterns/src/patterns/preferences/document/model.rs
#	crates/ui-patterns/src/patterns/preferences/model.rs
#	crates/ui-patterns/src/patterns/preferences/page.rs
#	crates/ui-patterns/src/patterns/preferences/rows.rs
#	crates/ui-patterns/src/patterns/preferences/window.rs
#	crates/ui-patterns/src/patterns/preferences/window/stories.rs
#	crates/ui-patterns/src/patterns/presets/browser.rs
#	crates/ui-patterns/tests/it/docking/group_view.rs
#	crates/ui-patterns/tests/it/form_dialogs/dialog.rs
#	crates/ui-patterns/tests/it/form_dialogs/params.rs
#	crates/ui-patterns/tests/it/preferences/model.rs
#	crates/ui-shell/src/shell/start.rs
#	crates/ui-shell/src/shell/start/stories.rs
#	crates/ui-widgets/src/buttons/icon_button.rs
#	crates/ui-widgets/src/buttons/mod.rs
#	crates/ui-widgets/src/buttons/stories.rs
#	crates/ui-widgets/src/choice/swatch.rs
#	crates/ui-widgets/src/choice/swatch_table.rs
#	crates/ui-widgets/src/display/text.rs
#	crates/ui-widgets/src/form/slider_field.rs
#	crates/ui-widgets/src/layout_components/mod.rs
#	crates/ui-widgets/src/list/mod.rs
#	crates/ui-widgets/src/list/row/paint.rs
#	crates/ui-widgets/src/list/row/show.rs
#	crates/ui-widgets/src/list/stories.rs
#	crates/ui-widgets/src/list/view.rs
#	crates/ui-widgets/src/list/view_stories.rs
#	crates/ui-widgets/src/menu/mod.rs
#	crates/ui-widgets/src/menu/stories.rs
#	crates/ui-widgets/src/pickers/select.rs
#	crates/ui-widgets/src/tabs/document.rs
#	crates/ui-widgets/src/text/number.rs
#	crates/ui-widgets/src/text/zoom_field.rs
#	crates/ui-widgets/src/tile_grid/grid.rs
#	crates/ui-widgets/src/tile_grid/grid/stories.rs
#	crates/ui-widgets/src/tile_grid/mod.rs
#	crates/ui-widgets/tests/it/label/tooltip.rs
#	crates/ui-widgets/tests/it/popover/popup.rs
#	crates/ui-widgets/tests/it/tabs.rs
#	crates/ui-widgets/tests/it/text/mod.rs
#	crates/ui-widgets/tests/it/text/number.rs
#	crates/ui-widgets/tests/it/tile_grid/grid.rs
#	crates/window/Cargo.toml
#	docs/components-index.md
#	docs/porting.md
This commit is contained in:
Dylan M. Taylor committed 2026-11-23 19:01:32 -05:00
commit b138b533fe
768 files changed
+46116 -5268

No files matched your search

Generated
+39 -27
View File
@@ -487,7 +487,7 @@ dependencies = [
"futures-lite",
"parking",
"polling",
"rustix 1.1.5",
"rustix 1.1.6",
"slab",
"windows-sys 0.61.2",
]
@@ -518,7 +518,7 @@ dependencies = [
"cfg-if",
"event-listener",
"futures-lite",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -544,7 +544,7 @@ dependencies = [
"cfg-if",
"futures-core",
"futures-io",
"rustix 1.1.5",
"rustix 1.1.6",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
@@ -1193,7 +1193,7 @@ dependencies = [
"io-lifetimes 3.0.1",
"ipnet",
"maybe-owned",
"rustix 1.1.5",
"rustix 1.1.6",
"rustix-linux-procfs",
"windows-sys 0.61.2",
"winx",
@@ -1208,7 +1208,7 @@ dependencies = [
"cap-primitives",
"io-extras",
"io-lifetimes 3.0.1",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -2053,7 +2053,7 @@ dependencies = [
name = "craft-atomic"
version = "0.1.0"
dependencies = [
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -2080,7 +2080,7 @@ version = "0.1.0"
name = "craft-automation"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"base64 0.23.1",
"craft-behavior",
"craft-control",
"craft-host",
@@ -3485,6 +3485,7 @@ dependencies = [
"egui",
"kurbo",
"serde",
"serde_json",
]
[[package]]
@@ -3654,6 +3655,7 @@ dependencies = [
"craft-atomic",
"craft-docpath",
"craft-host",
"craft-i18n",
"craft-theme",
"fmv-macos-events",
"futures-lite",
@@ -3767,6 +3769,7 @@ version = "0.1.0"
dependencies = [
"craft-behavior",
"craft-host",
"craft-theme",
"craft-ui",
"craft-winprint-gdi",
"egui",
@@ -3846,6 +3849,8 @@ dependencies = [
"egui",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"wasm-bindgen",
"web-sys",
]
[[package]]
@@ -3891,6 +3896,7 @@ dependencies = [
name = "craft-review"
version = "0.1.0"
dependencies = [
"base64 0.23.1",
"craft-behavior",
"craft-host",
"craft-i18n",
@@ -4393,6 +4399,7 @@ dependencies = [
"syn 2.0.119",
"toml",
"typeid",
"wasm-bindgen-futures",
"web-time",
]
@@ -4528,12 +4535,14 @@ dependencies = [
"craft-host",
"craft-i18n",
"craft-keymap",
"craft-svg",
"craft-theme",
"craft-ui-contract",
"craft-ui-macros",
"craft-ui-test-kit",
"craft-ui-widgets",
"egui",
"log",
"serde",
"smallvec",
]
@@ -4552,7 +4561,7 @@ dependencies = [
"image",
"log",
"plist",
"rustix 1.1.5",
"rustix 1.1.6",
"semver",
"serde",
"serde_json",
@@ -4651,7 +4660,10 @@ dependencies = [
name = "craft-web-host"
version = "0.1.0"
dependencies = [
"craft-host",
"craft-platform",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test",
"web-sys",
]
@@ -5398,7 +5410,7 @@ dependencies = [
"drm-ffi",
"drm-fourcc",
"libc",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -5408,7 +5420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690"
dependencies = [
"drm-sys",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -6323,7 +6335,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix 1.1.5",
"rustix 1.1.6",
"windows-sys 0.59.0",
]
@@ -6573,7 +6585,7 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
dependencies = [
"rustix 1.1.5",
"rustix 1.1.6",
"windows-link",
]
@@ -8272,7 +8284,7 @@ dependencies = [
"libc",
"libspa-sys",
"nom 8.0.0",
"rustix 1.1.5",
"rustix 1.1.6",
"system-deps",
]
@@ -8311,7 +8323,7 @@ dependencies = [
"image",
"khronos-egl",
"memmap2",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"tracing",
"wayland-backend",
@@ -9986,7 +9998,7 @@ dependencies = [
"libspa",
"libspa-sys",
"pipewire-sys",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -10117,7 +10129,7 @@ dependencies = [
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix 1.1.5",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
@@ -11194,9 +11206,9 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.5"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags 2.13.2",
"errno",
@@ -11212,7 +11224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
dependencies = [
"once_cell",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -12576,7 +12588,7 @@ dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"rustix 1.1.6",
"windows-sys 0.61.2",
]
@@ -13855,7 +13867,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
dependencies = [
"cc",
"downcast-rs",
"rustix 1.1.5",
"rustix 1.1.6",
"scoped-tls",
"smallvec",
"wayland-sys",
@@ -13868,7 +13880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
dependencies = [
"bitflags 2.13.2",
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-backend",
"wayland-scanner",
]
@@ -13917,7 +13929,7 @@ checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75"
dependencies = [
"bitflags 2.13.2",
"downcast-rs",
"rustix 1.1.5",
"rustix 1.1.6",
"wayland-backend",
"wayland-scanner",
]
@@ -14546,7 +14558,7 @@ dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"rustix 1.1.6",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
@@ -14663,7 +14675,7 @@ dependencies = [
"libc",
"libloading",
"once_cell",
"rustix 1.1.5",
"rustix 1.1.6",
"x11rb-protocol",
]
@@ -14746,7 +14758,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.5",
"rustix 1.1.6",
]
[[package]]
@@ -14906,7 +14918,7 @@ dependencies = [
"hex",
"libc",
"ordered-stream",
"rustix 1.1.5",
"rustix 1.1.6",
"serde",
"serde_repr",
"tracing",
+4 -1
View File
@@ -11,5 +11,8 @@ description = "Crash-safe atomic file writing and replacement for the Craft suit
[lints]
workspace = true
# Plain fsync where F_FULLFSYNC is refused, and the replaced file's extended attributes (`fs`), with
# explicit size queries (`fgetxattr_query`).
[target.'cfg(target_vendor = "apple")'.dependencies]
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
rustix = { version = "1.1.6", default-features = false, features = ["std", "fs"] }
+200 -11
View File
@@ -34,6 +34,13 @@
//! Existing destinations always stage privately and retain their original Unix mode. Restoring
//! an already-matching mode needs no chmod, including on fixed-mode network filesystems.
//!
//! ### Attributes
//! A replaced file is the same document: its stage gets the file's extended attributes (macOS),
//! its hidden and system attributes (Windows, at creation) and its creation date (macOS,
//! Windows) before it is flushed. An extended attribute that cannot be read or copied whole, or
//! passes a bound, refuses the save and leaves the original as it was. Saving through a symbolic
//! link keeps the link and replaces the file it names, so the attributes kept are that file's.
//!
//! ### Platform Characteristics
//! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files
//! open with sharing violations. The rename is retried with exponential backoff (`RenameRetry`).
@@ -59,6 +66,15 @@ pub trait AtomicFs {
/// request mode `0600` for `Private` or `0666` for `PlatformDefault`; the OS applies its
/// umask/default ACL. Other platforms keep their native creation behavior.
fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result<File>;
/// Create the stage like [`AtomicFs::create_new`], carrying over the attributes of the file it
/// replaces that can only be given at creation (Windows: hidden and system). `keep` is the
/// `metadata` of the regular file being replaced: a save through a symbolic link keeps the
/// link and replaces the file it names, so `keep` describes that file, never the link. `None`
/// for a new file. The default ignores `keep` and calls `create_new`.
fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result<File> {
let _ = keep;
self.create_new(path, permissions)
}
/// Flush a written file to durable storage.
fn sync(&self, file: &File) -> io::Result<()>;
/// Rename `from` over `to`, replacing it atomically.
@@ -99,6 +115,21 @@ impl AtomicFs for RealFs {
options.open(path)
}
fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result<File> {
// Given as the file is created, so a hidden file's stage is never visible: Windows has no
// safe call that sets them on an open file afterwards.
#[cfg(windows)]
if let Some(keep) = keep {
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
let mut options = OpenOptions::new();
options.write(true).create_new(true).attributes(keep.file_attributes() & KEPT_ATTRIBUTES);
return options.open(path);
}
#[cfg(not(windows))]
let _ = keep;
self.create_new(path, permissions)
}
fn sync(&self, file: &File) -> io::Result<()> {
sync_file(file)
}
@@ -315,12 +346,16 @@ fn replace_with_options(
check_writable(&target).map_err(|e| read_only_error(e, path))?;
}
let tmp = stage(fs, &dir, &name, path, existing.as_ref(), new_permissions, fill)?;
let tmp = stage(fs, &dir, &name, path, existing.as_ref().map(|m| (target.as_path(), m)), new_permissions, fill)?;
if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) {
let _ = fs.remove(&tmp);
return Err(rename_error(e, path, existed));
}
#[cfg(windows)]
if let Some(replaced) = existing.as_ref().filter(|m| m.is_file()) {
restore_kept_attributes(&target, replaced);
}
// The new bytes are in place; a failed directory fsync can't be undone and must not report
// the save as failed, so it is best effort.
@@ -369,31 +404,35 @@ fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32
}
/// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of
/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when
/// the file it replaces (`replaced`: its resolved path and `metadata`, Unix), keep that file's
/// other attributes ([`keep_attributes`]) and flush it. Permission restoration is skipped when
/// the mode already matches after `fill`; the group bits are dropped when the file cannot be put
/// in the replaced file's group, so they never open the file to a group that was not granted
/// them. A leftover file with the same name is skipped. When any step fails, the temporary file
/// is removed.
/// them. A name something already has (a leftover file, a link, a folder) is skipped, never
/// opened, so nothing planted there receives or redirects the write. When any step fails, the
/// temporary file is removed.
fn stage(
fs: &dyn AtomicFs,
dir: &Path,
name: &str,
path: &Path,
replaced: Option<&std::fs::Metadata>,
replaced: Option<(&Path, &std::fs::Metadata)>,
new_permissions: NewFilePermissions,
fill: impl FnOnce(&mut File) -> io::Result<()>,
) -> io::Result<PathBuf> {
let existed = replaced.is_some();
// Windows files carry only a read-only flag, and a read-only file can't be replaced.
let perms = replaced.filter(|_| cfg!(unix)).map(|m| m.permissions());
let perms = replaced.filter(|_| cfg!(unix)).map(|(_, m)| m.permissions());
// A folder or other non-file at the target has no attributes a stage could carry.
let keep = replaced.map(|(_, m)| m).filter(|m| m.is_file());
// New documents inherit the directory's policy directly: no probe or chmod is needed.
// Existing destinations still stage privately, including when their final mode is shared.
let creation = if existed { NewFilePermissions::Private } else { new_permissions };
for _ in 0..8 {
let tmp = dir.join(temp_name(name));
let mut file = match fs.create_new(&tmp, creation) {
let mut file = match fs.create_new_keeping(&tmp, creation, keep) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) if name_taken(&e, &tmp) => continue,
Err(e) => return Err(write_error(e, path, dir, existed)),
};
let written = fill(&mut file)
@@ -413,7 +452,7 @@ fn stage(
}
// The group bits belong to the replaced file's group, which a new
// inode need not be in (setgid directory, another primary group).
if let Some(replaced) = replaced {
if let Some((_, replaced)) = replaced {
let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?);
let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced);
let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?;
@@ -424,6 +463,7 @@ fn stage(
})
.map_err(|e| permissions_error(e, path))
})
.and_then(|()| keep_attributes(&file, replaced.filter(|(_, m)| m.is_file())).map_err(|e| attributes_error(e, path)))
.and_then(|()| fs.sync(&file).map_err(|e| write_error(e, path, dir, existed)));
#[allow(
clippy::drop_non_drop,
@@ -438,6 +478,143 @@ fn stage(
Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display())))
}
/// Whether creating the stage failed because something already has its name: a file, a link
/// (even a dangling one) or a folder. Windows reports a folder there as access denied.
fn name_taken(e: &io::Error, tmp: &Path) -> bool {
match e.kind() {
io::ErrorKind::AlreadyExists => true,
io::ErrorKind::PermissionDenied => cfg!(windows) && std::fs::symlink_metadata(tmp).is_ok(),
_ => false,
}
}
/// The Windows attributes a replaced file passes on to its stage: hidden and system, the two that
/// say who should see the file. A read-only file is never replaced, the archive bit is the
/// system's to set on a changed file, and the others describe how the volume stores it.
#[cfg(windows)]
const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4;
/// A server that hides dot-named files (Samba, NAS) marks the stage hidden and keeps the mark
/// through the rename: the saved file then gets the replaced file's attributes back. Only when the
/// kept bits differ, since restoring the whole attribute word on a local disk would clear the
/// archive bit backup tools read. Best effort: the new bytes are already in place.
#[cfg(windows)]
fn restore_kept_attributes(target: &Path, replaced: &std::fs::Metadata) {
use std::os::windows::fs::MetadataExt;
let saved = std::fs::symlink_metadata(target).map(|m| m.file_attributes() & KEPT_ATTRIBUTES);
if saved.is_ok_and(|bits| bits != replaced.file_attributes() & KEPT_ATTRIBUTES) {
let _ = std::fs::set_permissions(target, replaced.permissions());
}
}
/// Give the stage what the replaced regular file (`replaced`: its resolved path and `metadata`)
/// carries besides its bytes and mode, before the stage is flushed: on macOS its extended
/// attributes (`copy_xattrs`; an attribute that cannot be kept refuses the save), on macOS and
/// Windows its creation date (best effort: a volume that stores none keeps the stage's own). A
/// saved document is the same document. A new file has nothing to keep.
fn keep_attributes(stage: &File, replaced: Option<(&Path, &std::fs::Metadata)>) -> io::Result<()> {
let Some((target, meta)) = replaced else { return Ok(()) };
#[cfg(target_os = "macos")]
copy_xattrs(target, stage)?;
#[cfg(not(target_os = "macos"))]
let _ = target;
#[cfg(any(target_os = "macos", windows))]
if let Ok(created) = meta.created() {
#[cfg(target_os = "macos")]
use std::os::macos::fs::FileTimesExt;
#[cfg(windows)]
use std::os::windows::fs::FileTimesExt;
let _ = stage.set_times(std::fs::FileTimes::new().set_created(created));
}
#[cfg(not(any(target_os = "macos", windows)))]
let _ = (stage, meta);
Ok(())
}
/// The longest list of extended attribute names read from a replaced file.
#[cfg(target_os = "macos")]
const MAX_XATTR_NAMES_BYTES: usize = 64 * 1024;
/// The most extended attributes copied from a replaced file.
#[cfg(target_os = "macos")]
const MAX_XATTRS: usize = 1024;
/// The largest extended attribute value copied (a resource fork can be larger than ordinary ones).
#[cfg(target_os = "macos")]
const MAX_XATTR_VALUE_BYTES: usize = 16 * 1024 * 1024;
/// The most extended attribute bytes copied from one file in all.
#[cfg(target_os = "macos")]
const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024;
/// Copy the extended attributes of the regular file at `target` (Finder tags, the "Open with"
/// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the
/// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound,
/// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without
/// extended attributes (`ENOTSUP`) is skipped. `com.apple.provenance` belongs to macOS, which
/// gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`).
#[cfg(target_os = "macos")]
fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> {
use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open};
use rustix::io::Errno;
// Never read through a link: the target is already resolved, and a link swapped in since
// names another file. NONBLOCK keeps a FIFO put at the name from hanging the open.
let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) {
Ok(fd) => File::from(fd),
Err(Errno::NOENT | Errno::LOOP) => return Ok(()),
Err(e) => return Err(e.into()),
};
if !source.metadata()?.is_file() {
return Ok(());
}
let names_too_long = || io::Error::other("the extended attribute names exceed 64 KiB");
let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES];
let len = match flistxattr(&source, names.as_mut_slice()) {
Ok(len) => len,
Err(Errno::NOTSUP) => return Ok(()),
Err(Errno::RANGE) => return Err(names_too_long()),
Err(e) => return Err(e.into()),
};
let names = names.get(..len).ok_or_else(names_too_long)?;
let mut total = 0usize;
for (index, name) in names.split(|b| *b == 0).filter(|name| !name.is_empty()).enumerate() {
if index >= MAX_XATTRS {
return Err(io::Error::other("more than 1024 extended attributes"));
}
if name == b"com.apple.provenance" {
continue;
}
let name = std::ffi::CString::new(name).map_err(|_| io::Error::other("an extended attribute name is not valid"))?;
// An empty read buffer reads zero bytes in rustix, not the size: query it explicitly.
let size = fgetxattr_query(&source, &name)?;
if size > MAX_XATTR_VALUE_BYTES || size > MAX_XATTR_TOTAL_BYTES.saturating_sub(total) {
return Err(io::Error::other("the extended attributes exceed 16 MiB per value or 64 MiB in total"));
}
let value = read_xattr_value(size, |buffer| Ok(fgetxattr(&source, &name, buffer)?), || Ok(fgetxattr_query(&source, &name)?))?;
fsetxattr(stage, &name, &value, XattrFlags::empty())?;
total = total.saturating_add(value.len());
}
Ok(())
}
/// Read one attribute value of `size` bytes (already within the bounds) with `read`, then ask
/// its size again with `query_size`. A read that does not fill `size`, or a size that changed,
/// is refused: a growing resource fork returns the prefix that fits instead of an error.
#[cfg(target_os = "macos")]
fn read_xattr_value(
size: usize,
read: impl FnOnce(&mut [u8]) -> io::Result<usize>,
query_size: impl FnOnce() -> io::Result<usize>,
) -> io::Result<Vec<u8>> {
let mut value = vec![0u8; size.max(1)];
let len = read(value.as_mut_slice())?;
let after = query_size()?;
if len != size || after != size {
return Err(io::Error::other("an extended attribute changed size while saving"));
}
value.truncate(len);
Ok(value)
}
/// Exclusively creates and writes `path` with normal OS permissions, without replacing existing files.
/// Use [`WriteOptions`] for private data.
pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> {
@@ -597,11 +774,18 @@ fn resolve_links(path: &Path) -> io::Result<PathBuf> {
Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display())))
}
/// Generates a unique, hidden temporary file name beside `file`.
/// The most bytes of the target's name a temporary name keeps: with the leading `.`, the pid, the
/// counter and `.craft_tmp` the name stays within the 255-byte (Linux, macOS) and 255-unit
/// (Windows) limits however long the target's name is.
const TEMP_STEM_BYTES: usize = 128;
/// Generates a unique, hidden temporary file name beside `file`: `.{file}.{pid}-{n}.craft_tmp`,
/// with `file` cut to its first 128 bytes between characters.
pub fn temp_name(file: &str) -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let stem: String = file.chars().take(64).collect();
let end = file.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|&end| end <= TEMP_STEM_BYTES).last().unwrap_or(0);
let stem = file.get(..end).unwrap_or_default();
#[cfg(not(target_arch = "wasm32"))]
let pid = std::process::id();
#[cfg(target_arch = "wasm32")]
@@ -633,6 +817,11 @@ fn permissions_error(e: io::Error, path: &Path) -> io::Error {
io::Error::new(e.kind(), msg)
}
fn attributes_error(e: io::Error, path: &Path) -> io::Error {
let msg = format!("cannot save {}: the original's extended attributes cannot be kept ({e}){}", path.display(), unchanged(true));
io::Error::new(e.kind(), msg)
}
fn read_only_error(e: io::Error, path: &Path) -> io::Error {
let kept = unchanged(true);
let msg = match e.kind() {
+335
View File
@@ -241,6 +241,341 @@ fn temp_name_format_is_valid() {
assert!(name.ends_with(".craft_tmp"));
}
/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there.
#[derive(Clone, Copy, Debug)]
enum Obstacle {
File,
Folder,
/// A link to the file `outside` beside the stage.
#[cfg(unix)]
Link,
/// A link to `missing` beside the stage, which does not exist.
#[cfg(unix)]
DanglingLink,
}
/// The real filesystem, except that the first `obstacles.len()` stage names get an obstacle
/// planted at them first, as someone racing the save would.
struct Planting {
obstacles: Vec<Obstacle>,
planted: std::cell::RefCell<Vec<PathBuf>>,
}
impl Planting {
fn new(obstacles: Vec<Obstacle>) -> Self {
Self { obstacles, planted: Default::default() }
}
fn plant(&self, at: &Path) -> io::Result<()> {
let next = self.planted.borrow().len();
let Some(&obstacle) = self.obstacles.get(next) else { return Ok(()) };
match obstacle {
Obstacle::File => std::fs::write(at, b"PLANTED")?,
Obstacle::Folder => std::fs::create_dir(at)?,
#[cfg(unix)]
Obstacle::Link => std::os::unix::fs::symlink(at.with_file_name("outside"), at)?,
#[cfg(unix)]
Obstacle::DanglingLink => std::os::unix::fs::symlink(at.with_file_name("missing"), at)?,
}
self.planted.borrow_mut().push(at.to_path_buf());
Ok(())
}
}
impl AtomicFs for Planting {
fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result<File> {
self.plant(path)?;
RealFs.create_new(path, permissions)
}
fn sync(&self, file: &File) -> io::Result<()> {
RealFs.sync(file)
}
fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.rename(from, to)
}
fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> {
RealFs.hard_link(from, to)
}
fn remove(&self, path: &Path) -> io::Result<()> {
RealFs.remove(path)
}
fn sync_dir(&self, dir: &Path) -> io::Result<()> {
RealFs.sync_dir(dir)
}
fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> {
RealFs.set_permissions(file, perms)
}
#[cfg(unix)]
fn set_group(&self, file: &File, gid: u32) -> io::Result<()> {
RealFs.set_group(file, gid)
}
}
/// A stage name something already has (a file, a folder, a link, a dangling link) is skipped,
/// never opened: writing through it would put the user's document where the planter chose. With
/// every name taken the save fails and the original is kept.
#[test]
fn a_name_taken_at_the_stage_is_skipped_and_never_written_through() {
let d = TempDir::new("planted");
let p = d.0.join("doc.craft");
let outside = d.0.join("outside");
std::fs::write(&p, ORIGINAL).unwrap();
std::fs::write(&outside, b"OUTSIDE").unwrap();
#[cfg(unix)]
let obstacles = vec![Obstacle::File, Obstacle::Folder, Obstacle::Link, Obstacle::DanglingLink];
#[cfg(not(unix))]
let obstacles = vec![Obstacle::File, Obstacle::Folder];
let fs = Planting::new(obstacles.clone());
atomic_write_custom(&fs, NO_RETRY, &p, b"new").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"new");
let planted = fs.planted.into_inner();
assert_eq!(planted.len(), obstacles.len(), "every obstacle was met");
for (at, obstacle) in planted.iter().zip(&obstacles) {
let meta = std::fs::symlink_metadata(at).unwrap();
match obstacle {
Obstacle::File => assert_eq!(std::fs::read(at).unwrap(), b"PLANTED", "the planted file is not written"),
Obstacle::Folder => assert!(meta.is_dir() && std::fs::read_dir(at).unwrap().next().is_none(), "the folder is left empty"),
#[cfg(unix)]
Obstacle::Link | Obstacle::DanglingLink => assert!(meta.file_type().is_symlink(), "the link is left as a link"),
}
}
assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE", "nothing was written through a link");
assert!(!outside.with_file_name("missing").exists(), "a dangling link's file was not created");
for at in &planted {
let _ = std::fs::remove_file(at).or_else(|_| std::fs::remove_dir(at));
}
assert_no_temp(&d.0);
// Every name taken: the save is refused and the original kept.
let fs = Planting::new(vec![Obstacle::File; 64]);
let e = atomic_write_custom(&fs, NO_RETRY, &p, b"newer").unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{e}");
assert_eq!(std::fs::read(&p).unwrap(), b"new");
for at in fs.planted.into_inner() {
assert_eq!(std::fs::read(&at).unwrap(), b"PLANTED");
let _ = std::fs::remove_file(at);
}
assert_no_temp(&d.0);
}
/// A name near the 255-byte limit, in four-byte characters, still stages: the temporary name
/// keeps at most 128 bytes of it, cut between characters, and only the target is left.
#[test]
fn a_long_name_stages_and_leaves_only_the_target() {
let d = TempDir::new("long-name");
// 2 + 61 × 4 + 4 = 250 bytes, 67 characters: the first 64 characters alone are 247 bytes.
let name = format!("ab{}.pdf", "\u{1F600}".repeat(61));
assert_eq!(name.len(), 250);
let p = d.0.join(&name);
atomic_write(&p, b"first").unwrap();
atomic_write(&p, b"second").unwrap();
assert_eq!(std::fs::read(&p).unwrap(), b"second");
let left: Vec<_> = std::fs::read_dir(&d.0).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(left, [std::ffi::OsString::from(&name)], "only the target is left");
let staged = temp_name(&name);
assert!(staged.len() <= 255, "{} bytes", staged.len());
assert!(staged.starts_with(&format!(".ab{}.", "\u{1F600}".repeat(31))), "128 bytes of the name, cut between characters: {staged}");
}
/// Reads the extended attribute `name` of `path`, following no further than the path itself.
#[cfg(target_os = "macos")]
fn xattr(path: &Path, name: &str) -> Option<Vec<u8>> {
let size = rustix::fs::getxattr_query(path, name).ok()?;
let mut value = vec![0u8; size.max(1)];
let len = rustix::fs::getxattr(path, name, &mut value[..]).ok()?;
value.truncate(len);
Some(value)
}
/// A save keeps the replaced file's extended attributes (Finder tags, the "Open with" binding,
/// quarantine, binary, empty and resource-fork values), save after save, including one another
/// process sets while the stage is written. Through a symbolic link the link stays and the file it
/// names keeps them. A link swapped in at the target while staging is never read through: its
/// file's attributes stay its own. (`com.apple.provenance` cannot be set by a test; a file that
/// has it saves only because the copy skips it, as macOS refuses writing it.)
#[cfg(target_os = "macos")]
#[test]
fn attributes_set_while_staging_are_kept() {
use rustix::fs::{XattrFlags, setxattr};
let d = TempDir::new("xattrs");
let target = d.0.join("doc.pdf");
std::fs::write(&target, ORIGINAL).unwrap();
let attributes: &[(&str, &[u8])] = &[
("com.apple.metadata:_kMDItemUserTags", b"<plist version=\"1.0\"><array><string>Craft\n6</string></array></plist>"),
("com.apple.LaunchServices.OpenWith", b"bplist00\xd1\x01\x02Wversion\x10\x00"),
("com.apple.quarantine", b"0081;5e0d1d05;Craft;"),
("com.craft.test.binary", b"\0\xff\x80original\0"),
("com.craft.test.empty", b""),
("com.apple.ResourceFork", b"\0\xfffork"),
];
for (name, value) in attributes {
setxattr(&target, *name, value, XattrFlags::empty()).unwrap();
}
// What the system stored (quarantine may be normalised): the saved file must hold the same.
let stored: Vec<_> = attributes.iter().map(|(name, _)| (*name, xattr(&target, name).unwrap())).collect();
for save in 0..2 {
atomic_write_with(&target, |f| {
// Another process tags the original while the new bytes are written.
setxattr(&target, "com.craft.test.late", format!("late {save}").as_bytes(), XattrFlags::empty())?;
f.write_all(b"new")
})
.unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"new");
for (name, value) in &stored {
assert_eq!(xattr(&target, name).as_ref(), Some(value), "save {save} keeps {name}");
}
assert_eq!(xattr(&target, "com.craft.test.late"), Some(format!("late {save}").into_bytes()), "set while staging");
assert_no_temp(&d.0);
}
// Through a link: the link stays, the file it names is replaced and keeps its attributes.
let link = d.0.join("link.pdf");
std::os::unix::fs::symlink(&target, &link).unwrap();
atomic_write(&link, b"through the link").unwrap();
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link");
assert_eq!(std::fs::read(&target).unwrap(), b"through the link");
for (name, value) in &stored {
assert_eq!(xattr(&target, name).as_ref(), Some(value), "the linked file keeps {name}");
}
// A link put at the target while staging names another file: nothing is read through it.
let outside = d.0.join("outside.pdf");
std::fs::write(&outside, b"OUTSIDE").unwrap();
setxattr(&outside, "com.craft.test.private", b"private", XattrFlags::empty()).unwrap();
atomic_write_with(&target, |f| {
std::fs::remove_file(&target)?;
std::os::unix::fs::symlink(&outside, &target)?;
f.write_all(b"swapped")
})
.unwrap();
assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE");
assert_eq!(xattr(&outside, "com.craft.test.private"), Some(b"private".to_vec()));
assert!(!std::fs::symlink_metadata(&target).unwrap().file_type().is_symlink());
assert_eq!(xattr(&target, "com.craft.test.private"), None, "the swapped-in link's file lent nothing");
assert_no_temp(&d.0);
}
/// An attribute past the 16 MiB value bound refuses the save instead of dropping it: the target
/// keeps its bytes and its attribute, and no stage is left.
#[cfg(target_os = "macos")]
#[test]
fn oversized_attributes_refuse_the_save_and_keep_the_target() {
use rustix::fs::{XattrFlags, getxattr_query, setxattr};
let d = TempDir::new("xattrs-bound");
let target = d.0.join("doc.pdf");
std::fs::write(&target, ORIGINAL).unwrap();
// Only a resource fork may be this large; the bytes exist only in this temporary file.
let fork = vec![42u8; 16 * 1024 * 1024 + 1];
setxattr(&target, "com.apple.ResourceFork", &fork, XattrFlags::empty()).unwrap();
let e = atomic_write(&target, b"new").unwrap_err();
assert!(e.to_string().contains("extended attributes"), "{e}");
assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL);
assert_eq!(getxattr_query(&target, "com.apple.ResourceFork").unwrap(), fork.len());
assert_no_temp(&d.0);
}
/// A value read must fill the size first queried and keep it in a second query: a growing
/// resource fork returns the prefix that fits instead of an error. Complete values, empty and
/// binary, are kept as read.
#[cfg(target_os = "macos")]
#[test]
fn an_attribute_read_must_fill_its_size_and_keep_it() {
for bytes in [&b""[..], &b"\0\xffB"[..]] {
let value = read_xattr_value(
bytes.len(),
|buffer| {
buffer[..bytes.len()].copy_from_slice(bytes);
Ok(bytes.len())
},
|| Ok(bytes.len()),
)
.unwrap();
assert_eq!(value, bytes);
}
// A short read, a size that grew after the read, a prefix of a grown value.
for (before, read_len, after) in [(3, 2, 3), (3, 3, 4), (0, 1, 1), (3, 2, 2)] {
let e = read_xattr_value(before, |_| Ok(read_len), || Ok(after)).unwrap_err();
assert!(e.to_string().contains("changed size"), "{before} {read_len} {after}: {e}");
}
let e = read_xattr_value(3, |_| Ok(3), || Err(io::Error::new(io::ErrorKind::PermissionDenied, "recheck refused"))).unwrap_err();
assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
}
/// A saved document is the same document: it keeps its creation date. A new file gets its own.
#[cfg(any(target_os = "macos", windows))]
#[test]
fn a_replaced_files_creation_date_is_kept() {
#[cfg(target_os = "macos")]
use std::os::macos::fs::FileTimesExt;
#[cfg(windows)]
use std::os::windows::fs::FileTimesExt;
let d = TempDir::new("created");
let target = d.0.join("doc.pdf");
std::fs::write(&target, ORIGINAL).unwrap();
// 2020-01-02 03:04:05 UTC.
let then = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_577_934_245);
let file = OpenOptions::new().write(true).open(&target).unwrap();
file.set_times(std::fs::FileTimes::new().set_created(then)).unwrap();
drop(file);
assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the fixture's date is set");
atomic_write(&target, b"new").unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"new");
assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the saved file keeps its creation date");
let fresh = d.0.join("new.pdf");
atomic_write(&fresh, b"new").unwrap();
assert!(std::fs::metadata(&fresh).unwrap().created().unwrap() > then, "a new file has a date of its own");
}
/// A hidden or system file stays hidden or system, and its stage already is while written; a
/// plain file stays plain though the stage's name starts with a dot; a new file gets neither.
/// Through a symbolic link the file it names is the replaced file and keeps its attributes.
#[cfg(windows)]
#[test]
fn hidden_and_system_attributes_are_kept() {
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
const HIDDEN: u32 = 0x2;
const SYSTEM: u32 = 0x4;
let d = TempDir::new("attributes");
let kept = |p: &Path| std::fs::metadata(p).unwrap().file_attributes() & (HIDDEN | SYSTEM);
let plant = |p: &Path, attributes: u32| {
let mut fixture = OpenOptions::new().write(true).create_new(true).attributes(attributes).open(p).unwrap();
fixture.write_all(ORIGINAL).unwrap();
};
for (i, keep) in [0, HIDDEN, SYSTEM, HIDDEN | SYSTEM].into_iter().enumerate() {
let target = d.0.join(format!("doc{i}.pdf"));
plant(&target, keep);
assert_eq!(kept(&target), keep, "the fixture has attributes {keep:#x}");
let mut staged = u32::MAX;
atomic_write_with(&target, |f| {
staged = f.metadata()?.file_attributes() & (HIDDEN | SYSTEM);
f.write_all(b"new")
})
.unwrap();
assert_eq!(staged, keep, "the stage has the target's attributes before it is flushed");
assert_eq!(kept(&target), keep, "the saved file keeps attributes {keep:#x}");
assert_eq!(std::fs::read(&target).unwrap(), b"new");
}
let fresh = d.0.join("new.pdf");
atomic_write(&fresh, b"new").unwrap();
assert_eq!(kept(&fresh), 0, "a new file is neither hidden nor system");
let referent = d.0.join("referent.pdf");
plant(&referent, HIDDEN);
let link = d.0.join("link.pdf");
if let Err(e) = std::os::windows::fs::symlink_file(&referent, &link) {
eprintln!("skipped the link case: creating a symbolic link needs Developer Mode or administrator rights ({e})");
return;
}
atomic_write(&link, b"through the link").unwrap();
assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link");
assert_eq!(std::fs::read(&referent).unwrap(), b"through the link");
assert_eq!(kept(&referent), HIDDEN, "the file the link names stays hidden");
assert_no_temp(&d.0);
}
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_atomic_write_returns_unsupported() {
+9 -7
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-automation"
description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue, frame profiler and frame trace; native only), and recorded actions with the Actions panel (every target)."
description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue and synthetic input on every target; server, client, frame profiler and frame trace native only), and recorded actions with the Actions panel (every target)."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -22,7 +22,7 @@ default = []
# The egui parts: the Actions panel, the control channel's server side (screenshots, synthetic
# input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`,
# `Params` and the recorded actions' model and files.
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"]
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"]
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
screen-testing = ["ui", "agents", "craft-ui/testing"]
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
@@ -31,25 +31,27 @@ screen-testing = ["ui", "agents", "craft-ui/testing"]
agents = ["craft-control/agents", "dep:craft-host"]
[dependencies]
# The screenshot reply's PNG and its inline base64 (the control channel builds on every target with `ui`).
base64 = "0.23"
craft-behavior = { workspace = true, optional = true }
# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the
# CLI's live client), re-exported by `agents` so every app shares one copy.
craft-control = { workspace = true }
# The recorded actions' file picks (`ui`) go through the host on every target.
craft-host = { workspace = true, optional = true }
craft-keymap = { workspace = true, optional = true }
craft-theme = { workspace = true }
craft-ui = { workspace = true, optional = true }
egui = { workspace = true, optional = true }
png = "0.17"
serde = { workspace = true }
serde_json = { workspace = true }
# The screenshot queue encodes and inlines PNGs on every target the control channel builds for.
base64 = "0.22"
craft-host = { workspace = true, optional = true }
craft-platform = { workspace = true }
log = "0.4"
png = "0.17"
# `std::time::Instant` panics on wasm; this is the same type on native.
web-time = "1.1"
# The server, client, profiler and trace.
# The server, client, token files, profiler and trace.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
getrandom = "0.3"
hmac = "0.12"
+201 -4
View File
@@ -1,11 +1,15 @@
//! Named controls over the window's access tree: the controls a client finds by name and role, describes, and places
//! a pointer on. Built with the in-process channel, under the `ui` feature.
//! Named controls over the window's access tree (`ui.find`, `control` targets) and `ui.inspect` (the reported
//! widgets of a window's access tree, and the lookup of the one node a click or a focus names).
//!
//! Both read the tree the window host keeps from the last presented frame ([`WindowHost::keep_access_tree`], which
//! the control server turns on) and walk only the nodes assistive technology reports ([`AccessTree::keys`]): a hidden node,
//! one below it and one behind an open modal are neither listed nor reachable.
use std::collections::HashSet;
use craft_behavior::Mixed;
use craft_ui::runtime::access::Role;
use craft_ui::runtime::egui::access::{AccessTree, NodeKey, name};
use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey, name};
use craft_ui::runtime::windows::WindowHost;
use egui::{Rect, ViewportId};
use serde_json::{Map, Value, json};
@@ -27,6 +31,9 @@ pub const NO_PLACE: &str = "the control has no place on the screen";
/// The largest `index` a target takes.
pub const MAX_INDEX: usize = 1024;
/// The widgets `ui.inspect` lists when the request names no `limit`.
pub const DEFAULT_LIMIT: u64 = 500;
/// The place of a control a target names: its rect in screen points, or the error why it has none.
pub type ControlMap<'a> = &'a dyn Fn(&Target) -> Result<Rect, String>;
@@ -54,7 +61,110 @@ fn plain(text: &str) -> &str {
text.strip_suffix(':').unwrap_or(text).trim()
}
/// The AccessKit role name of a node, as `role` fields spell it.
/// The node a method names: its id or its label.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NodeTarget {
/// The node's id.
Id(u64),
/// The node's label, matched case-insensitively.
Label(String),
}
impl NodeTarget {
/// The node `params` name (`id` or `label`), or none when they name none. `id` is the id `ui.inspect` lists, a
/// decimal string or a number; `label` is a string; naming both is an error. Other fields are the caller's to
/// check; a `null` field is absent.
pub fn from_params(params: &Value) -> Result<Option<NodeTarget>, String> {
let field = |key: &str| params.get(key).filter(|value| !value.is_null());
match (field("id"), field("label")) {
(Some(_), Some(_)) => Err("`id` and `label` exclude each other".into()),
(Some(id), None) => {
let raw = id.as_u64().or_else(|| id.as_str().and_then(|text| text.parse().ok()));
raw.map(|raw| Some(NodeTarget::Id(raw))).ok_or_else(|| "id must be a widget id from ui.inspect".into())
}
(None, Some(Value::String(label))) => Ok(Some(NodeTarget::Label(label.clone()))),
(None, Some(_)) => Err("label must be a string".into()),
(None, None) => Ok(None),
}
}
}
/// What a node that takes `action` is, for the refusal of one that does not.
fn able(action: Declared) -> &'static str {
match action {
Declared::Click => "clickable",
Declared::Focus => "focusable",
Declared::ContextMenu => "a widget with a context menu",
_ => "a widget that takes this action",
}
}
/// Queues `action` on the node `target` names in `viewport`'s kept access tree.
fn inject_node(host: &WindowHost, viewport: ViewportId, target: &NodeTarget, action: Declared) -> Result<(), String> {
let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?;
let node = resolve(&tree, target, action)?;
host.inject_access(viewport, node, action);
Ok(())
}
/// Queues a click of the node `target` names in `viewport`, once the kept tree has it as one reported, enabled,
/// clickable node ([`resolve`]).
pub fn inject_click(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> {
inject_node(host, viewport, target, Declared::Click)
}
/// Queues the context menu of the node `target` names in `viewport`, once the kept tree has it as one reported,
/// enabled node with a context menu ([`resolve`]).
pub fn inject_context_menu(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> {
inject_node(host, viewport, target, Declared::ContextMenu)
}
/// Queues the focus request for the node `target` names in `viewport`, once the kept tree has it as one reported,
/// enabled, focusable node ([`resolve`]).
pub fn inject_focus(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> {
inject_node(host, viewport, target, Declared::Focus)
}
/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none,
/// several, disabled or undeclared. An id must be a reported node; a label matches the reported, enabled nodes that
/// declare `action` and whose label equals it, ignoring case, and exactly one must match.
pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result<NodeKey, String> {
let reported = tree.keys();
let label_of = |key: NodeKey| tree.name_of(key).unwrap_or("unlabelled").to_owned();
let key = match target {
NodeTarget::Id(raw) => {
let key = NodeKey::from_raw(*raw);
if !reported.contains(&key) {
return Err(format!("no widget with id {raw} on screen (run ui.inspect again)"));
}
key
}
NodeTarget::Label(label) => {
let wanted = label.to_lowercase();
let named: Vec<NodeKey> =
reported.iter().copied().filter(|key| tree.name_of(*key).is_some_and(|name| name.to_lowercase() == wanted)).collect();
let usable: Vec<NodeKey> = named.iter().copied().filter(|key| !tree.is_disabled_key(*key) && tree.declares_key(*key, action)).collect();
match usable.as_slice() {
[one] => *one,
[] if named.is_empty() => return Err(format!("no widget labelled {label:?} on screen (try ui.inspect with query)")),
[] if named.iter().any(|key| tree.declares_key(*key, action)) => {
return Err(format!("the widget labelled {label:?} is disabled"));
}
[] => return Err(format!("the widget labelled {label:?} is not {}", able(action))),
many => return Err(format!("{} widgets are labelled {label:?}; name one by id", many.len())),
}
}
};
if tree.is_disabled_key(key) {
return Err(format!("widget {} ({}) is disabled", key.raw(), label_of(key)));
}
if !tree.declares_key(key, action) {
return Err(format!("widget {} ({}) is not {}", key.raw(), label_of(key), able(action)));
}
Ok(key)
}
/// The accesskit role's name as agents' scripts read it (`Button`, `CheckBox`).
fn role_name(tree: &AccessTree, key: NodeKey) -> Option<String> {
match tree.role_of(key)? {
Role::Node(role) => Some(format!("{role:?}")),
@@ -191,3 +301,90 @@ fn find(params: &Value, host: &WindowHost, viewport: ViewportId) -> Result<Value
let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?;
Ok(describe(&tree, target.find(&tree)?))
}
/// One listed widget: `{id, role, depth, enabled, clickable, focusable}` and, where the node says, `label`, `value`,
/// `description`, `rect` (`[x0, y0, x1, y1]` in points), `toggled` (`true`, `false` or `mixed`), `selected`, and
/// `focused: true` for the focused node. The id is a decimal string: 64-bit ids do not survive JSON readers that use
/// doubles.
fn widget(tree: &AccessTree, key: NodeKey, depth: usize, focused: bool) -> Value {
let mut w = Map::new();
w.insert("id".into(), json!(key.raw().to_string()));
w.insert("role".into(), json!(role_name(tree, key)));
w.insert("depth".into(), json!(depth));
w.insert("enabled".into(), json!(!tree.is_disabled_key(key)));
w.insert("clickable".into(), json!(tree.declares_key(key, Declared::Click)));
w.insert("focusable".into(), json!(tree.declares_key(key, Declared::Focus)));
if let Some(label) = tree.name_of(key) {
w.insert("label".into(), json!(label));
}
if let Some(value) = tree.value_of(key) {
w.insert("value".into(), json!(value));
}
if let Some(description) = tree.description_of(key) {
w.insert("description".into(), json!(description));
}
if let Some(rect) = tree.bounds_of(key) {
w.insert("rect".into(), json!([rect.min.x, rect.min.y, rect.max.x, rect.max.y]));
}
if let Some(toggled) = tree.toggled_of(key) {
let toggled = match toggled {
Mixed::Same(true) => "true",
Mixed::Same(false) => "false",
Mixed::Mixed => "mixed",
};
w.insert("toggled".into(), json!(toggled));
}
if let Some(selected) = tree.selected_of(key) {
w.insert("selected".into(), json!(selected));
}
if focused {
w.insert("focused".into(), json!(true));
}
Value::Object(w)
}
/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes
/// of `viewport`'s access tree, in tree order (depth first from the root, which is not listed, children in their
/// order). `query` matches a widget whose label, value or description contains it, ignoring case; `role` its role's
/// name, ignoring case; `focused` whether it is the focused node. `count` is every widget the filters keep, `widgets`
/// the first `limit` of them. No other fields; [`NO_TREE`] before the window presented a frame.
pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result<Value, String> {
let p = Params(params).only(None, &["query", "role", "focused", "limit"])?;
let p = Params(&p);
let query = p.str_field("query")?.map(str::to_lowercase);
let role = p.str_field("role")?.map(str::to_lowercase);
let focused = p.bool_field("focused")?;
let limit = usize::try_from(p.uint_field("limit")?.unwrap_or(DEFAULT_LIMIT)).unwrap_or(usize::MAX);
let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?;
let reported: HashSet<NodeKey> = tree.keys().into_iter().collect();
let root = tree.root_key();
let focus = tree.focused_key();
let (mut widgets, mut count) = (Vec::new(), 0usize);
// A stack, not recursion: the tree comes from the app and may be deep. `walked` keeps a malformed tree that lists
// a node twice from listing it twice or looping.
let mut walked = HashSet::new();
let mut pending: Vec<(NodeKey, usize)> = root.into_iter().map(|key| (key, 0)).collect();
while let Some((key, depth)) = pending.pop() {
if !reported.contains(&key) || !walked.insert(key) {
continue;
}
pending.extend(tree.children_of(key).into_iter().rev().map(|child| (child, depth + 1)));
if Some(key) == root {
continue;
}
let text =
[tree.name_of(key), tree.value_of(key), tree.description_of(key)].into_iter().flatten().collect::<Vec<_>>().join(" ").to_lowercase();
let keep = query.as_ref().is_none_or(|query| text.contains(query.as_str()))
&& role.as_ref().is_none_or(|role| role_name(&tree, key).is_some_and(|name| name.to_lowercase() == *role))
&& focused.is_none_or(|wanted| (key == focus) == wanted);
if !keep {
continue;
}
count += 1;
if widgets.len() < limit {
widgets.push(widget(&tree, key, depth, key == focus));
}
}
Ok(json!({"widgets": widgets, "count": count, "truncated": count > widgets.len()}))
}
+13 -9
View File
@@ -20,7 +20,7 @@ use craft_ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use web_time::Instant;
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply};
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply};
use crate::synthetic::TARGET_CHANGED;
/// A reply: the JSON object the transport writes as one line.
@@ -112,13 +112,16 @@ pub enum Reply {
/// Reply with this JSON now.
Done(Value),
/// A `ui.screenshot`: admit `token` to the queue; `path` is where the app's write authority
/// puts the PNG, `None` inlines it as base64 in the reply.
/// puts the PNG, `None` inlines it as base64 in the reply; `region` is refused at admission
/// when it lies outside the window.
#[non_exhaustive]
Screenshot {
/// Identifies the capture; must differ from every pending token.
token: u64,
/// File to write the PNG to, or `None` to inline it.
path: Option<String>,
/// The part of the window to capture, in points; `None` captures the whole window.
region: Option<egui::Rect>,
/// The viewport to capture.
viewport: egui::ViewportId,
},
@@ -138,10 +141,10 @@ impl Reply {
Reply::AccessTree
}
/// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it
/// when `None`.
pub fn screenshot(token: u64, path: Option<String>, viewport: egui::ViewportId) -> Self {
Self::Screenshot { token, path, viewport }
/// A `ui.screenshot` reply for `token` of `viewport` with what [`ScreenshotParams::from_params`] read: the PNG
/// goes to `params.path` or is inlined when `None`, and shows `params.region` or the whole window.
pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self {
Self::Screenshot { token, path: params.path, region: params.region, viewport }
}
/// `Done` with the [`result_reply`] of a method's result.
@@ -207,8 +210,9 @@ 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::Screenshot { token, path, viewport } => {
if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) {
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()) {
let _ = reply.send(json!({"ok": false, "error": e}));
}
}
@@ -316,7 +320,7 @@ impl ControlChannel {
pub fn finish_captures(&mut self, finished: Vec<Finished>, write: &mut crate::screenshot::PngWriter<'_>) {
for f in finished {
let reply = match f.result {
Ok(image) => screenshot_reply(f.token, image, f.path.as_deref(), write),
Ok(image) => screenshot_reply(f.token, image, f.region, f.geometry, f.path.as_deref(), write),
Err(e) => json!({"ok": false, "error": e}),
};
if let Some(tx) = f.reply {
+47
View File
@@ -0,0 +1,47 @@
//! `ui.dock.apply`: one dock action applied to the app's workspace, and the workspace's `ui.inspect` listing.
use std::hash::Hash;
use craft_behavior::dock::{Action, Workspace};
use craft_ui::docking::PanelSpecs;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use crate::protocol::Params;
/// `ui.dock.apply {action}`: deserializes one dock action and applies it to `workspace` with the permissions `specs`
/// gives, as the dock area does. It returns `Ok({applied: [...]})`, the panels the action closed, in group order; an
/// error is the dock error's text. `None` for any other method.
pub fn dock_method<P: Clone + Eq + Hash + Serialize + DeserializeOwned>(
workspace: &mut Workspace<P>,
specs: &impl PanelSpecs<P>,
locked: bool,
method: &str,
params: &Value,
) -> Option<Result<Value, String>> {
if method != "ui.dock.apply" {
return None;
}
Some(apply(workspace, specs, locked, params))
}
fn apply<P: Clone + Eq + Hash + Serialize + DeserializeOwned>(
workspace: &mut Workspace<P>,
specs: &impl PanelSpecs<P>,
locked: bool,
params: &Value,
) -> Result<Value, String> {
let params = Params(params).only(None, &["action"])?;
let action = params.get("action").cloned().ok_or("missing `action`")?;
let action: Action<P> = serde_json::from_value(action).map_err(|e| format!("`action` is not a dock action: {e}"))?;
let applied = workspace.apply(action, locked, |panel| specs.permissions(panel)).map_err(|e| e.to_string())?;
let applied = serde_json::to_value(applied).map_err(|e| e.to_string())?;
Ok(json!({ "applied": applied }))
}
/// The `dock` field of the app's one `ui.inspect`: the workspace as JSON.
pub fn inspect<P: Serialize>(workspace: &Workspace<P>) -> Value {
// A panel id that cannot be written lists the dock as null rather than failing the whole `ui.inspect`.
serde_json::to_value(workspace).unwrap_or(Value::Null)
}
+50
View File
@@ -0,0 +1,50 @@
//! `ui.pick`: answers the next file picker of a running app.
use std::fmt::Display;
use std::path::PathBuf;
use craft_host::{FileError, Files, Picked};
use serde_json::{Value, json};
use crate::protocol::Params;
/// The fields of `ui.pick`, of which a request names exactly one.
const FIELDS: [&str; 4] = ["files", "folder", "save", "cancel"];
/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`,
/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`.
/// Paths are taken as given; the service settles them as it would a panel's answer.
pub fn pick_method(files: &dyn Files, method: &str, params: &Value) -> Option<Result<Value, String>> {
(method == "ui.pick").then(|| pick(files, params))
}
fn pick(files: &dyn Files, params: &Value) -> Result<Value, String> {
let params = Params(params).only(None, &FIELDS)?;
let read = Params(&params);
let given: Vec<&str> = FIELDS.iter().copied().filter(|field| params.get(*field).is_some()).collect();
let [field] = given.as_slice() else { return Err(refused("give exactly one field")) };
let picked = match *field {
"files" => Picked::Paths(paths(params.get("files"))?),
"cancel" => match read.bool_field("cancel").map_err(refused)? {
Some(true) => Picked::Cancelled,
_ => return Err(refused("cancel must be true")),
},
one => Picked::Paths(vec![PathBuf::from(read.str_field(one).map_err(refused)?.ok_or_else(|| refused(format!("missing `{one}`")))?)]),
};
files.answer_next(picked).map_err(|e| match e {
FileError::Unsupported => "this window's file service takes no automated answers".to_owned(),
other => other.to_string(),
})?;
Ok(json!({"answered": "next"}))
}
/// `files` as a non-empty list of paths.
fn paths(files: Option<&Value>) -> Result<Vec<PathBuf>, String> {
let list = files.and_then(Value::as_array).filter(|list| !list.is_empty());
let paths = list.and_then(|list| list.iter().map(|path| path.as_str().map(PathBuf::from)).collect::<Option<Vec<_>>>());
paths.ok_or_else(|| refused("files must be a non-empty array of path strings"))
}
fn refused(why: impl Display) -> String {
format!("{why}; ui.pick takes exactly one of: {}", FIELDS.join(", "))
}
+10 -1
View File
@@ -3,7 +3,10 @@
//! Drive a running Craft app from tests, agents and the CLI, and record and play actions.
//!
//! [`actions`] and [`ui::actions`] build on every target: the recorded-action list, its player
//! and the Actions panel; so do the agent settings in [`agents`]. The rest is desktop only.
//! and the Actions panel; so do the agent settings in [`agents`] and, with `ui`, the control
//! channel, its screenshots, synthetic input and the access-tree lookups (a web page feeds
//! [`control::ControlChannel`] from its own request queue). The server, client, token files,
//! profiler and trace are desktop only.
//!
//! A transport thread ([`server`], or a channel in tests) turns each JSON line into a
//! [`control::ControlRequest`]; the UI thread drains them between frames through
@@ -29,6 +32,10 @@ pub mod args;
pub mod control;
#[cfg(feature = "ui")]
pub mod dialogs;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
pub mod dock;
#[cfg(feature = "ui")]
pub mod files;
#[cfg(not(target_arch = "wasm32"))]
pub mod profiler;
pub mod protocol;
@@ -40,6 +47,8 @@ pub mod security;
pub mod synthetic;
#[cfg(not(target_arch = "wasm32"))]
pub mod trace;
#[cfg(all(feature = "ui", not(target_arch = "wasm32")))]
pub mod window;
#[cfg(not(target_arch = "wasm32"))]
pub mod client;
+155 -25
View File
@@ -1,7 +1,8 @@
//! `ui.screenshot`: bounded, cancellable capture requests over [`WindowHost::screenshot`].
//!
//! The slot correlates one capture with one image. This queue owns what the slot leaves to the
//! app: request identity (token, output path, reply, the viewport it shoots), deadlines and
//! app: request identity (token, output path, reply, the viewport it shoots and the region of it,
//! refused at admission when outside the window and cropped in [`screenshot_reply`]), deadlines and
//! settling, the admission budget ([`MAX_PENDING`] requests, [`MAX_IMAGE_BYTES`] per image,
//! [`MAX_TOTAL_BYTES`] in all), the document identity fixed at admission, each viewport's geometry
//! epoch recorded at issue so an image is saved only for the layout it was rendered from (a size,
@@ -18,13 +19,16 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use web_time::{Duration, Instant};
use std::time::Duration;
use base64::Engine as _;
use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost};
use egui::{ColorImage, ViewportId};
use egui::{ColorImage, Rect, ViewportId};
use serde_json::Value;
use web_time::Instant;
use crate::control::ControlResponse;
use crate::protocol::Params;
/// Requests outstanding at once (issued, completed, waiting for geometry or waiting to be issued).
pub const MAX_PENDING: usize = 4;
@@ -146,6 +150,7 @@ pub struct PendingCapture {
token: u64,
viewport: ViewportId,
path: Option<String>,
region: Option<Rect>,
reply: Option<Sender<ControlResponse>>,
deadline: Instant,
ready_at: Instant,
@@ -178,6 +183,10 @@ pub struct Finished {
pub token: u64,
/// File to write the PNG to; `None` inlines it in the reply.
pub path: Option<String>,
/// The part of the window to crop the image to, in points; `None` keeps the whole window.
pub region: Option<egui::Rect>,
/// The layout the image was captured from; the crop and the reply's `pixels_per_point` read it.
pub geometry: CaptureGeometry,
/// Where to send the answer.
pub reply: Option<Sender<ControlResponse>>,
/// The captured image, or the error text for the reply.
@@ -185,9 +194,17 @@ pub struct Finished {
}
impl Finished {
/// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given.
pub fn new(token: u64, path: Option<String>, reply: Option<Sender<ControlResponse>>, result: Result<Arc<ColorImage>, String>) -> Self {
Self { token, path, reply, result }
/// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given,
/// cropped to `region` as `geometry` scales it.
pub fn new(
token: u64,
path: Option<String>,
region: Option<egui::Rect>,
geometry: CaptureGeometry,
reply: Option<Sender<ControlResponse>>,
result: Result<Arc<ColorImage>, String>,
) -> Self {
Self { token, path, region, geometry, reply, result }
}
}
@@ -198,6 +215,8 @@ pub struct ScreenshotRequest {
pub token: u64,
/// Where to write the PNG, when the reply is a file.
pub path: Option<String>,
/// The part of the window to capture, in points; `None` captures the whole window.
pub region: Option<Rect>,
/// The viewport to capture.
pub viewport: ViewportId,
/// Where the reply goes.
@@ -209,9 +228,9 @@ pub struct ScreenshotRequest {
}
impl ScreenshotRequest {
/// A request for `viewport` answered on `reply`: no file, no document, no settle delay.
/// A request for the whole of `viewport` answered on `reply`: no file, no document, no settle delay.
pub fn new(token: u64, viewport: ViewportId, reply: Sender<ControlResponse>) -> Self {
Self { token, path: None, viewport, reply, document: None, settle_ms: 0.0 }
Self { token, path: None, region: None, viewport, reply, document: None, settle_ms: 0.0 }
}
}
@@ -220,6 +239,7 @@ struct WaitingAdmit {
token: u64,
viewport: ViewportId,
path: Option<String>,
region: Option<Rect>,
reply: Sender<ControlResponse>,
deadline: Instant,
settle_ms: f64,
@@ -312,17 +332,19 @@ impl Captures {
/// `the viewport is not capturable ({w}×{h} points at {ppp} px/pt, texture side {side})`,
/// `a {N} MiB screenshot is over the {MAX_IMAGE_BYTES / 1 MiB} MiB per-image limit` (`N` the
/// expected bytes / 1 MiB, integer division), or
/// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`.
/// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`, or
/// `screenshot {token} failed: the region must lie inside the {w}×{h}-point window`. The budget is reserved for
/// the whole window, region or not: the slot retains the whole image until it is cropped.
/// While the viewport's geometry is not recorded the request waits.
pub fn admit(&mut self, request: ScreenshotRequest, now: Instant) -> Result<(), (Sender<ControlResponse>, String)> {
let ScreenshotRequest { token, path, viewport, reply, document, settle_ms } = request;
let ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms } = request;
if self.records.iter().any(|r| r.token == token) || self.waiting.iter().any(|w| w.token == token) {
return Err((reply, format!("screenshot token {token} is already pending")));
}
if self.pending() >= MAX_PENDING {
return Err((reply, format!("too many screenshots pending (at most {MAX_PENDING})")));
}
let request = WaitingAdmit { token, viewport, path, reply, deadline: now + DEADLINE, settle_ms, document };
let request = WaitingAdmit { token, viewport, path, region, reply, deadline: now + DEADLINE, settle_ms, document };
match self.windows.get(&viewport).copied() {
None => {
self.waiting.push(request);
@@ -335,7 +357,7 @@ impl Captures {
/// Queues `request` at `geometry` and `epoch`, what its viewport's window recorded.
fn admit_with_geometry(&mut self, request: WaitingAdmit, geometry: CaptureGeometry, epoch: u64) -> Result<(), (Sender<ControlResponse>, String)> {
let WaitingAdmit { token, viewport, path, reply, deadline, settle_ms, document } = request;
let WaitingAdmit { token, viewport, path, region, reply, deadline, settle_ms, document } = request;
// The request's clock started when it arrived.
let arrived = deadline - DEADLINE;
if self.records.iter().any(|r| r.token == token) {
@@ -348,6 +370,9 @@ impl Captures {
Ok(bytes) => bytes,
Err(e) => return Err((reply, e)),
};
if let Err(e) = check_region(token, region, &geometry) {
return Err((reply, e));
}
if let Err(e) = aggregate_budget(self.reserved_bytes(), expected) {
return Err((reply, e));
}
@@ -357,6 +382,7 @@ impl Captures {
token,
viewport,
path,
region,
reply: Some(reply),
deadline,
ready_at: arrived + Duration::from_secs_f64(settle / 1000.0),
@@ -538,6 +564,9 @@ impl Captures {
finished.push(Finished {
token: w.token,
path: w.path,
region: w.region,
// No geometry was recorded for a waiting request; the result is an error, so nothing reads it.
geometry: CaptureGeometry::new([0.0, 0.0], 0),
reply: Some(w.reply),
result: Err(format!("screenshot {} cancelled: {reason}", w.token)),
});
@@ -549,6 +578,8 @@ impl Captures {
finished.push(Finished {
token: r.token,
path: r.path.take(),
region: r.region,
geometry: r.geometry,
reply: r.reply.take(),
result: Err(format!("screenshot {} cancelled: {reason}", r.token)),
});
@@ -580,11 +611,23 @@ fn aggregate_budget(others: usize, expected: usize) -> Result<(), String> {
Ok(())
}
/// Whether `region` lies inside the window of `geometry`: the request is refused otherwise, never cropped to a
/// smaller image than it asked for. `None` (the whole window) always fits.
fn check_region(token: u64, region: Option<Rect>, geometry: &CaptureGeometry) -> Result<(), String> {
let Some(region) = region else { return Ok(()) };
let [width, height] = geometry.size_points;
if region.min.x >= 0.0 && region.min.y >= 0.0 && region.max.x <= width && region.max.y <= height {
return Ok(());
}
Err(format!("screenshot {token} failed: the region must lie inside the {width}×{height}-point window"))
}
/// Finalise a request at a new geometry: recheck the per-image and aggregate limits (excluding
/// its old reservation), take the new reservation and restart settling.
/// its old reservation) and that its region still fits, take the new reservation and restart settling.
fn revalidate_reservation(r: &mut PendingCapture, others: usize, geometry: CaptureGeometry, epoch: u64) -> Result<(), String> {
let expected = image_budget(&geometry)?;
aggregate_budget(others, expected)?;
check_region(r.token, r.region, &geometry)?;
r.reserved_bytes = expected;
r.geometry = geometry;
r.epoch = epoch;
@@ -597,7 +640,7 @@ fn finish(r: &mut PendingCapture, result: Result<Arc<ColorImage>, String>) -> Fi
if let Some(slot) = r.slot.take() {
slot.cancel();
}
Finished { token: r.token, path: r.path.take(), reply: r.reply.take(), result }
Finished { token: r.token, path: r.path.take(), region: r.region, geometry: r.geometry, reply: r.reply.take(), result }
}
/// The returned image must be the issued viewport (within a pixel) or a uniform renderer fit
@@ -678,40 +721,127 @@ pub fn encode_png(width: usize, height: usize, rgba: &[u8]) -> Result<Vec<u8>, S
/// authorized workspace. `Err` is the reply's error text.
pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a;
/// The reply for a finished image:
/// - an image over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows):
/// A validated `ui.screenshot`: where the PNG goes and which part of the window it shows.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct ScreenshotParams {
/// File to write the PNG to, or `None` to inline it.
pub path: Option<String>,
/// The part of the window to capture as `[x0, y0, x1, y1]` in points, finite and ordered; `None` captures the
/// whole window.
pub region: Option<egui::Rect>,
}
impl ScreenshotParams {
/// `{path?, region?}`, no other fields. `path` is a string; `region` is `[x0, y0, x1, y1]` in points, four finite
/// numbers with `x0 < x1` and `y0 < y1`: ``"region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and
/// y0 < y1"`` otherwise. Whether it lies inside the window is checked at admission, against the window's geometry.
pub fn from_params(params: &Value) -> Result<ScreenshotParams, String> {
let p = Params(params).only(None, &["path", "region"])?;
let p = Params(&p);
let path = p.str_field("path")?.map(str::to_owned);
let region = p.0.get("region").map(region_param).transpose()?;
Ok(ScreenshotParams { path, region })
}
}
/// `region`: `[x0, y0, x1, y1]`, finite and ordered.
fn region_param(region: &Value) -> Result<Rect, String> {
const SHAPE: &str = "region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and y0 < y1";
let number = |v: &Value| v.as_f64().map(|n| n as f32).filter(|n| n.is_finite());
let corners = match region.as_array().map(Vec::as_slice) {
Some([x0, y0, x1, y1]) => number(x0).zip(number(y0)).zip(number(x1).zip(number(y1))),
_ => None,
};
corners
.filter(|((x0, y0), (x1, y1))| x0 < x1 && y0 < y1)
.map(|((x0, y0), (x1, y1))| Rect::from_min_max(egui::pos2(x0, y0), egui::pos2(x1, y1)))
.ok_or_else(|| SHAPE.into())
}
/// The pixel columns and rows `[x0, y0, x1, y1)` of `region` in an image of `size` captured at `geometry`. The image
/// scale is `size / geometry.size_points`, never `pixels_per_point`: a renderer that fitted the surface to its
/// texture side returns a smaller image of the same layout. Edges round to the nearest pixel and are clamped to the
/// image; `None` when nothing of the region is left or the geometry has no area.
fn crop_pixels(region: Rect, geometry: &CaptureGeometry, size: [usize; 2]) -> Option<[usize; 4]> {
let [width, height] = geometry.size_points;
if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) {
return None;
}
let (sx, sy) = (size[0] as f32 / width, size[1] as f32 / height);
// `as usize` saturates: a negative or NaN edge is 0, an edge past the image is clamped below.
let px = |v: f32, scale: f32, max: usize| ((v * scale).round() as usize).min(max);
let [x0, x1] = [px(region.min.x, sx, size[0]), px(region.max.x, sx, size[0])];
let [y0, y1] = [px(region.min.y, sy, size[1]), px(region.max.y, sy, size[1])];
(x0 < x1 && y0 < y1).then_some([x0, y0, x1, y1])
}
/// The reply for a finished image, cropped to `region` (in points; `None` keeps the whole image) at the scale of the
/// image to `geometry`, the layout it was captured from:
/// - a region with no pixels left in the image:
/// `{"ok": false, "error": "screenshot {token} failed: the region has no pixels in the captured image"}`;
/// - a crop over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows):
/// `{"ok": false, "error": "screenshot {token} failed: the image exceeds the {MAX_IMAGE_BYTES / 1 MiB} MiB encode budget"}`;
/// - no `path`: `{"ok": true, "result": {"base64": <standard base64 of the PNG>, "mime": "image/png", "width", "height"}}`,
/// with no size limit beyond the encode budget;
/// - no `path`: `{"ok": true, "result": {"base64": <standard base64 of the PNG>, "mime": "image/png", "width", "height",
/// "pixels_per_point"}}`, with no size limit beyond the encode budget;
/// - a `path`: the PNG goes to `write(path, bytes)`, the app's file authority (limited to its
/// authorized workspace), and the reply is
/// `{"ok": true, "result": {"path", "width", "height"}}`;
/// `{"ok": true, "result": {"path", "width", "height", "pixels_per_point"}}`;
/// - an encode or write error `e`: `{"ok": false, "error": e}`.
///
/// `width` and `height` are the crop's pixels; `pixels_per_point` is `geometry`'s, the window's scale.
/// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap.
pub fn screenshot_reply(token: u64, image: Arc<ColorImage>, path: Option<&str>, write: &mut PngWriter<'_>) -> ControlResponse {
pub fn screenshot_reply(
token: u64,
image: Arc<ColorImage>,
region: Option<egui::Rect>,
geometry: CaptureGeometry,
path: Option<&str>,
write: &mut PngWriter<'_>,
) -> ControlResponse {
let [w, h] = image.size;
let Some(bytes) = w.checked_mul(h).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else {
let crop = match region {
None => Some([0, 0, w, h]),
Some(region) => crop_pixels(region, &geometry, [w, h]),
};
let Some([x0, y0, x1, y1]) = crop.filter(|[x0, y0, x1, y1]| x0 < x1 && y0 < y1) else {
return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the region has no pixels in the captured image")});
};
let (cw, ch) = (x1 - x0, y1 - y0);
let Some(bytes) = cw.checked_mul(ch).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else {
return serde_json::json!({
"ok": false,
"error": format!("screenshot {token} failed: the image exceeds the {} MiB encode budget", MAX_IMAGE_BYTES / (1 << 20)),
});
};
let mut rgba = Vec::with_capacity(bytes);
rgba.extend(image.pixels.iter().flat_map(|c| c.to_array()));
for y in y0..y1 {
let row = y.checked_mul(w).and_then(|start| image.pixels.get(start + x0..start + x1));
let Some(row) = row else {
return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the image has fewer pixels than its size")});
};
rgba.extend(row.iter().flat_map(|c| c.to_array()));
}
drop(image);
let png = match encode_png(w, h, &rgba) {
let png = match encode_png(cw, ch, &rgba) {
Ok(png) => png,
Err(e) => return serde_json::json!({"ok": false, "error": e}),
};
let ppp = geometry.pixels_per_point;
let Some(path) = path else {
return serde_json::json!({
"ok": true,
"result": {"base64": base64::engine::general_purpose::STANDARD.encode(png), "mime": "image/png", "width": w, "height": h},
"result": {
"base64": base64::engine::general_purpose::STANDARD.encode(png),
"mime": "image/png",
"width": cw,
"height": ch,
"pixels_per_point": ppp,
},
});
};
match write(path, &png) {
Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": w, "height": h}}),
Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": cw, "height": ch, "pixels_per_point": ppp}}),
Err(e) => serde_json::json!({"ok": false, "error": e}),
}
}
+41 -6
View File
@@ -271,11 +271,15 @@ fn token_conflict() -> AutomationError {
AutomationError::BadRequest("use either a control token or a control token file, not both".into())
}
/// The most a Windows token file read takes: a token, its newline and room for stray whitespace.
#[cfg(windows)]
const TOKEN_FILE_MAX_BYTES: u64 = 4096;
/// Validates what was opened, not just the name: the file must be a regular file that no other
/// local principal can read, so a group- or world-readable token is refused rather than trusted.
fn read_token_file(path: &Path) -> Result<String, AutomationError> {
let io = |e: std::io::Error| AutomationError::Io(format!("{}: {e}", path.display()));
let mut file = std::fs::File::open(path).map_err(io)?;
let file = std::fs::File::open(path).map_err(io)?;
let meta = file.metadata().map_err(io)?;
if !meta.is_file() {
return Err(AutomationError::Io(format!("{}: control token file is not a regular file", path.display())));
@@ -291,7 +295,25 @@ fn read_token_file(path: &Path) -> Result<String, AutomationError> {
)));
}
}
let token = std::io::read_to_string(&mut file).map_err(io)?;
// A Windows file inherits its folder's access list, so the owner and the access list are read with the contents
// through one handle: nothing swapped in at the path between the check and the read gets through.
#[cfg(windows)]
let token = {
use craft_platform::owner_only;
drop(file);
let me = owner_only::current_user_sid().map_err(io)?;
let (sddl, bytes) = owner_only::read_with_sddl(path, TOKEN_FILE_MAX_BYTES).map_err(io)?;
if let Some(problem) = owner_only::foreign_access(&sddl, &me) {
return Err(AutomationError::Io(format!(
"{}: control token file can be reached by others: {problem}; restrict it to its owner",
path.display()
)));
}
String::from_utf8(bytes).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?
};
#[cfg(not(windows))]
let token = std::io::read_to_string(&file).map_err(io)?;
let token = token.trim().to_owned();
validate_token(&token)?;
Ok(token)
@@ -309,6 +331,17 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
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.
#[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())));
}
}
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
}
@@ -317,10 +350,12 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
/// validated. Neither given: a generated token. A `token_file` that exists is read: it must be a
/// regular file (`I/O: <path>: control token file is not a regular file`) and on Unix have no
/// group or other permission bits (`I/O: <path>: control token file is readable by group or
/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), 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 token and a newline); losing that create race to
/// another process reads the winner's file instead.
/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), on Windows be
/// owned by the user with an access list of the user and SYSTEM only (`I/O: <path>: control token
/// 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.
pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result<String, AutomationError> {
if supplied.is_some() && token_file.is_some() {
return Err(token_conflict());
+5 -1
View File
@@ -56,7 +56,8 @@ pub fn listen(port: u16, token: String, host: WindowHost) -> std::io::Result<(Re
/// Serves a listener bound earlier (an app's `--control`, bound before its window opens) until the
/// returned [`Listening`] is dropped: authenticates each connection with `token`, forwards its
/// requests to the receiver and wakes the root window through `host`. The app prints
/// requests to the receiver and wakes the root window through `host`, which keeps each window's access tree
/// ([`WindowHost::keep_access_tree`]) for [`crate::access`]. The app prints
/// `control server listening on <addr>`.
pub fn serve(listener: TcpListener, token: String, host: WindowHost) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
serve_with_deadline(listener, token, host, AUTH_DEADLINE)
@@ -73,6 +74,9 @@ pub fn serve_with_deadline(
) -> std::io::Result<(Receiver<ControlRequest>, Listening)> {
let (tx, rx) = channel::<ControlRequest>();
let addr = listener.local_addr()?;
// `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept
// from before the first connection, so the first request already finds it.
host.keep_access_tree();
let stop = Arc::new(AtomicBool::new(false));
let stopped = Arc::clone(&stop);
let accept = std::thread::Builder::new().name("control server".into()).spawn(move || {
+138 -26
View File
@@ -1,10 +1,11 @@
//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`,
//! `ui.type`, `ui.ime` and `ui.capsLock`.
//! 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`.
//!
//! This module reads and validates the protocol's parameters; the window host queues the input
//! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`],
//! [`WindowHost::inject_key`], [`WindowHost::inject_release`], [`WindowHost::inject_text`],
//! [`WindowHost::inject_ime`]), one step per pass, so a move, a press, a release, a key's down and up and each
//! [`WindowHost::inject_ime`], [`WindowHost::inject_files`], [`WindowHost::inject_access`]), one step per pass, so a
//! move, a press, a release, a key's down and up and each
//! composition step land on separate passes as real input does. A request is validated whole before anything of it is
//! queued, so a refused one leaves no half-queued press. The host answers the
//! waiting replies once [`WindowHost::injected_idle`] turns true ([`crate::control::ControlChannel::poll_input`]), and
@@ -18,6 +19,13 @@
//! maps to the screen through its canvas ([`DocumentMap`]). Document-coordinate `ui.pointer` events are the
//! application's own method: they drive its tool host, not the window. With `control: {name, role?, within?, index?}`
//! a point is the centre of that control's rect, `x` and `y` an offset from it ([`access::Target`]).
//!
//! 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`.
use std::path::PathBuf;
use craft_behavior::PointerButton;
use craft_keymap::{Key, Mods};
@@ -25,7 +33,7 @@ use craft_ui::runtime::windows::{Released, WindowHost};
use egui::{Pos2, Vec2, ViewportId, pos2, vec2};
use serde_json::Value;
use crate::access;
use crate::access::{self, NodeTarget, inject_click, inject_context_menu, inject_focus};
use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params};
/// Most clicks one `ui.click` may ask for (`count`).
@@ -86,9 +94,21 @@ impl At {
}
return Ok(Self::Control { target: access::Target::from_params(control)?, offset: vec2(x, y) });
}
Self::in_space(p, pos2(x, y))
}
/// `x` and `y`, both required, in the space `coordinates` names (`screen`, the default, or `document`).
fn required(p: &Params<'_>) -> Result<Self, String> {
let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT));
let x = p.number_in("x", "x", range)?.ok_or_else(|| "missing `x`".to_owned())? as f32;
let y = p.number_in("y", "y", range)?.ok_or_else(|| "missing `y`".to_owned())? as f32;
Self::in_space(p, pos2(x, y))
}
fn in_space(p: &Params<'_>, pos: Pos2) -> Result<Self, String> {
Ok(match p.choice("coordinates", "coordinates", &["screen", "document"])?.unwrap_or("screen") {
"document" => Self::Document(pos2(x, y), p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))),
_ => Self::Screen(pos2(x, y)),
"document" => Self::Document(pos, p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))),
_ => Self::Screen(pos),
})
}
@@ -141,12 +161,44 @@ fn key(p: &Params<'_>) -> Result<Option<Key>, String> {
p.choice("key", "key", &[])?.map(|name| Key::parse(name).ok_or_else(|| format!("unknown key `{name}`"))).transpose()
}
/// Where a `ui.click` goes.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ClickTarget {
/// A position.
At(At),
/// A node of the access tree.
Node(NodeTarget),
}
/// A validated `ui.focus`: moves the focus to a node of the access tree.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Focus {
/// The node that takes the focus.
pub target: NodeTarget,
}
impl Focus {
/// `{id | label}`: the node to focus, exactly one of the two, no other fields (``"missing `id` or `label`"``).
pub fn from_params(params: &Value) -> Result<Focus, String> {
let p = Params(params).only(None, &["id", "label"])?;
NodeTarget::from_params(&p)?.map(|target| Focus { target }).ok_or_else(|| "missing `id` or `label`".into())
}
/// Queues the focus request for the node in `viewport`; a node the kept tree does not have as one reported,
/// enabled, focusable node is refused ([`crate::access::resolve`]).
pub fn inject(&self, host: &WindowHost, viewport: ViewportId) -> Result<(), String> {
inject_focus(host, viewport, &self.target)
}
}
/// A validated `ui.click`.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Click {
/// Target position.
pub at: At,
/// Where the click goes: a position or a node of the access tree.
pub target: ClickTarget,
/// The button pressed.
pub button: PointerButton,
/// Number of clicks (2 is a double click).
@@ -158,31 +210,63 @@ pub struct Click {
}
impl Click {
/// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}`, no other fields (`Params::only`). `button`
/// defaults to `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is
/// ``"`count` must be at most 256 (got {count})"``. Other errors are the `Params` validators'.
/// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}` for a point, or `{id | label, button?}` for a node
/// of the access tree ([`NodeTarget::from_params`]); no other fields (`Params::only`). `button` defaults to
/// `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is
/// ``"`count` must be at most 256 (got {count})"``. A node is clicked by its own action, so with one only the
/// primary button (its click) and the secondary one (its context menu) are allowed, and a point, `count` above 1,
/// `hold` and held modifiers are refused. Other errors are the `Params` validators'.
pub fn from_params(params: &Value) -> Result<Self, String> {
let p = only(params, &["button", "count", "hold"])?;
let p = only(params, &["button", "count", "hold", "id", "label"])?;
let p = Params(&p);
let count = p.uint_field("count")?.unwrap_or(1);
if count > MAX_CLICKS {
return Err(format!("`count` must be at most {MAX_CLICKS} (got {count})"));
}
Ok(Self {
at: At::from_params(&p)?,
button: button(&p)?.unwrap_or(PointerButton::Primary),
count,
mods: p.modifiers(&KEY_MODIFIERS)?,
hold: p.bool_field("hold")?.unwrap_or(false),
})
let pressed = button(&p)?;
let mods = p.modifiers(&KEY_MODIFIERS)?;
let hold = p.bool_field("hold")?.unwrap_or(false);
if let Some(node) = NodeTarget::from_params(p.0)? {
if POINT.iter().any(|field| p.0.get(field).is_some()) {
return Err("a click names a node (`id` or `label`) or a point (`x`, `y`), not both".into());
}
if count > 1 {
return Err("`count` goes with a point, not a node".into());
}
if hold {
return Err("`hold` goes with a point, not a node".into());
}
if !mods.is_none() {
return Err("modifiers go with a point, not a node".into());
}
let button = match pressed {
None | Some(PointerButton::Primary) => PointerButton::Primary,
Some(PointerButton::Secondary) => PointerButton::Secondary,
Some(_) => return Err("a node takes a primary or a secondary click, not the middle button".into()),
};
return Ok(Self { target: ClickTarget::Node(node), button, count: 1, mods, hold: false });
}
Ok(Self { target: ClickTarget::At(At::from_params(&p)?), button: pressed.unwrap_or(PointerButton::Primary), count, mods, hold })
}
/// Queues a move to the target, then `count` presses and releases of the button, in `viewport`.
/// Queues a move to the point, then `count` presses and releases of the button, in `viewport`; for a node, its
/// click, or its context menu for the secondary button, once the kept tree has it as one reported, enabled node
/// that declares the action ([`crate::access::resolve`]).
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
let count = u32::try_from(self.count).unwrap_or(u32::MAX);
let at = self.at.place(host, viewport, map)?;
host.inject_click(viewport, at, self.button, count, self.mods, self.hold);
Ok(())
match &self.target {
ClickTarget::At(at) => {
let count = u32::try_from(self.count).unwrap_or(u32::MAX);
host.inject_click(viewport, at.place(host, viewport, map)?, self.button, count, self.mods, self.hold);
Ok(())
}
ClickTarget::Node(node) => {
if matches!(self.button, PointerButton::Secondary) {
inject_context_menu(host, viewport, node)
} else {
inject_click(host, viewport, node)
}
}
}
}
}
@@ -199,12 +283,12 @@ pub struct Move {
}
impl Move {
/// `{x?, y?, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`].
/// `{x, y, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`].
pub fn from_params(params: &Value) -> Result<Self, String> {
let p = only(params, &["rest"])?;
let p = Params(&p);
Ok(Self {
at: At::from_params(&p)?,
at: At::required(&p)?,
mods: p.modifiers(&KEY_MODIFIERS)?,
rest: p.number_in("rest", "rest", Some((0.0, MAX_REST)))?.unwrap_or(0.0),
})
@@ -342,6 +426,8 @@ pub fn caps_lock_from_params(params: &Value) -> Result<Option<bool>, String> {
pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Option<Result<(), String>> {
Some(match method {
"ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)),
"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.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)),
@@ -353,6 +439,32 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V
})
}
/// `ui.drop {paths, hover_only?, x?, y?, coordinates?}`: hovers the files `paths` names (a non-empty array of
/// strings) over the point, where the pointer is when neither `x` nor `y` is given, and drops them in the following
/// step unless `hover_only`. The point is mapped as every request's is; a drop carries no modifiers, so a held one is
/// refused.
fn drop_files(params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
const PATHS: &str = "paths must be a non-empty array of strings";
let p = only(params, &["paths", "hover_only"])?;
let p = Params(&p);
if !p.modifiers(&KEY_MODIFIERS)?.is_none() {
return Err("`ui.drop` takes no modifiers".into());
}
let paths: Vec<PathBuf> = match p.0.get("paths") {
None => return Err("missing `paths`".into()),
Some(Value::Array(items)) => items.iter().map(|item| item.as_str().map(PathBuf::from)).collect::<Option<_>>().ok_or(PATHS)?,
Some(_) => return Err(PATHS.into()),
};
if paths.is_empty() {
return Err(PATHS.into());
}
let hover_only = p.bool_field("hover_only")?.unwrap_or(false);
let at = (p.0.get("x").is_some() || p.0.get("y").is_some() || p.0.get("control").is_some()).then(|| At::from_params(&p)).transpose()?;
let at = at.map(|at| at.place(host, viewport, map)).transpose()?;
host.inject_files(viewport, at, paths, !hover_only);
Ok(())
}
/// A validated `ui.type`: `{text}`, a string.
fn text(params: &Value) -> Result<String, String> {
let p = Params(params).only(None, &["text"])?;
+25
View File
@@ -0,0 +1,25 @@
//! `ui.window`: window commands through the framework's one window-command path.
use craft_ui::runtime::windows::{WindowAction, WindowHost};
use egui::ViewportId;
use serde_json::{Value, json};
use crate::protocol::Params;
/// `ui.window {maximized: bool}` sends `WindowAction::SetMaximized` through `WindowHost::act` and returns `Ok({})`, or
/// `Err` when `act` returns false (no window commands, as on wasm). `None` for any other method. It keeps no state.
pub fn window_method(host: &WindowHost, viewport: ViewportId, method: &str, params: &Value) -> Option<Result<Value, String>> {
if method != "ui.window" {
return None;
}
Some(run(host, viewport, params))
}
fn run(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result<Value, String> {
let params = Params(params).only(None, &["maximized"])?;
let maximized = Params(&params).bool_field("maximized")?.ok_or("missing `maximized`")?;
if !host.act(viewport, WindowAction::SetMaximized(maximized)) {
return Err("this platform has no window commands".to_owned());
}
Ok(json!({}))
}
+158 -4
View File
@@ -1,14 +1,20 @@
//! Named controls through the protocol: a `control` target places a click on the control, `ui.find` describes it, and
//! a target that is ambiguous, unknown or asked for too early queues nothing.
//! Named controls through the protocol (`control` targets, `ui.find`), `ui.inspect` over the window's kept access
//! tree, and `ui.click` and `ui.focus` on a node it names: tree order and filters, what an open modal hides, a click,
//! a context menu and a focus reaching their widget, and the targets refused before anything is queued.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_automation::access::{AMBIGUOUS, NO_CONTROL, NO_TREE, access_method};
use craft_automation::access::{AMBIGUOUS, NO_CONTROL, NO_TREE, NodeTarget, access_method, inspect, resolve};
use craft_automation::synthetic::input_method;
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Show as _, clicked};
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
use craft_ui::dialog::Dialog;
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::runtime::egui::access::Declared;
use craft_ui::runtime::egui::injected::hook_without_pass;
use craft_ui::runtime::windows::WindowHost;
use craft_ui::sections::{DialogRole, FooterButton};
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::TextField;
use egui::{Pos2, ViewportId};
@@ -112,3 +118,151 @@ fn an_ambiguous_or_missing_name_queues_nothing() {
rig.send("ui.click", json!({"control": {"name": "Go", "index": 1}})).expect("valid");
assert_eq!(rig.counts(), [0, 1], "index 1 is the second in reading order");
}
/// The listed widgets of `params`, from the window's kept tree.
fn listed(host: &WindowHost, params: Value) -> Value {
inspect(host, ViewportId::ROOT, &params).expect("an inspect reply")
}
/// The labels of a reply's widgets, in its order.
fn labels(reply: &Value) -> Vec<String> {
reply["widgets"].as_array().into_iter().flatten().filter_map(|w| w["label"].as_str().map(str::to_owned)).collect()
}
/// The widget of a reply labelled `label`.
fn widget<'a>(reply: &'a Value, label: &str) -> &'a Value {
reply["widgets"].as_array().into_iter().flatten().find(|w| w["label"] == label).unwrap_or_else(|| panic!("{label} is listed: {reply}"))
}
/// Where `label` sits in `order`.
fn place(order: &[String], label: &str) -> usize {
order.iter().position(|l| l == label).unwrap_or_else(|| panic!("{label} is listed in {order:?}"))
}
/// Every reported node is listed once in tree order with its state, the root left out; `query`, `role` and `focused`
/// keep a subset, `limit` cuts the list but not the count; a node behind an open modal is neither listed nor
/// resolved, and the modal's own buttons are.
#[trial]
fn inspect_lists_reported_nodes_in_tree_order_with_their_filters() {
let open = Rc::new(Cell::new(false));
let (shown, name) = (open.clone(), Rc::new(RefCell::new(String::from("Draft"))));
let mut fx = Fixture::new(move |ui| {
Button::new("Open").show(ui);
Button::new("Save").show(ui);
Button::new("Archive").enabled(false).show(ui);
TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui);
let mut now = shown.get();
Dialog::new("Options").opened(Bind::bound(&mut now)).buttons([FooterButton::new("Apply", DialogRole::Accept)]).show(ui, |_, _| {});
shown.set(now);
});
let host = WindowHost::of(fx.ctx());
host.keep_access_tree();
fx.settle();
let all = listed(&host, json!({}));
let order = labels(&all);
assert!(place(&order, "Open") < place(&order, "Save") && place(&order, "Save") < place(&order, "Archive"), "tree order: {order:?}");
let widgets = all["widgets"].as_array().expect("a widget list");
assert_eq!(all["count"].as_u64(), Some(widgets.len() as u64), "{all}");
assert_eq!(all["truncated"], false);
assert!(widgets.iter().all(|w| w["depth"].as_u64().is_some_and(|depth| depth >= 1)), "the root is not listed: {all}");
let ids: Vec<&str> = widgets.iter().filter_map(|w| w["id"].as_str()).collect();
assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "each node once: {ids:?}");
let (save, archive) = (widget(&all, "Save"), widget(&all, "Archive"));
assert!(save["enabled"] == true && save["clickable"] == true, "{save}");
assert!(archive["enabled"] == false, "{archive}");
let rect = |w: &Value| w["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::<Vec<_>>()).expect("a rect");
assert!(rect(widget(&all, "Open"))[3] <= rect(save)[1] + 0.5, "Open lies above Save");
let queried = listed(&host, json!({"query": "SAV"}));
assert!(labels(&queried).contains(&"Save".to_owned()) && !labels(&queried).contains(&"Open".to_owned()), "{queried}");
let buttons = listed(&host, json!({"role": "button"}));
assert!(["Open", "Save", "Archive"].iter().all(|label| labels(&buttons).contains(&(*label).to_owned())), "{buttons}");
assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["role"].as_str().is_some_and(|role| role.eq_ignore_ascii_case("button"))));
let fields = listed(&host, json!({"role": "textinput"}));
assert_eq!(fields["count"], 1, "the one text field, its role matched ignoring case: {fields}");
assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != fields["widgets"][0]["id"]), "the field is no button");
let (focused, unfocused) = (listed(&host, json!({"focused": true})), listed(&host, json!({"focused": false})));
assert_eq!(focused["count"].as_u64().unwrap_or(0) + unfocused["count"].as_u64().unwrap_or(0), all["count"].as_u64().unwrap_or(0));
assert!(focused["widgets"].as_array().into_iter().flatten().all(|w| w["focused"] == true), "{focused}");
let first = listed(&host, json!({"limit": 1}));
assert_eq!(first["widgets"].as_array().map(Vec::len), Some(1));
assert_eq!((first["count"].clone(), first["truncated"].clone()), (all["count"].clone(), json!(true)));
assert_eq!(first["widgets"][0], all["widgets"][0], "the limit keeps the first in tree order");
assert!(inspect(&host, ViewportId::ROOT, &json!({"nodes": true})).is_err(), "an unknown field is refused");
open.set(true);
fx.idle(30);
let tree = host.access_tree_view(ViewportId::ROOT).expect("the kept tree");
let behind = listed(&host, json!({}));
assert!(!labels(&behind).contains(&"Open".to_owned()), "a node behind the modal is not listed: {behind}");
assert!(labels(&behind).contains(&"Apply".to_owned()), "the modal's own button is: {behind}");
assert!(resolve(&tree, &NodeTarget::Label("Open".into()), Declared::Click).is_err(), "nor is it resolved");
assert!(resolve(&tree, &NodeTarget::Label("apply".into()), Declared::Click).is_ok(), "a label matches ignoring case");
}
/// A click by label activates its button once; a secondary click opens the node's context menu; a focus by the id
/// `ui.inspect` lists moves the key focus there. A missing, ambiguous, disabled or undeclared target is refused and
/// queues nothing.
#[trial]
fn click_and_focus_by_label_or_id_reach_the_widget_and_refuse_what_they_cannot_name() {
let saves = Rc::new(Cell::new(0));
let (counted, name) = (saves.clone(), Rc::new(RefCell::new(String::new())));
let mut fx = Fixture::new(move |ui| {
if Button::new("Save").show(ui).clicked() {
counted.set(counted.get() + 1);
}
let layer = Button::new("Layer").show(ui);
Menu::context("Layer menu", &layer).show(ui, |ui, _| {
MenuItem::new("Delete layer").show(ui);
});
Button::new("Copy").id_salt("first copy").show(ui);
Button::new("Copy").id_salt("second copy").show(ui);
Button::new("Archive").enabled(false).show(ui);
TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui);
});
let (host, ctx) = (WindowHost::of(fx.ctx()), fx.ctx().clone());
host.keep_access_tree();
fx.settle();
let none = |_: usize, _: Pos2| None;
let send = |fx: &mut Fixture, method: &str, params: Value| {
input_method(method, &params, &host, ViewportId::ROOT, &none).expect("an input method").expect("a target it can name");
fx.run_injected().settle();
};
send(&mut fx, "ui.click", json!({"label": "save"}));
assert_eq!(saves.get(), 1, "the click by label activated Save once");
let field = listed(&host, json!({"role": "TextInput"}))["widgets"][0]["id"].clone();
assert!(field.is_string(), "the text field is listed with its id");
let before = listed(&host, json!({"focused": true}));
assert!(before["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != field), "the field has no focus yet: {before}");
send(&mut fx, "ui.focus", json!({"id": field}));
let focused = listed(&host, json!({"focused": true}));
assert_eq!(focused["widgets"].as_array().map(|w| w.iter().map(|w| w["id"].clone()).collect::<Vec<_>>()), Some(vec![field]), "{focused}");
// Refused while no popup is open, so each is refused for what it names, not for a covered window.
let refused = [
("ui.click", json!({"label": "Nothing here"})),
("ui.click", json!({"id": "1"})),
("ui.click", json!({"label": "copy"})),
("ui.click", json!({"label": "Archive"})),
("ui.click", json!({"label": "Save", "button": "secondary"})),
("ui.focus", json!({"label": "Nothing here"})),
];
for (method, params) in refused {
let answer = input_method(method, &params, &host, ViewportId::ROOT, &none);
assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}");
assert!(host.injected_idle(), "{method} {params} left nothing waiting");
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing");
}
fx.settle();
assert_eq!(saves.get(), 1, "no refused request clicked");
assert_eq!(listed(&host, json!({"query": "Delete layer"}))["count"], 0, "the menu starts closed");
send(&mut fx, "ui.click", json!({"label": "Layer", "button": "secondary"}));
assert!(listed(&host, json!({"query": "Delete layer"}))["count"].as_u64().is_some_and(|n| n >= 1), "the context menu opened");
assert_eq!(saves.get(), 1, "nothing else was clicked");
}
+66 -2
View File
@@ -1,4 +1,4 @@
//! `ControlChannel` deadlines and the loopback server's limits.
//! `ControlChannel` deadlines and the loopback server's limits: connections, request size, authentication.
use std::io::{BufRead, BufReader, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
@@ -8,7 +8,7 @@ use std::time::Duration;
use craft_automation::client::ControlClient;
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error};
use craft_automation::protocol::MAX_RESPONSE_BYTES;
use craft_automation::security::{CHALLENGE_METHOD, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
use craft_automation::server;
use craft_ui::runtime::motion;
use craft_ui::runtime::windows::WindowHost;
@@ -123,6 +123,70 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error.
fn is_closed(reader: &mut impl BufRead) -> bool {
let mut line = String::new();
matches!(reader.read_line(&mut line), Ok(0))
}
/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of
/// the open ones ends, its place serves a new connection.
#[trial]
fn connections_past_the_limit_are_refused_with_the_reason() {
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
let connect = || {
let stream = TcpStream::connect(server.addr).expect("connected");
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
let reader = BufReader::new(stream.try_clone().expect("cloned"));
(stream, reader)
};
// Unauthenticated, so each holds its place until it closes or the authentication deadline passes.
let mut open: Vec<TcpStream> = (0..MAX_CONNECTIONS).map(|_| connect().0).collect();
let (_extra, mut reader) = connect();
let refused = read_json(&mut reader).expect("a refusal");
assert_eq!(refused, json!({"id": null, "ok": false, "error": "connection limit reached"}));
assert!(is_closed(&mut reader), "the refused connection is closed");
drop(open.pop());
// The server frees the place when it reads the close; a new connection is served once it has.
let started = motion::now();
let served = loop {
let (mut stream, mut reader) = connect();
writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written");
let reply = read_json(&mut reader).expect("a reply");
if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) {
break reply;
}
assert_eq!(reply["error"], "connection limit reached", "{reply}");
std::thread::sleep(Duration::from_millis(20));
};
assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
drop(open);
}
/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the
/// connection closes at once, without waiting for the deadline and without dispatching anything: a client cannot keep
/// guessing on one connection.
#[trial]
fn a_refused_first_frame_closes_the_connection() {
let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started");
let wrong = "f".repeat(TOKEN.len());
for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))]
{
let mut stream = TcpStream::connect(server.addr).expect("connected");
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
writeln!(stream, "{first}").expect("written");
assert_eq!(read_json(&mut reader).expect("a refusal"), json!({"id": id, "ok": false, "error": "authentication required"}), "{first}");
// The server may already have closed while this is written.
let _ = writeln!(stream, "{}", json!({"id": 5, "method": "auth", "params": {"token": TOKEN}}));
assert!(is_closed(&mut reader), "{first}: the connection is closed, the second guess unanswered");
}
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line
/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app.
#[trial]
+65
View File
@@ -0,0 +1,65 @@
//! `ui.dock.apply` on a workspace, with the host's permissions and lock.
use craft_automation::dock::{dock_method, inspect};
use craft_behavior::DockSide;
use craft_behavior::dock::{Action, DockError, DockPlacement, Layout, Node, PanelState, Permissions, Workspace};
use craft_ui::contract::PlainData;
use craft_ui::docking::{PanelSpec, PanelSpecs};
use craft_ui::testing::trial;
use serde_json::{Value, json};
/// Two panels, the first protected as a canvas is.
#[derive(PlainData)]
struct Panels;
impl PanelSpecs<u8> for Panels {
fn spec(&self, panel: &u8) -> PanelSpec {
PanelSpec::new(format!("Panel {panel}"))
}
fn permissions(&self, panel: &u8) -> Permissions {
if *panel == 1 { Permissions::PROTECTED } else { Permissions::ALL }
}
}
fn call(workspace: &mut Workspace<u8>, locked: bool, params: Value) -> Result<Value, String> {
dock_method(workspace, &Panels, locked, "ui.dock.apply", &params).expect("a ui.dock method")
}
/// A JSON action applies to the workspace with the host's permissions and lock; a refused one replies the dock error
/// and changes nothing, and `inspect` lists the workspace.
#[trial]
fn a_dock_action_from_json_applies_to_the_workspace() {
let mut workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![1u8, 2], 0)), Vec::new()));
assert_eq!(workspace.layout().panel_state(&2), PanelState::Open);
assert_eq!(call(&mut workspace, false, json!({"action": {"Activate": {"panel": 2}}})), Ok(json!({"applied": []})));
assert_eq!(workspace.layout().panel_state(&2), PanelState::Front, "the activate action brings panel 2 to the front");
let before = workspace.clone();
assert_eq!(
call(&mut workspace, false, json!({"action": Action::close(1u8)})),
Err(DockError::NotAllowed.to_string()),
"the host's permissions protect panel 1"
);
assert_eq!(workspace, before, "a refused action leaves the workspace as it was");
assert!(call(&mut workspace, false, json!({"action": Action::activate(1u8), "panel": 1})).is_err(), "an unknown key is refused");
assert!(call(&mut workspace, false, json!({})).is_err(), "a missing action is refused");
assert!(call(&mut workspace, false, json!({"action": {"Activate": {}}})).is_err());
assert_eq!(workspace, before);
let split = Action::move_beside(2u8, 1, DockPlacement::Split(DockSide::End));
assert_eq!(call(&mut workspace, true, json!({"action": split})), Err(DockError::NotAllowed.to_string()), "a locked workspace refuses a move");
assert_eq!(workspace, before);
assert_eq!(call(&mut workspace, true, json!({"action": Action::activate(1u8)})), Ok(json!({"applied": []})), "a locked workspace activates");
assert_eq!(workspace.layout().panel_state(&1), PanelState::Front);
assert_eq!(call(&mut workspace, false, json!({"action": Action::close(2u8)})), Ok(json!({"applied": [2]})), "the reply lists the closed panel");
assert_eq!(workspace.layout().panel_state(&2), PanelState::Hidden);
assert!(dock_method(&mut workspace, &Panels, false, "ui.dock.close", &json!({})).is_none());
let listed = inspect(&workspace);
assert_eq!(serde_json::from_value::<Workspace<u8>>(listed).ok(), Some(workspace.clone()), "inspect lists the whole workspace");
assert_eq!(workspace.layout().panels(), vec![&1]);
}
+71
View File
@@ -0,0 +1,71 @@
//! `ui.pick` at the protocol boundary.
use std::path::PathBuf;
use craft_automation::files::pick_method;
use craft_host::{Files, NoPickFiles, PickRequest, Picked, ScriptedFiles};
use craft_ui::testing::trial;
use serde_json::{Value, json};
fn call(files: &dyn Files, params: Value) -> Result<Value, String> {
pick_method(files, "ui.pick", &params).expect("ui.pick is the pick method")
}
fn path(p: &str) -> PathBuf {
PathBuf::from(p)
}
/// Each field reaches the service as its `Picked`; with picks on screen the oldest is answered; a bad request is
/// refused with the field list and answers nothing; a service that takes no automated answers says so.
#[trial]
fn ui_pick_answers_the_next_picker_and_refuses_bad_params() {
let answered = Ok(json!({"answered": "next"}));
let files = ScriptedFiles::new();
assert_eq!(call(&files, json!({"files": ["/w/a.pdf", "/w/b.pdf"]})), answered);
assert_eq!(call(&files, json!({"folder": "/w/out"})), answered);
assert_eq!(call(&files, json!({"save": "/w/c.pdf"})), answered);
assert_eq!(call(&files, json!({"cancel": true, "files": null})), answered, "a null field is omitted");
let picked: Vec<Picked> = (0..4)
.map(|_| {
let id = files.pick(PickRequest::open("document"));
files.take_answer(id).expect("a queued answer comes at once")
})
.collect();
assert_eq!(
picked,
[
Picked::Paths(vec![path("/w/a.pdf"), path("/w/b.pdf")]),
Picked::Paths(vec![path("/w/out")]),
Picked::Paths(vec![path("/w/c.pdf")]),
Picked::Cancelled
]
);
let held = ScriptedFiles::held();
let oldest = held.pick(PickRequest::open("first"));
let newest = held.pick(PickRequest::open("second"));
assert_eq!(call(&held, json!({"files": ["/w/first.pdf"]})), answered);
assert_eq!(held.take_answer(oldest), Some(Picked::Paths(vec![path("/w/first.pdf")])), "the oldest open pick is answered");
assert_eq!(held.take_answer(newest), None);
assert_eq!(held.open(), 1);
for bad in [
json!({"files": ["/w/a.pdf"], "save": "/w/b.pdf"}),
json!({}),
json!({"files": []}),
json!({"files": ["/w/a.pdf", 3]}),
json!({"save": 3}),
json!({"cancel": false}),
json!({"path": "/w/a.pdf"}),
] {
let error = call(&files, bad.clone()).expect_err("refused");
assert!(error.contains("files, folder, save, cancel"), "{bad}: {error}");
}
assert_eq!(call(&files, json!({"folder": "/w/after"})), answered);
let id = files.pick(PickRequest::folder("export"));
assert_eq!(files.take_answer(id), Some(Picked::Paths(vec![path("/w/after")])), "no refused request queued an answer");
let unsupported = call(&NoPickFiles::default(), json!({"cancel": true})).expect_err("a service without automated answers refuses");
assert!(!unsupported.contains("files, folder, save, cancel"), "an unsupported service is not a field-list refusal: {unsupported}");
assert!(pick_method(&files, "ui.click", &json!({})).is_none());
}
+2
View File
@@ -7,5 +7,7 @@ pub(crate) mod actions;
pub(crate) mod agents;
pub(crate) mod control;
pub(crate) mod dialogs;
pub(crate) mod dock;
pub(crate) mod files;
pub(crate) mod screenshot;
pub(crate) mod synthetic;
+94 -1
View File
@@ -1,5 +1,6 @@
//! `Captures`: admission budgets, settling, deadlines, cancellation, document identity, the
//! geometry epoch per viewport, the window a capture names, and the image checks.
//! geometry epoch per viewport, the window a capture names, the image checks, and the region a
//! reply is cropped to.
use std::cell::RefCell;
use std::sync::Arc;
@@ -396,6 +397,98 @@ fn the_image_must_match_the_issued_viewport() {
}
}
/// The first pixel of a PNG, decoded.
fn first_pixel(png: &[u8]) -> [u8; 4] {
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().expect("a PNG");
let mut pixels = vec![0; reader.output_buffer_size()];
reader.next_frame(&mut pixels).expect("a frame");
[pixels[0], pixels[1], pixels[2], pixels[3]]
}
/// A region is checked against the window at admission (and again when the layout changed before issue) and refused
/// when it does not lie inside; the whole window is reserved for it. The reply crops it at the image's own scale to
/// the window, so a fitted image is cropped at its fit, and both reply shapes carry the window's point scale.
#[trial]
fn a_region_is_cropped_at_the_image_scale_and_one_outside_the_window_is_refused() {
use craft_automation::control::ControlChannel;
use craft_automation::screenshot::ScreenshotParams;
use serde_json::json;
let params = |value| ScreenshotParams::from_params(&value);
let region = Rect::from_min_max(Pos2::new(10.0, 5.0), Pos2::new(60.0, 30.0));
assert_eq!(params(json!({"path": "a.png", "region": [10, 5, 60, 30]})).map(|p| (p.path, p.region)), Ok((Some("a.png".to_owned()), Some(region))));
for bad in [json!({"region": [60, 5, 10, 30]}), json!({"region": [10, 5, 60]}), json!({"region": [10, 5, 60, "30"]}), json!({"zoom": 2})] {
assert!(params(bad.clone()).is_err(), "{bad} is refused");
}
let ctx = Context::default();
let now = motion::now();
let (_transport, requests) = channel();
let mut control = ControlChannel::new(requests);
let mut g = geometry(100.0, 50.0);
g.pixels_per_point = 2.0;
control.captures.note_geometry(ViewportId::ROOT, g);
let request = |token: u64, region: Rect| {
let (tx, rx) = channel();
let mut request = ScreenshotRequest::new(token, ViewportId::ROOT, tx);
request.region = Some(region);
(request, rx)
};
let (outside, _) = request(1, Rect::from_min_max(Pos2::new(90.0, 40.0), Pos2::new(110.0, 60.0)));
let e = control.captures.admit(outside, now).map_err(|(_, e)| e).expect_err("outside the window");
assert!(e.contains("inside"), "{e}");
assert_eq!(control.captures.pending(), 0);
let (inside, rx) = request(2, region);
control.captures.admit(inside, now).map_err(|(_, e)| e).expect("inside the window");
assert_eq!(control.captures.reserved_bytes(), 200 * 100 * 4, "the whole window is reserved");
let mut picture = ColorImage::filled([200, 100], Color32::BLUE);
picture.pixels[10 * 200 + 20] = Color32::RED;
issue_one(&mut control.captures, &ctx, now).complete(Arc::new(picture));
let finished = control.captures.drain(now, None);
let mut written = Vec::new();
control.finish_captures(finished, &mut |_, bytes| {
written = bytes.to_vec();
Ok(())
});
let reply = rx.try_recv().expect("a reply");
assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(100), json!(50)), "{reply}");
assert_eq!(reply["result"]["pixels_per_point"], 2.0);
assert!(written.is_empty(), "no path, no file");
use base64::Engine as _;
let png = base64::engine::general_purpose::STANDARD.decode(reply["result"]["base64"].as_str().expect("an inline PNG")).expect("base64");
assert_eq!(first_pixel(&png), Color32::RED.to_array(), "the crop starts at the region's corner at two pixels per point");
// A fitted surface: 600×300 points through a 400-pixel texture side come back as 400×200.
let mut fitted = geometry(600.0, 300.0);
fitted.max_texture_side = 400;
control.captures.note_geometry(ViewportId::ROOT, fitted);
let (mut half, rx) = request(3, Rect::from_min_max(Pos2::new(300.0, 150.0), Pos2::new(600.0, 300.0)));
half.path = Some("half.png".into());
control.captures.admit(half, now).map_err(|(_, e)| e).expect("inside the window");
issue_one(&mut control.captures, &ctx, now).complete(filled([400, 200], Color32::WHITE));
let finished = control.captures.drain(now, None);
control.finish_captures(finished, &mut |path, bytes| {
assert_eq!(path, "half.png");
written = bytes.to_vec();
Ok(())
});
let reply = rx.try_recv().expect("a reply");
assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(200), json!(100)), "{reply}");
assert_eq!(reply["result"]["pixels_per_point"], 1.0);
assert!(!written.is_empty(), "the PNG went to the writer");
// A region that a shrink before issue leaves outside is refused then, not cut to a smaller picture.
let (late, _reply) = request(4, region);
control.captures.admit(late, now).map_err(|(_, e)| e).expect("inside the window");
control.captures.note_geometry(ViewportId::ROOT, geometry(40.0, 20.0));
let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, now, None);
assert!(callbacks.is_empty(), "nothing is captured for it");
assert!(finished.len() == 1 && error(&finished[0]).contains("inside"), "refused at issue");
assert_eq!(control.captures.pending(), 0);
}
const ROOT_SIZE: Vec2 = Vec2::new(800.0, 600.0);
const CHILD_SIZE: Vec2 = Vec2::new(400.0, 300.0);
+93 -8
View File
@@ -6,7 +6,7 @@ use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_automation::access::NO_TREE;
use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, 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;
@@ -340,7 +340,8 @@ fn queued_input_is_withdrawn_when_its_target_changes() {
}
/// An unknown field, a wrong type, an unknown name, too many clicks or a point too far out refuses the whole request
/// before any of it is queued: no half-queued press or held key is left behind.
/// before any of it is queued: no half-queued press or held key is left behind. A node target takes no point, repeat,
/// hold, modifier or button but the secondary one, and names exactly one of `id` and `label`.
#[trial]
fn bad_input_params_are_refused_before_anything_is_queued() {
let mut rig = Rig::new();
@@ -353,21 +354,90 @@ fn bad_input_params_are_refused_before_anything_is_queued() {
("ui.click", json!({"x": 10, "button": "thumb"})),
("ui.click", json!({"x": 10, "hold": true, "count": MAX_CLICKS + 1})),
("ui.click", json!({"x": far, "hold": true})),
("ui.move", json!({"x": 10, "nudge": 1})),
("ui.move", json!({"x": 10, "rest": "long"})),
("ui.move", json!({"x": 10, "coordinates": "page"})),
("ui.move", json!({"y": -far})),
("ui.move", json!({"x": 10, "y": 10, "nudge": 1})),
("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.key", json!({"key": "A", "hold": true, "nudge": 1})),
("ui.key", json!({"key": 5})),
("ui.key", json!({"key": "NoSuchKey", "hold": true})),
("ui.ime", json!({"preedit": "ab", "cursor": [1, 9]})),
("ui.click", json!({"x": 10, "y": 10, "label": "Save"})),
("ui.click", json!({"label": "Save", "count": 2})),
("ui.click", json!({"label": "Save", "hold": true})),
("ui.click", json!({"label": "Save", "shift": true})),
("ui.click", json!({"label": "Save", "button": "middle"})),
("ui.click", json!({"id": "12", "button": "middle"})),
("ui.click", json!({"id": "twelve"})),
("ui.focus", json!({"id": "12", "label": "Save"})),
("ui.focus", json!({})),
("ui.drop", json!({"paths": []})),
("ui.drop", json!({"paths": ["a.pdf"], "alt": true})),
];
for (method, params) in refused {
let answer = input_method(method, &params, &host, ViewportId::ROOT, &map);
for (method, params) in &refused {
let answer = input_method(method, params, &host, ViewportId::ROOT, &map);
assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}");
assert!(host.injected_idle(), "{method} {params} left nothing waiting");
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing");
}
// This window keeps no access tree, so a node request is refused there whatever it says; its parameters alone
// refuse the node rows, and the secondary button, a node's context menu, is allowed.
for (method, params) in refused.iter().filter(|(_, params)| params.get("id").is_some() || params.get("label").is_some() || params == &json!({})) {
let by_params = if *method == "ui.focus" { Focus::from_params(params).is_err() } else { Click::from_params(params).is_err() };
assert!(by_params, "{method} {params} is refused by its parameters");
}
assert!(Click::from_params(&json!({"label": "Save", "button": "secondary"})).is_ok());
}
/// A key whose press moves the focus (Tab from one field to the next) still has its release carried out: the release
/// is not cancelled as input whose focus changed, no key stays down, and the waiter is answered as processed. The
/// framework takes the Tab press it acts on out of egui's input, so egui's fields never read it.
#[trial]
fn a_key_release_is_carried_out_after_its_press_moves_focus() {
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
let passes: Rc<RefCell<Vec<Seen>>> = Rc::default();
let rects = Rc::new(Cell::new([Rect::NOTHING; 2]));
let (seen, shown) = (passes.clone(), rects.clone());
let (first, second) = (Rc::new(RefCell::new(String::new())), Rc::new(RefCell::new(String::new())));
let fx = Fixture::new(move |ui| {
let a = TextField::new("First", Bind::bound(&mut *first.borrow_mut())).show(ui).response.rect;
let b = TextField::new("Second", Bind::bound(&mut *second.borrow_mut())).show(ui).response.rect;
shown.set([a, b]);
seen.borrow_mut().push(ui.input(|i| Seen { any_key_down: !i.keys_down.is_empty(), events: i.events.clone(), ..Seen::default() }));
});
let mut rig = Rig { fx, passes };
rig.fx.settle();
let at = rects.get()[0].center();
rig.send("ui.click", json!({"x": at.x, "y": at.y}));
let before = rig.fx.focused();
assert!(before.is_some(), "the click focused the first field");
let (_transport, requests) = std::sync::mpsc::channel();
let mut channel = ControlChannel::new(requests);
let host = rig.host();
rig.take();
input_method("ui.key", &json!({"key": "Tab"}), &host, ViewportId::ROOT, &map).expect("a method").expect("valid");
let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Tab"}));
channel.settle(req, Reply::AfterInput, None, 0.0);
let mut answer = None;
for _ in 0..32 {
rig.fx.frame(Vec::new());
channel.poll_input(&host);
answer = reply.try_recv().ok();
if answer.is_some() {
break;
}
}
rig.fx.frame(Vec::new());
let answer = answer.expect("the waiter is answered");
assert_eq!(answer["ok"], true, "processed, not cancelled: {answer}");
assert!(rig.fx.focused().is_some() && rig.fx.focused() != before, "the press moved the focus");
let passes = rig.take();
let tab = |event: &Event| matches!(event, Event::Key { key: Key::Tab, pressed: true, .. });
assert!(!passes.iter().any(|pass| pass.events.iter().any(tab)), "the Tab press the framework took reaches no field in egui");
assert!(passes.last().is_some_and(|pass| !pass.any_key_down), "no key stays down");
}
/// `ui.ime` queues behind the input before it: typed text, then the composition with its converted segment, then
@@ -448,3 +518,18 @@ fn a_wheel_in_lines_turns_by_notches() {
assert!(matches!(refused, Some(Err(_))), "{refused:?}");
assert!(rig.host().injected_idle(), "the refused turn queued nothing");
}
/// `ui.move` requires both `x` and `y`: omitting either coordinate refuses the request before anything is queued
/// instead of silently moving to 0 on the missing axis.
#[trial]
fn ui_move_refuses_a_missing_coordinate() {
let mut rig = Rig::new();
rig.fx.settle();
let (host, ctx) = (rig.host(), rig.fx.ctx().clone());
for params in [json!({"x": 1}), json!({"y": 1}), json!({})] {
let answer = input_method("ui.move", &params, &host, ViewportId::ROOT, &map);
assert!(matches!(answer, Some(Err(_))), "ui.move {params} is refused: {answer:?}");
assert!(host.injected_idle(), "ui.move {params} left nothing waiting");
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "ui.move {params} queued nothing");
}
}
+16 -4
View File
@@ -169,6 +169,7 @@ pub struct NumberCodec {
zoom: bool,
/// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]).
share: bool,
signed_zoom: bool,
}
impl fmt::Debug for NumberCodec {
@@ -179,6 +180,7 @@ impl fmt::Debug for NumberCodec {
.field("fixed", &self.fixed)
.field("zoom", &self.zoom)
.field("share", &self.share)
.field("signed_zoom", &self.signed_zoom)
.field("custom", &self.custom.is_some())
.finish()
}
@@ -196,6 +198,7 @@ impl PartialEq for NumberCodec {
&& self.fixed == other.fixed
&& self.zoom == other.zoom
&& self.share == other.share
&& self.signed_zoom == other.signed_zoom
&& same_custom
}
}
@@ -230,7 +233,7 @@ const NUMBER_SAMPLE: &str = "0000.00";
impl NumberCodec {
/// A codec reading with `reader` and writing at most `decimals` decimal places.
pub fn new(reader: Reader, decimals: usize) -> Self {
NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false }
NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false, signed_zoom: false }
}
/// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown
@@ -247,8 +250,14 @@ impl NumberCodec {
self
}
/// Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign.
pub fn signed_zoom(mut self) -> Self {
self.signed_zoom = true;
self
}
/// The zoom reading of trimmed, non-empty `text`: the text before a second decimal separator, then `a/b` as a
/// percentage or a plain number. The filter keeps `+`, `-` and `*` out, so the reader's expressions never run.
/// percentage or a plain number. The filter keeps `+` and `*` out, so the reader's expressions never run.
fn read_zoom(&self, text: &str) -> Result<(f64, ParseNote), NotAValue> {
let separator = self.reader.decimal_separator();
let second = text.char_indices().filter(|&(_, c)| c == separator).nth(1).map(|(at, _)| at);
@@ -256,6 +265,9 @@ impl NumberCodec {
Some(at) => (&text[..at], true),
None => (text, false),
};
if kept.strip_prefix('-').unwrap_or(kept).contains('-') {
return Err(NotAValue);
}
let number = match kept.split_once('/') {
Some((part, whole)) => {
let part = self.reader.read(part, None)?;
@@ -371,9 +383,9 @@ impl Codec for NumberCodec {
}
}
/// Zoom typing takes ASCII digits, `/` and the decimal separator; every other number field takes every character.
/// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character.
fn filter(&self, c: char) -> bool {
!self.zoom || c.is_ascii_digit() || c == '/' || c == self.reader.decimal_separator()
!self.zoom || c.is_ascii_digit() || (self.signed_zoom && c == '-') || c == '/' || c == self.reader.decimal_separator()
}
fn sample(&self, _current: &Option<f64>) -> Cow<'_, str> {
+2
View File
@@ -351,6 +351,8 @@ pub enum CursorPriority {
DropTarget,
/// A drag in progress.
Drag,
/// Hides the pointer over everything, links included, while a presentation runs.
Hidden,
}
/// The winning request: the highest priority, the later request on a tie.
+28 -12
View File
@@ -1,6 +1,6 @@
//! `EditHistory<T>`: the undo and redo of a dialog, a tool session or the keymap editor, fed by edit events.
use crate::value::{EditEvent, GestureId, Value};
use crate::value::{EditEvent, GestureId, Mixed, Value};
use std::sync::Arc;
/// Most steps a history keeps.
@@ -78,14 +78,15 @@ impl<T: Value> EditHistory<T> {
self.undo.drain(..gone);
}
/// Takes in one event. Events of a gesture other than the open one are ignored.
/// Takes in one event. Events of a gesture other than the open one are ignored. A concrete
/// before value captures changes made outside history since the preceding edit.
pub fn record(&mut self, event: &EditEvent<T>) {
match event {
EditEvent::Begin { id, label, .. } => self.open = Some(Open { id: *id, name: label.clone() }),
EditEvent::Update { .. } => {}
EditEvent::Commit { id, after, .. } => {
EditEvent::Commit { id, before, after } => {
if let Some(open) = self.open.take_if(|open| open.id == *id) {
self.push(after, open.name);
self.push(before, after, open.name);
}
}
EditEvent::Cancel { id, .. } => {
@@ -93,9 +94,9 @@ impl<T: Value> EditHistory<T> {
self.open = None;
}
}
EditEvent::Set { after, label, .. } => {
EditEvent::Set { before, after, label, .. } => {
self.open = None;
self.push(after, label.clone());
self.push(before, after, label.clone());
}
}
}
@@ -105,17 +106,21 @@ impl<T: Value> EditHistory<T> {
self.open.is_some()
}
fn push(&mut self, after: &T, name: Arc<str>) {
if *after == self.settled {
fn push(&mut self, before: &Mixed<T>, after: &T, name: Arc<str>) {
let weight = match before.same() {
Some(value) => self.budget.map_or(0, |(_, weigh)| weigh(value)),
None => self.settled_weight,
};
let before = before.same().unwrap_or(&self.settled).clone();
self.settled = after.clone();
self.settled_weight = self.budget.map_or(0, |(_, weigh)| weigh(after));
if *after == before {
return;
}
if self.undo.len() >= LIMIT {
self.undo.remove(0);
}
let weight = self.budget.map_or(0, |(_, weigh)| weigh(after));
let value = std::mem::replace(&mut self.settled, after.clone());
let weight = std::mem::replace(&mut self.settled_weight, weight);
self.undo.push(Entry { value, name, weight });
self.undo.push(Entry { value: before, name, weight });
self.redo.clear();
self.trim();
}
@@ -170,6 +175,17 @@ mod tests {
EditEvent::set(Mixed::Same(before), after, "Fill".into(), None)
}
#[test]
fn undo_restores_selection_changed_between_edits() {
let mut history = EditHistory::new(&(0, 0));
history.record(&EditEvent::set(Mixed::Same((0, 1)), (1, 0), "Remove".into(), None));
let mut now = (1, 0);
assert!(history.step(&mut now, Step::Undo));
assert_eq!(now, (0, 1));
assert!(history.step(&mut now, Step::Redo));
assert_eq!(now, (1, 0));
}
#[test]
fn a_take_back_returns_the_earlier_value_keeps_redo_and_settles() {
let mut history = EditHistory::new(&0);
+10
View File
@@ -0,0 +1,10 @@
//! The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it.
/// The longest step motion integrates, in seconds, so a stalled pass never jumps the view.
pub const FRAME_STEP_MAX: f64 = 0.1;
/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the
/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number.
pub fn frame_step(dt: f64) -> f64 {
if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 }
}
+5 -3
View File
@@ -148,9 +148,11 @@ impl CropBox {
(w.is_finite() && h.is_finite()).then(|| (w.round().max(1.0), h.round().max(1.0)))
}
/// Whether both sides are at least one document unit.
pub fn size_ok(&self) -> bool {
self.rect.width() >= MIN_FRAME && self.rect.height() >= MIN_FRAME
/// Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is
/// not a number counts as one unit).
pub fn size_ok(&self, min: f64) -> bool {
let min = min.max(MIN_FRAME);
self.rect.width() >= min && self.rect.height() >= min
}
/// The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on
+1 -1
View File
@@ -24,7 +24,7 @@ pub use lock::{
pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels};
pub use move_gesture::{ConstrainStyle, MoveGesture, MoveValue, StrokeLock};
pub use outside::outside_pieces;
pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag};
pub use quad::{BoxAllow, BoxDrag, BoxHandles, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag};
pub use selection_op::SelectionOperation;
pub use snap::{
SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapSuspend, SnapTarget, SnapTargets, across_axis, coordinate_across,
+63 -13
View File
@@ -97,6 +97,8 @@ pub enum ScaleRule {
/// PhotoCraft's Use Legacy Free Transform, DesignCraft and VectorCraft: corners stretch freely
/// and ⇧ keeps the proportions; edges stretch their one axis.
Free,
/// Corners keep their proportions using the larger relative axis change; ⇧ frees them.
LargerAxis,
/// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal,
/// keeping the proportions; an edge stretches its one axis.
Shape,
@@ -203,6 +205,25 @@ pub struct BoxRules {
/// minimum keeps a scale drag from flipping the box, and a side already shorter than it at
/// the press keeps its length as its floor, so a click changes nothing.
pub min_side: f64,
/// Which handles the box shows and takes keys and drags for.
pub handles: BoxHandles,
/// How far either side of a side's line a press grabs that side, in screen points, along the whole side and as
/// far past its ends: a paragraph frame whose edges rewrap it. Inside the box the band reaches at most a quarter of
/// the way across, so a narrow box keeps its middle. 0, the default, leaves each side its band outside the box.
pub edge_band: f32,
}
/// Which handles of a box are shown.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum BoxHandles {
/// The four corners and the four sides.
#[default]
All,
/// The four corners.
Corners,
/// The right and left sides.
Sides,
}
impl Default for BoxRules {
@@ -214,6 +235,8 @@ impl Default for BoxRules {
allow: BoxAllow::default(),
rotate_step: 15.0,
min_side: 0.0,
handles: BoxHandles::default(),
edge_band: 0.0,
}
}
}
@@ -249,6 +272,28 @@ impl BoxRules {
self
}
/// The rules with `handles` as the handles the box shows.
pub fn with_handles(mut self, handles: BoxHandles) -> BoxRules {
self.handles = handles;
self
}
/// The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)).
pub fn with_edge_band(mut self, points: f32) -> BoxRules {
self.edge_band = points;
self
}
/// Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides
/// and no corner. The inside, the outside and the reference point always show.
pub fn shows(&self, part: BoxPart) -> bool {
match (self.handles, part) {
(BoxHandles::Corners, BoxPart::Edge(_)) | (BoxHandles::Sides, BoxPart::Corner(_)) => false,
(BoxHandles::Sides, BoxPart::Edge(k)) => k % 2 == 1,
_ => true,
}
}
/// The mode drags follow: a mode the content refuses scales as Free Transform does.
pub fn effective_mode(&self) -> TransformMode {
let refused = match self.mode {
@@ -262,14 +307,15 @@ impl BoxRules {
/// Whether a drag of `part` changes the box: in Distort only the corners, the inside and the
/// reference point; in Skew everything but the outside; the outside only where rotating is
/// allowed. A click outside a refused zone still applies the box (the overlay's rule).
/// allowed; and never a handle the box does not [show](Self::shows). A click outside a refused
/// zone still applies the box (the overlay's rule).
pub fn allows(&self, part: BoxPart) -> bool {
let by_mode = match self.effective_mode() {
TransformMode::Distort => !matches!(part, BoxPart::Outside | BoxPart::Edge(_)),
TransformMode::Skew => part != BoxPart::Outside,
_ => true,
};
by_mode && (self.allow.rotate || part != BoxPart::Outside)
by_mode && (self.allow.rotate || part != BoxPart::Outside) && self.shows(part)
}
/// The modifiers a drag of `part` acts on, from the keys held: ⌘ is dropped on a corner or
@@ -504,16 +550,22 @@ fn apply_drag(g: &Gesture, p: Point, mods: Mods, rules: &BoxRules) -> BoxState {
}
BoxState { quad, pivot: carry_pivot(q0, quad, c) }
}
BoxPart::Corner(_) | BoxPart::Edge(_) => scale_drag(g, p, mods, rules.min_side).unwrap_or(BoxState { quad: q0, pivot: c }),
BoxPart::Corner(_) | BoxPart::Edge(_) => {
scale_drag(g, p, mods, rules.min_side, rules.scale == ScaleRule::LargerAxis).unwrap_or(BoxState { quad: q0, pivot: c })
}
}
}
/// A plain corner or edge drag: scaling in the box's own frame (the unit square through the
/// homography), so rotated and skewed boxes scale along their axes. A proportional corner follows
/// the pointer's projection on the line from the anchor to the corner, so a distorted box scales
/// along its own diagonal; past the anchor the factor turns negative and the box flips. Each
/// scaled side keeps at least `min_side` ([`scale_floor`]). `None` for a collapsed box.
fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option<BoxState> {
/// the pointer's projection on the diagonal, or the larger relative axis change when selected. Past the anchor
/// the factor turns negative and the box flips. Each scaled side keeps at least `min_side`
/// ([`scale_floor`]). `None` for a collapsed box.
fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64, larger_axis: bool) -> Option<BoxState> {
let p = match g.part {
BoxPart::Corner(i) => g.quad0[usize::from(i) % 4] + (p - g.start),
_ => p,
};
let h = Homography::unit_to_quad(g.quad0)?;
let inv = h.inverse()?;
let Point { x: u, y: v } = inv.apply(p);
@@ -556,16 +608,14 @@ fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option<BoxSta
kv = kv.max(lo_v);
}
} else if corner {
// The corner follows the pointer's projection on the line from the anchor to the dragged
// corner in document space. That line maps back onto the unit square's line through the
// same two points, so the factor read on one unit axis holds for both, also on a
// distorted box. One factor scales both axes, so it is clamped once, to the stricter
// axis' floor, and the box keeps its proportions.
// One factor holds both axes to the stricter floor, including on inward drags.
let (hu, hv) = (if mu.0 { 0.0 } else { 1.0 }, if mv.0 { 0.0 } else { 1.0 });
let a = h.apply(Point::new(au, av));
let d = h.apply(Point::new(hu, hv)) - a;
let len2 = d.hypot2();
let k = if len2 > 1e-12 {
let k = if larger_axis {
if (ku - 1.0).abs() > (kv - 1.0).abs() { ku } else { kv }
} else if len2 > 1e-12 {
let q = inv.apply(a + d * ((p - a).dot(d) / len2));
if (hu - au).abs() >= (hv - av).abs() { (q.x - au) / (hu - au) } else { (q.y - av) / (hv - av) }
} else {
+37 -6
View File
@@ -309,6 +309,11 @@ pub struct Shape<O> {
pub local: bool,
/// The least size across the hit area has, in points.
pub min_across: f32,
/// The named stacking order: stacked parts of one priority rank by it before the nearest centre, the higher order
/// winning.
pub stacking: u32,
/// Whether a passed drag targets the arena root instead of the next shape.
pub drag_to_root: bool,
}
impl<O: Clone> Shape<O> {
@@ -330,7 +335,7 @@ impl<O: Clone> Shape<O> {
impl<O> Shape<O> {
/// A shape of `owner` at stack `position`.
pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option<PartRef>, priority: HitPriority, position: u32) -> Self {
Shape { shape, sense, owner, part, priority, position, local: false, min_across: 0.0 }
Shape { shape, sense, owner, part, priority, position, local: false, min_across: 0.0, stacking: 0, drag_to_root: false }
}
/// The hit area is at least `across` points wide and high.
@@ -339,6 +344,12 @@ impl<O> Shape<O> {
self
}
/// The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre.
pub const fn stacking(mut self, order: u32) -> Self {
self.stacking = order;
self
}
/// The shape lies in the body layer's space.
pub const fn local(mut self, local: bool) -> Self {
self.local = local;
@@ -376,10 +387,12 @@ pub struct Winner<O> {
pub sense: Sense,
/// Its shape lies in the body layer's space.
pub local: bool,
/// A passed drag targets the arena root.
pub drag_to_root: bool,
}
/// The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last
/// registered. A press considers only shapes that sense a click or a drag.
/// The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest
/// centre, the last registered. A press considers only shapes that sense a click or a drag.
pub fn resolve<O: Copy>(shapes: &[Shape<O>], point: Pos2, what: ResolveFor) -> Option<Winner<O>> {
resolve_mapped(shapes, point, what, |_| point)
}
@@ -394,12 +407,19 @@ pub fn resolve_mapped<O: Copy>(shapes: &[Shape<O>], point: Pos2, what: ResolveFo
.filter(|(_, shape)| what == ResolveFor::Hover || shape.sense.takes_press())
.filter(|(_, shape)| shape.hits(at(shape)))
.max_by(|(ia, a), (ib, b)| {
(a.position, a.priority.level, a.priority.sub)
.cmp(&(b.position, b.priority.level, b.priority.sub))
(a.position, a.priority.level, a.priority.sub, a.stacking)
.cmp(&(b.position, b.priority.level, b.priority.sub, b.stacking))
.then_with(|| distance(b).partial_cmp(&distance(a)).unwrap_or(Ordering::Equal))
.then(ia.cmp(ib))
})
.map(|(index, shape)| Winner { index, owner: shape.owner, part: shape.part, sense: shape.sense, local: shape.local })
.map(|(index, shape)| Winner {
index,
owner: shape.owner,
part: shape.part,
sense: shape.sense,
local: shape.local,
drag_to_root: shape.drag_to_root,
})
}
#[cfg(test)]
@@ -436,6 +456,17 @@ mod tests {
assert_eq!(owner(&tie), Some(2));
}
#[test]
fn stacked_parts_of_one_priority_rank_by_their_order_before_the_nearest_centre() {
let at = pos2(50.0, 50.0);
let owner = |shapes: &[Shape<u8>]| resolve(shapes, at, ResolveFor::Press).map(|w| w.owner);
let near = || shape(rect(40.0, 40.0, 20.0, 20.0), Sense::CLICK, 1, 0, HitLevel::Body, 0);
let far = || shape(rect(0.0, 0.0, 200.0, 200.0), Sense::CLICK, 2, 0, HitLevel::Body, 0);
assert_eq!(owner(&[far(), near()]), Some(1), "unstacked, the nearer centre wins");
assert_eq!(owner(&[far().stacking(1), near()]), Some(2), "the higher stacking order wins though the press is nearer the other's centre");
assert_eq!(owner(&[near().stacking(1), far().stacking(1)]), Some(1), "one order: the nearest centre decides");
}
#[test]
fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() {
let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)];
+8 -1
View File
@@ -30,6 +30,12 @@ pub trait ItemLayout {
/// The item under `point`.
fn hit(&self, point: Pos2, offset: ScrollPos) -> Option<usize>;
/// The item whose drop area contains `point`. Layouts with visible gaps can include those in a drop area while
/// leaving them out of ordinary pointer hits.
fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option<usize> {
self.hit(point, offset)
}
/// How arrow keys move through the items.
fn nav(&self) -> NavShape;
@@ -105,7 +111,8 @@ pub trait ItemLayout {
/// Whether the items are as wide as they measure themselves. A layout that asks for widths places the items
/// from their measured ideal and minimum widths (`set_width`), so every item must be built and measured: its
/// `visible` lists all items, and the collection does not virtualise it.
/// `visible` lists all items, and the collection does not virtualise it. Its items sit side by side, so where the
/// collection's width comes from its rows (a room that does not bound it) it is their ideal widths' sum.
fn auto_widths(&self) -> bool {
false
}
+8 -3
View File
@@ -59,13 +59,18 @@ pub trait DisplayOrder<K> {
}
/// Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a
/// press, and opens or closes with Forward and Back when it has children. A move stops on it, and it is never
/// selected, extended over, toggled, marqueed, dragged, renamed or reached by type-ahead. Only meaningful for a
/// section.
/// press, and opens or closes with Forward and Back when it has children. A move stops on it. By default it is
/// not selected or extended over; see `selectable_section`. It is not toggled, marqueed, dragged, renamed or
/// reached by type-ahead. Only meaningful for a section.
fn section_stop(&self, _at: usize) -> bool {
false
}
/// Whether a section stop also represents an item that keyboard selection can pick or extend over.
fn selectable_section(&self, _at: usize) -> bool {
false
}
/// How many section stops (`section_stop`) come before entry `at`. They are not members of the set of items, so
/// the positions an item reports to assistive technology do not count them.
fn section_stops_before(&self, _at: usize) -> usize {
+84 -19
View File
@@ -7,9 +7,20 @@ use crate::intent::{Granularity, Intent, MoveMods, NavMove};
use craft_host::target::Os;
use craft_keymap::{Chord, Key, Mods};
/// What the focused stop is, as far as the table's rows differ.
/// The named key scheme of a reorderable collection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReorderKeys {
/// The stacking keys (`REORDER_KEYS`): Cmd+] and Cmd+[.
#[default]
Stacking,
/// Alt with the arrows (`ALT_ARROW_KEYS`).
AltArrows,
}
/// What the focused stop is, as far as the table's rows differ.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct KeyRole {
/// A value control with a reset value and no text part: Delete resets it.
pub resettable: bool,
@@ -17,8 +28,10 @@ pub struct KeyRole {
pub space: bool,
/// A collection that selects several items: Ctrl+Space (Control on macOS) toggles the lead's pick.
pub multi_select: bool,
/// A reorderable collection: the stacking keys (`REORDER_KEYS`) move the selected items.
pub reorderable: bool,
/// The scheme whose keys move the selected items of a reorderable collection, `None` when it does not reorder.
pub reorderable: Option<ReorderKeys>,
/// The axis the collection's order is laid out along.
pub reorder_axis: Axis,
/// A collection with `CollectionProps.rename`.
pub rename: bool,
/// `FocusPolicy.pages`: Ctrl+Tab switches pages.
@@ -52,6 +65,12 @@ pub struct KeyRole {
pub home_row: usize,
}
impl Default for KeyRole {
fn default() -> Self {
Self::new()
}
}
impl KeyRole {
/// A role with no special rows.
pub const fn new() -> KeyRole {
@@ -59,7 +78,8 @@ impl KeyRole {
resettable: false,
space: false,
multi_select: false,
reorderable: false,
reorderable: None,
reorder_axis: Axis::Y,
rename: false,
pages: false,
nudge: false,
@@ -94,9 +114,15 @@ impl KeyRole {
self
}
/// The stacking keys move the selected items.
pub const fn reorderable(mut self, on: bool) -> Self {
self.reorderable = on;
/// The scheme's keys move the selected items; `None` when the stop does not reorder.
pub const fn reorderable(mut self, keys: Option<ReorderKeys>) -> Self {
self.reorderable = keys;
self
}
/// The axis the order is laid out along.
pub const fn reorder_axis(mut self, axis: Axis) -> Self {
self.reorder_axis = axis;
self
}
@@ -191,12 +217,29 @@ pub enum DropOperation {
Link,
}
/// The drop operation the held modifiers pick.
pub fn drop_operation(os: Os, mods: Mods) -> DropOperation {
let link = if os == Os::Mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift };
/// Which held key turns a drag into a copy over a target.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CopyKeys {
/// Alt, Option on macOS: a design app's duplicating drag (Photoshop's layers).
#[default]
Alt,
/// The file manager's: Ctrl off macOS, Option on macOS (Explorer, Finder, a document's page grid).
Platform,
}
/// The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on
/// macOS, whatever the copy keys.
pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation {
let mac = os == Os::Mac;
let link = if mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift };
let copies = match copy {
CopyKeys::Platform if !mac => mods.cmd,
_ => mods.alt,
};
if link {
DropOperation::Link
} else if mods.alt {
} else if copies {
DropOperation::Copy
} else {
DropOperation::Move
@@ -221,14 +264,32 @@ pub const REORDER_KEYS: [Chord; 6] = [
Chord::new(Mods { shift: true, ..Mods::CMD }, Key::OpenCurlyBracket),
];
/// The `Intent::MoveItem` a stacking key asks for, `None` for any other press.
pub fn reorder_intent(key: Key, mods: Mods) -> Option<Intent> {
/// The four Alt+arrow chords of `ReorderKeys::AltArrows`.
pub const ALT_ARROW_KEYS: [Chord; 4] =
[Chord::new(Mods::ALT, Key::Up), Chord::new(Mods::ALT, Key::Down), Chord::new(Mods::ALT, Key::Left), Chord::new(Mods::ALT, Key::Right)];
/// The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other
/// press.
pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option<Intent> {
let chord = Chord::new(mods, key);
if !REORDER_KEYS.contains(&chord) {
return None;
match keys {
ReorderKeys::Stacking => {
if !REORDER_KEYS.contains(&chord) {
return None;
}
let front = matches!(key, Key::CloseBracket | Key::CloseCurlyBracket);
Some(Intent::move_item(front, mods.shift))
}
ReorderKeys::AltArrows => {
if !ALT_ARROW_KEYS.contains(&chord) {
return None;
}
// Down and Right are one place later in reading order on either axis; the item step turns `front` back
// into a direction with `toward_end` over the same axis, which is its own inverse.
let later = matches!(key, Key::Down | Key::Right);
Some(Intent::move_item(toward_end(later, axis), false))
}
}
let front = matches!(key, Key::CloseBracket | Key::CloseCurlyBracket);
Some(Intent::move_item(front, mods.shift))
}
/// Whether a move toward the front goes toward the end of an order laid out along `axis`. The front of a vertical
@@ -256,8 +317,12 @@ pub fn intent(os: Os, key: Key, mods: Mods, role: KeyRole) -> Option<Intent> {
if let Some(fine) = fine_move(key, mods, role) {
return Some(fine);
}
if role.reorderable
&& let Some(reorder) = reorder_intent(key, mods)
// Before the Alt+Up and Alt+Down rows, so that the Alt+arrow scheme reorders instead of opening or closing. Rows
// stacked one per line have no neighbour across their axis: the arrows across it stay their move rows there.
let across = if role.reorder_axis == Axis::X { matches!(key, Key::Up | Key::Down) } else { matches!(key, Key::Left | Key::Right) };
if let Some(keys) = role.reorderable
&& !(role.stacked && across)
&& let Some(reorder) = reorder_intent(key, mods, keys, role.reorder_axis)
{
return Some(reorder);
}
+8 -4
View File
@@ -23,6 +23,7 @@ pub mod eviction;
pub mod fit;
pub mod flow;
pub mod focus;
pub mod frame_step;
pub mod grid;
pub mod hit;
pub mod hold_repeat;
@@ -34,6 +35,7 @@ pub mod item_source;
pub mod keys;
pub mod label_column;
pub mod layout_memory;
pub mod middle_scroll;
pub mod monitor;
pub mod motion;
pub mod nav;
@@ -80,6 +82,7 @@ pub use edit_history::EditHistory;
pub use editor::{EditorInput, SurroundingUnit};
pub use flow::{Axis, Flow, Insets};
pub use focus::{CancelRule, KeyOwner, OwnerClass, PressFocus, ScopeKind};
pub use frame_step::{FRAME_STEP_MAX, frame_step};
pub use grid::{GridCursor, GridMeasure, resolve_columns};
pub use hit::{HitLevel, HitPriority, HitShape, ResolveFor, Shape, Winner, resolve, resolve_mapped};
pub use input::Input;
@@ -87,9 +90,10 @@ pub use intent::{AccessRequest, EditCommand, Granularity, Intent, MoveMods, NavM
pub use item_layout::{FreeLayout, ItemLayout, LineIndex, SHEET_ZOOM, SheetLayout, SpanLayout, TileLayout};
pub use item_marquee::{MarqueeMode, MarqueeSelect};
pub use item_source::{DisplayOrder, ItemSource, Keyed, Outline, SizeHint, keyed};
pub use keys::{DropOperation, KeyRole};
pub use keys::{CopyKeys, DropOperation, KeyRole, ReorderKeys};
pub use label_column::{LabelColumn, LabelPlacement};
pub use layout_memory::SizeTween;
pub use middle_scroll::{MiddleButton, MiddleScroll};
pub use monitor::{Monitor, MonitorKey};
pub use motion::{MotionKind, MotionMode, Playback};
pub use nav::{Arrows, Letters, NavOutline, NavShape, NavState, NavStep, Roving, TypeAhead, lead_step, wheel_step};
@@ -99,8 +103,8 @@ pub use pixel_size::PixelSize;
pub use hold_repeat::HoldRepeat;
pub use press::{
Buttons, MultiTap, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressMachine, PressPhase,
PressStart, PressState, PressStep, count_clicks,
Buttons, MultiTap, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressAside, PressCancel, PressMachine,
PressPhase, PressPick, PressStart, PressState, PressStep, count_clicks,
};
pub use quantity::Reader;
pub use role_rule::{GridFacts, RoleRule, is_checkable, is_selectable, role_violations};
@@ -117,7 +121,7 @@ pub use value::{
same_in_f32, same_in_f32_at,
};
pub use value_drag::{DragWarp, ValueDrag, wrap_value};
pub use wheel::{GESTURE_GAP, Wheel, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit};
pub use wheel::{GESTURE_GAP, Wheel, WheelEase, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit};
#[cfg(test)]
extern crate self as craft_behavior;
+115
View File
@@ -0,0 +1,115 @@
//! The middle button's auto-scroll latch: the gesture state of one middle press.
use crate::frame_step;
use crate::press::PressPhase;
use emath::{Pos2, Vec2};
/// How far, in points, the pointer may sit above or below the anchor without scrolling.
const DEAD_ZONE: f32 = 15.0;
/// Held passes past the dead zone after which a release ends the latch: a shorter hold is a click, which keeps it.
const HELD_PASSES: u32 = 2;
/// The power of the distance the speed grows with.
const SPEED_EXPONENT: f32 = 2.2;
/// Points per second per unit of the distance raised to [`SPEED_EXPONENT`].
const SPEED_MULTIPLIER: f32 = 0.04;
/// The farthest distance the speed is computed from, so the power of a hostile pointer position stays finite. No
/// pointer on a real screen reaches it.
const MAX_DISPLACEMENT: f32 = 1_000_000.0;
/// What the middle button does over a scroll area.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MiddleButton {
/// Drags the view.
#[default]
Pan,
/// Latches an auto-scroll anchor.
AutoScroll,
}
/// The auto-scroll latch of one middle press.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MiddleScroll {
anchor: Option<Pos2>,
held_passes: u32,
swallowing: bool,
}
impl MiddleScroll {
/// A middle press: inside the scroll area it latches at `at`; a second press ends the latch.
pub fn press(&mut self, at: Pos2, inside: bool) {
if self.active() {
self.cancel();
} else if inside && at.is_finite() {
self.anchor = Some(at);
self.held_passes = 0;
}
}
/// The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier
/// release keeps it.
pub fn release(&mut self) {
if self.held_passes >= HELD_PASSES {
self.cancel();
}
}
/// Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the
/// `Down` that cancels an active latch and for each later phase of that press through its release or cancel. A
/// press that begins while nothing is latched is not swallowed.
pub fn swallows(&mut self, phase: PressPhase) -> bool {
match phase {
PressPhase::Down { .. } => {
self.swallowing = self.active();
if self.swallowing {
self.cancel();
}
self.swallowing
}
PressPhase::Release { .. } | PressPhase::Cancel { .. } => std::mem::take(&mut self.swallowing),
PressPhase::Idle | PressPhase::Hover => false,
_ => self.swallowing,
}
}
/// Ends the latch.
pub fn cancel(&mut self) {
self.anchor = None;
self.held_passes = 0;
}
/// One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and
/// returns the vertical scroll for the step `frame_step(dt)`, at `|d|^2.2 × 0.04` points per second, reversed by
/// `invert`. The result moves the content: with the pointer below the anchor it is negative, so the view scrolls
/// down. Zero while nothing is latched.
pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2 {
let Some(anchor) = self.anchor else { return Vec2::ZERO };
let displacement = pointer.y - anchor.y;
if !displacement.is_finite() {
return Vec2::ZERO;
}
let distance = displacement.abs();
if distance <= DEAD_ZONE {
return Vec2::ZERO;
}
let step = frame_step(dt);
// A frame's later passes take no time: counting them would count one frame's hold twice and end a click.
if held && step > 0.0 {
self.held_passes = self.held_passes.saturating_add(1);
}
// The full distance sets the speed, not the part past the dead zone.
let speed = distance.min(MAX_DISPLACEMENT).powf(SPEED_EXPONENT) * SPEED_MULTIPLIER;
let delta = -displacement.signum() * speed * step as f32;
Vec2::new(0.0, if invert { -delta } else { delta })
}
/// Where the latch is anchored, `None` when there is none.
pub fn anchor(&self) -> Option<Pos2> {
self.anchor
}
/// Whether a latch is active.
pub fn active(&self) -> bool {
self.anchor.is_some()
}
}
+14
View File
@@ -314,6 +314,20 @@ mod tests {
assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside");
}
#[test]
fn an_overlay_with_no_room_on_its_side_opens_on_the_other() {
let size = Vec2::new(200.0, 80.0);
let low = rect(300.0, 540.0, 100.0, 30.0);
let placed = place(&PlaceRequest::new(low, size, BOUNDS).side(Side::Below).gap(4.0));
assert_eq!(placed.side, Side::Above, "no room below the anchor: {placed:?}");
assert!(placed.rect.bottom() <= low.top(), "above the anchor: {placed:?}");
assert!(BOUNDS.contains_rect(placed.rect), "{placed:?}");
let high = rect(300.0, 100.0, 100.0, 30.0);
let placed = place(&PlaceRequest::new(high, size, BOUNDS).side(Side::Below).gap(4.0));
assert_eq!(placed.side, Side::Below, "room below: {placed:?}");
assert!(placed.rect.top() >= high.bottom(), "below the anchor: {placed:?}");
}
#[test]
fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() {
let point = rect(300.0, 400.0, 0.0, 0.0);
+304 -48
View File
@@ -306,15 +306,24 @@ pub struct PressState {
pub sample: Option<PointerSample>,
/// A drag holds the pointer: nothing else hovers.
pub captured: bool,
/// Where a secondary press made during another open press came up on this part in this pass
/// ([`PressStep::aside`]): a context request beside the running phase, which goes on.
pub context: Option<Pos2>,
}
impl PressState {
/// A part with no press history.
pub const IDLE: PressState = PressState::new(PressPhase::Idle);
/// A state in `phase` with no modifiers, sample or capture.
/// A state in `phase` with no modifiers, sample, capture or aside context request.
pub const fn new(phase: PressPhase) -> Self {
PressState { phase, mods: Mods::NONE, sample: None, captured: false }
PressState { phase, mods: Mods::NONE, sample: None, captured: false, context: None }
}
/// The aside secondary press that came up on the part at `at` in this pass.
pub const fn context(mut self, at: Option<Pos2>) -> Self {
self.context = at;
self
}
/// The modifiers held.
@@ -484,11 +493,56 @@ pub struct PressStep<T> {
pub dragging: bool,
/// The target released as a click in this pass.
pub activated: Option<T>,
/// The start of an open press whose sense has `PASSES_DRAG` and no `DRAG` that moved past slop in this pass:
/// the caller may hand it to the shape below with [`PressMachine::hand_over`].
pub passes: Option<PressStart>,
/// A secondary press that came up in this pass while a primary press stayed open: a right-click during a drag. The
/// open press goes on; the aside asks its target for a context menu.
pub aside: Option<PressAside<T>>,
}
impl<T> Default for PressStep<T> {
fn default() -> Self {
PressStep { target: None, phase: None, dragging: false, activated: None }
PressStep { target: None, phase: None, dragging: false, activated: None, passes: None, aside: None }
}
}
/// A secondary press made and released while a primary press was open ([`PressStep::aside`]). Its target is the one
/// `pick` gave the secondary press, so it senses `Sense::CONTEXT_CLICK`.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PressAside<T> {
/// The target of the secondary press.
pub target: T,
/// Where and when the secondary button went down.
pub start: PressStart,
/// Where it came up, in screen space.
pub pos: Pos2,
}
/// The press winner a root picks at a press position, as [`PressMachine::step`]'s `pick` returns it.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PressPick<T> {
/// The press winner.
pub target: T,
/// What it senses of the press.
pub sense: Sense,
/// The press's click went to a shape above that passes its drag to this target (`Sense::PASSES_DRAG`): the press
/// opens silent and is the target's only once its drag starts.
pub passed: bool,
}
impl<T> PressPick<T> {
/// `target`, sensing `sense`, takes the press.
pub fn new(target: T, sense: Sense) -> Self {
PressPick { target, sense, passed: false }
}
/// The press's click went to a shape above that passes its drag to this target.
pub fn passed(mut self) -> Self {
self.passed = true;
self
}
}
@@ -500,6 +554,13 @@ struct Open<T> {
dragging: bool,
/// Moved past slop on a target that senses no drag: the click is gone and nothing starts.
abandoned: bool,
/// Moved past slop in this pass on a target that clicks and passes its drag (`Sense::PASSES_DRAG`), with the
/// pointer at the pass's end: no click and no drag until [`PressMachine::hand_over`] gives the press its new
/// target. The next pass abandons a press no shape took.
passing: Option<Pos2>,
/// A press passed to this target ([`PressPick::passed`]) whose drag has not started: it reports nothing, and a
/// release or cancel ends it unreported. Its move past slop starts the drag with `DragStart`, as a hand-over does.
silent: bool,
/// The pointer left the window ([`PointerEvent::Gone`]): the click is gone, but a target that senses a drag still
/// starts it from the moves that follow. The button is still down and the window keeps getting the pointer's moves
/// and release while it is outside, so a press near a window edge (a window's resize grip) that leaves the window
@@ -516,14 +577,14 @@ struct Open<T> {
}
impl<T> Open<T> {
/// A phase before the release is still to be reported.
/// A phase before the release is still to be reported, or the press waits for its hand-over.
fn owes_phase(&self) -> bool {
!self.reported || (self.dragging && !self.drag_reported)
!self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some()
}
/// A release now is a click.
fn clicks(&self) -> bool {
!self.dragging && !self.abandoned && !self.left && self.sense.contains(Sense::CLICK)
!self.dragging && !self.abandoned && !self.left && self.passing.is_none() && self.sense.contains(Sense::CLICK)
}
}
@@ -531,18 +592,20 @@ impl<T> Open<T> {
#[derive(Clone, Copy, Debug)]
pub struct PressMachine<T> {
open: Option<Open<T>>,
/// The secondary press held beside the open primary press, with its target and start.
aside: Option<(T, PressStart)>,
}
impl<T> Default for PressMachine<T> {
fn default() -> Self {
PressMachine { open: None }
PressMachine { open: None, aside: None }
}
}
impl<T: Copy> PressMachine<T> {
/// A machine with no press.
pub const fn new() -> Self {
PressMachine { open: None }
PressMachine { open: None, aside: None }
}
/// The target of the open press.
@@ -584,6 +647,8 @@ impl<T: Copy> PressMachine<T> {
reported: true,
drag_reported: false,
released_at: None,
passing: None,
silent: false,
});
}
@@ -593,21 +658,32 @@ impl<T: Copy> PressMachine<T> {
self.open.is_some_and(|open| open.released_at.is_some())
}
/// Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None`
/// when no shape of this root takes the press.
pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep<T> {
/// Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed
/// there; it returns `None` when no shape of this root takes the press. A secondary press goes only to a shape that
/// senses `Sense::CONTEXT_CLICK`, so `pick` passes over the others for it, to the next shape under the press.
pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option<PressPick<T>>) -> PressStep<T> {
let mut pos = input.pos;
let mut released: Option<(T, PressStart, Pos2, bool, bool)> = None;
let mut cancelled: Option<(T, PressStart, PressCancel)> = None;
// The press released or cancelled in this pass, and whether it was silent: one that ends silent reports nothing.
let mut released: Option<(T, PressStart, Pos2, bool, bool, bool)> = None;
let mut cancelled: Option<(T, PressStart, PressCancel, bool)> = None;
let mut aside: Option<PressAside<T>> = None;
// A press passed in the last pass that no shape took is abandoned; that pass reported its `Down`.
if let Some(open) = &mut self.open
&& open.passing.is_some()
{
open.passing = None;
open.abandoned = true;
open.reported = true;
}
if let Some(open) = self.open
&& let Some((at, click)) = open.released_at
&& !open.owes_phase()
{
released = Some((open.target, open.start, at, open.dragging, click));
released = Some((open.target, open.start, at, open.dragging, click, open.silent));
self.open = None;
}
if let (Some(reason), Some(open)) = (input.cancel, self.open) {
cancelled = Some((open.target, open.start, reason));
cancelled = Some((open.target, open.start, reason, open.silent));
self.open = None;
}
for event in input.events {
@@ -618,10 +694,14 @@ impl<T: Copy> PressMachine<T> {
&& open.released_at.is_none()
&& !open.dragging
&& !open.abandoned
&& open.passing.is_none()
&& at.distance(open.start.origin) > input.slop
{
if open.sense.contains(Sense::DRAG) {
open.dragging = true;
open.silent = false;
} else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) {
open.passing = Some(at);
} else {
open.abandoned = true;
}
@@ -638,44 +718,70 @@ impl<T: Copy> PressMachine<T> {
if let Some(open) = self.open
&& let Some((up, click)) = open.released_at
{
released = Some((open.target, open.start, up, open.dragging, click));
released = Some((open.target, open.start, up, open.dragging, click, open.silent));
self.open = None;
}
// A secondary press during an open primary press goes beside it, to the context target `pick` gives
// it, and the primary press goes on (a right-click during a drag asks for the menu there).
if button == PointerButton::Secondary
&& self.aside.is_none()
&& self.open.is_some_and(|open| open.start.button == PointerButton::Primary)
{
let start = PressStart::new(at, button, time, clicks);
self.aside = pick(at, button).filter(|pick| pick.sense.contains(Sense::CONTEXT_CLICK)).map(|pick| (pick.target, start));
continue;
}
// An open press keeps the pointer until its button comes up: no press starts over it, of its own
// button (a repeated Down, as a window never sends one) or another. Its moves and its release still
// reach it when a modal opened over its target since. A middle or secondary press captures for a
// drag (a canvas pan, a drag with the secondary button) and never clicks. A target that senses
// `MIDDLE_CLICK` also takes a middle press that can click (a tab closes on it), and one that senses
// `CONTEXT_CLICK` takes a secondary press, which a click-only target would not capture.
// reach it when a modal opened over its target since. A middle press captures for a drag (a canvas
// pan) and never clicks, unless its target senses `MIDDLE_CLICK` (a tab closes on it). A secondary
// press is only a target's that senses `CONTEXT_CLICK`, which clicks and drags with it; a target that
// only drags (a transform box) leaves it to the context target under it.
let capture_only = button != PointerButton::Primary;
if !matches!(button, PointerButton::Primary | PointerButton::Middle | PointerButton::Secondary) || self.open.is_some() {
continue;
}
self.open = pick(at)
.map(|(target, sense)| {
self.open = pick(at, button)
.map(|pick| {
let clicks = match button {
PointerButton::Middle => sense.contains(Sense::MIDDLE_CLICK),
PointerButton::Secondary => sense.contains(Sense::CONTEXT_CLICK),
PointerButton::Middle => pick.sense.contains(Sense::MIDDLE_CLICK),
PointerButton::Secondary => pick.sense.contains(Sense::CONTEXT_CLICK),
_ => false,
};
(target, if capture_only && !clicks { sense - Sense::CLICK } else { sense }, clicks)
let sense = if capture_only && !clicks { pick.sense - Sense::CLICK } else { pick.sense };
(pick, sense, clicks)
})
.filter(|(_, sense, clicks)| !capture_only || *clicks || sense.contains(Sense::DRAG))
.map(|(target, sense, _)| (target, sense))
.map(|(target, sense)| Open {
target,
sense,
start: PressStart::new(at, button, time, clicks),
dragging: false,
abandoned: false,
left: false,
reported: false,
drag_reported: false,
released_at: None,
.filter(|(_, sense, clicks)| match button {
PointerButton::Primary => true,
PointerButton::Middle => *clicks || sense.contains(Sense::DRAG),
_ => *clicks,
})
.map(|(pick, sense, _)| {
// A silent press owes no `Down`: its first phase is its `DragStart`.
let silent = pick.passed && sense.contains(Sense::DRAG);
Open {
target: pick.target,
sense,
start: PressStart::new(at, button, time, clicks),
dragging: false,
abandoned: false,
left: false,
passing: None,
silent,
reported: silent,
drag_reported: false,
released_at: None,
}
});
}
PointerEvent::Released { button, pos: at } => {
pos = at;
if button == PointerButton::Secondary
&& let Some((target, start)) = self.aside.take()
{
aside = Some(PressAside { target, start, pos: at });
continue;
}
if self.open.is_some_and(|open| open.start.button != button || open.released_at.is_some()) {
continue;
}
@@ -684,7 +790,7 @@ impl<T: Copy> PressMachine<T> {
{
open.released_at = Some((at, open.clicks()));
} else if let Some(open) = self.open.take() {
released = Some((open.target, open.start, at, open.dragging, open.clicks()));
released = Some((open.target, open.start, at, open.dragging, open.clicks(), open.silent));
}
}
}
@@ -693,20 +799,38 @@ impl<T: Copy> PressMachine<T> {
if self.open.is_some_and(|open| open.released_at.is_none()) && !input.held && released.is_none() {
self.open = None;
}
if let Some((target, start, reason)) = cancelled {
let phase = PressPhase::Cancel { start, reason };
return PressStep { target: Some(target), phase: Some(phase), dragging: false, activated: None };
// An aside press lasts no longer than the press it went beside.
if self.open.is_none() {
self.aside = None;
}
if let Some((target, start, at, was_dragging, click)) = released {
let quiet = PressStep { aside, ..PressStep::default() };
if let Some((target, start, reason, silent)) = cancelled {
if silent {
return quiet;
}
let phase = PressPhase::Cancel { start, reason };
return PressStep { target: Some(target), phase: Some(phase), ..quiet };
}
if let Some((target, start, at, was_dragging, click, silent)) = released {
if silent {
return quiet;
}
let phase = PressPhase::Release { start, pos: at, click };
return PressStep {
target: Some(target),
phase: Some(phase),
dragging: was_dragging,
activated: (click && start.button == PointerButton::Primary).then_some(target),
..quiet
};
}
let Some(open) = self.open.as_mut() else { return PressStep::default() };
let Some(open) = self.open.as_mut() else { return quiet };
if open.silent {
return quiet;
}
if let Some(at) = &mut open.passing {
*at = pos;
}
let phase = if !open.reported {
PressPhase::Down { start: open.start }
} else if open.dragging && !open.drag_reported {
@@ -717,8 +841,33 @@ impl<T: Copy> PressMachine<T> {
} else {
PressPhase::Held { start: open.start, pos }
};
open.reported = true;
PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, activated: None }
// A passing press owes its `Down` to the shape `hand_over` gives it when this pass is its first.
if open.passing.is_none() {
open.reported = true;
}
let passes = open.passing.map(|_| open.start);
PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, passes, ..quiet }
}
/// Makes `target` the open press's target in the pass that reported `passes`, dragging from the same
/// `PressStart`. It returns the `DragStart` step when an earlier pass reported the press, and the `Down` step
/// (the `DragStart` follows in the next pass) when the move past slop came in the pass of the press itself.
/// `None` when no press passes in this pass or `sense` has no `DRAG`; the next pass abandons the press. The step
/// has no [`aside`](PressStep::aside): that stays the pass's own step's.
pub fn hand_over(&mut self, target: T, sense: Sense) -> Option<PressStep<T>> {
let open = self.open.as_mut().filter(|open| !open.abandoned && sense.contains(Sense::DRAG))?;
let at = open.passing.take()?;
open.target = target;
open.sense = sense;
open.dragging = true;
let phase = if open.reported {
open.drag_reported = true;
PressPhase::DragStart { start: open.start, pos: at }
} else {
open.reported = true;
PressPhase::Down { start: open.start }
};
Some(PressStep { target: Some(target), phase: Some(phase), dragging: open.drag_reported, ..PressStep::default() })
}
}
@@ -731,7 +880,7 @@ mod tests {
fn pass(machine: &mut PressMachine<u8>, events: &[PointerEvent], sense: Sense) -> PressStep<u8> {
let held = machine.open.is_some() || matches!(events.last(), Some(PointerEvent::Pressed { .. }));
machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_| Some((1, sense)))
machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_, _| Some(PressPick::new(1, sense)))
}
fn press(x: f32, time: f64) -> PointerEvent {
@@ -754,6 +903,37 @@ mod tests {
assert_eq!(step.activated, Some(1));
}
/// A right-click during a drag goes beside it: the secondary release reports an aside on the context target, and the
/// drag goes on to its own release. A secondary press on a target without `CONTEXT_CLICK` reports none.
#[test]
fn a_secondary_click_during_a_drag_reports_an_aside_and_the_drag_goes_on() {
let (from, to, menu) = (pos2(0.0, 0.0), pos2(40.0, 0.0), pos2(40.0, 5.0));
let mut machine = PressMachine::new();
let mut pass = |events: &[PointerEvent]| {
machine.step(PassInput::new(events, SLOP, to, true), |_, button| match button {
PointerButton::Secondary => Some(PressPick::new(2, Sense::CLICK | Sense::CONTEXT_CLICK)),
_ => Some(PressPick::new(1, Sense::DRAG)),
})
};
pass(&[PointerEvent::pressed(from, 1.0, 1)]);
pass(&[PointerEvent::moved(to, None)]);
let down = pass(&[PointerEvent::pressed_by(PointerButton::Secondary, menu, 1.2, 1)]);
assert!(down.aside.is_none(), "nothing asks before the secondary button comes up");
assert!(matches!(down.phase, Some(PressPhase::Drag { .. })), "the drag goes on: {down:?}");
let up = pass(&[PointerEvent::released_by(PointerButton::Secondary, menu)]);
assert_eq!(up.aside.map(|aside| (aside.target, aside.pos)), Some((2, menu)), "the release asks the context target");
assert_eq!(up.target, Some(1), "the drag keeps its target");
assert!(up.phase.is_some_and(|phase| phase.is_drag()), "and its drag: {up:?}");
let end = pass(&[PointerEvent::released(to)]);
assert!(matches!(end.phase, Some(PressPhase::Release { .. })) && end.aside.is_none(), "the drag ends on its own release: {end:?}");
let mut machine = PressMachine::new();
let mut pass = |events: &[PointerEvent]| machine.step(PassInput::new(events, SLOP, to, true), |_, _| Some(PressPick::new(1, Sense::DRAG)));
pass(&[PointerEvent::pressed(from, 1.0, 1)]);
pass(&[PointerEvent::pressed_by(PointerButton::Secondary, menu, 1.2, 1)]);
assert!(pass(&[PointerEvent::released_by(PointerButton::Secondary, menu)]).aside.is_none(), "a drag-only target takes no aside");
}
/// The phases a sequence of passes reports, as `D`own, `H`eld, `S` (drag start), `G` (drag), `R`elease with `!` for an
/// activation, `-` for none.
fn phases(passes: &[&[PointerEvent]], sense: Sense) -> String {
@@ -783,8 +963,9 @@ mod tests {
fn a_press_of_the_held_button_leaves_the_open_drag_its_moves_and_release() {
let first = pos2(0.0, 0.0);
let mut machine = PressMachine::new();
let mut step =
|events: &[PointerEvent]| machine.step(PassInput::new(events, SLOP, first, true), |at| (at == first).then_some((1u8, Sense::DRAG)));
let mut step = |events: &[PointerEvent]| {
machine.step(PassInput::new(events, SLOP, first, true), |at, _| (at == first).then_some(PressPick::new(1u8, Sense::DRAG)))
};
step(&[press(0.0, 1.0)]);
step(&[PointerEvent::Moved { at: pos2(40.0, 0.0), sample: None }]);
let repeated = step(&[press(50.0, 1.2)]);
@@ -855,4 +1036,79 @@ mod tests {
let passes: [&[PointerEvent]; 5] = [&[press(0.0, 1.0)], &[up, second], &[far, up], &[], &[]];
assert_eq!(phases(&passes, Sense::CLICK | Sense::DRAG), "D R! D S R");
}
const PASSES: Sense = Sense::CLICK.union(Sense::PASSES_DRAG);
/// One pass with the button held at its end, over a root whose press winner is target 1 and passes its drag.
fn passing_pass(machine: &mut PressMachine<u8>, events: &[PointerEvent]) -> PressStep<u8> {
machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), true), |_, _| Some(PressPick::new(1, PASSES)))
}
fn moved(x: f32) -> PointerEvent {
PointerEvent::Moved { at: pos2(x, 0.0), sample: None }
}
fn up(x: f32) -> PointerEvent {
PointerEvent::released(pos2(x, 0.0))
}
#[test]
fn a_drag_past_slop_on_a_part_that_passes_it_goes_to_the_shape_below() {
let origin = pos2(0.0, 0.0);
assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "within slop the press is the shape's click");
// The press was reported in an earlier pass: the shape below drags from the pass of the move.
let mut machine = PressMachine::new();
let down = passing_pass(&mut machine, &[press(0.0, 1.0)]);
assert!(matches!(down.phase, Some(PressPhase::Down { .. })) && down.passes.is_none(), "{down:?}");
assert!(machine.hand_over(2, Sense::DRAG).is_none(), "a press within slop passes nothing");
let passed = passing_pass(&mut machine, &[moved(40.0)]);
assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{passed:?}");
let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag");
assert_eq!(handed.target, Some(2));
assert!(
matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(40.0, 0.0)),
"{:?}",
handed.phase
);
let drag = passing_pass(&mut machine, &[moved(60.0)]);
assert_eq!(drag.target, Some(2));
assert!(matches!(drag.phase, Some(PressPhase::Drag { .. })), "{:?}", drag.phase);
let end = passing_pass(&mut machine, &[up(60.0)]);
assert_eq!(end.target, Some(2));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
assert_eq!(end.activated, None, "a passed press is no click");
}
/// The move past slop came in the press's own pass: the shape below gets the Down, its DragStart next pass, and a
/// release in between waits for it.
#[test]
fn a_drag_past_slop_in_the_press_pass_hands_the_down_over() {
let origin = pos2(0.0, 0.0);
let mut machine = PressMachine::new();
let first = passing_pass(&mut machine, &[press(0.0, 1.0), moved(40.0)]);
assert!(matches!(first.phase, Some(PressPhase::Down { .. })) && first.passes.is_some(), "{first:?}");
let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag");
assert_eq!(handed.target, Some(2));
assert!(matches!(handed.phase, Some(PressPhase::Down { start }) if start.origin == origin), "{:?}", handed.phase);
let start = passing_pass(&mut machine, &[up(40.0)]);
assert_eq!(start.target, Some(2));
assert!(matches!(start.phase, Some(PressPhase::DragStart { .. })), "{:?}", start.phase);
assert!(machine.release_held(), "the release waits for the owed DragStart");
let end = passing_pass(&mut machine, &[]);
assert_eq!(end.target, Some(2));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
}
/// No shape took the passed press: it is abandoned, and its release is no click.
#[test]
fn a_passed_press_no_shape_takes_is_abandoned() {
let mut machine = PressMachine::new();
let _ = passing_pass(&mut machine, &[press(0.0, 1.0)]);
assert!(passing_pass(&mut machine, &[moved(40.0)]).passes.is_some());
let end = passing_pass(&mut machine, &[up(40.0)]);
assert_eq!(end.target, Some(1));
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
assert_eq!(end.activated, None);
}
}
+6 -1
View File
@@ -30,7 +30,8 @@ bitflags! {
/// The zoom share (Ctrl or Cmd with the wheel, pinch), taken without scroll; the split rule passes both scroll shares on.
const WHEEL_ZOOM = 1024;
/// A secondary press captures the part and its release is reported to it, so a part that senses only a click
/// still gets its context click. Without this bit a secondary press only captures for a drag.
/// still gets its context click, and one that drags drags with the secondary button too. Without this bit the
/// shape takes no secondary press: it goes to the next shape under it that senses this bit.
const CONTEXT_CLICK = 2048;
/// A container root learns of a primary press on its own surface: inside its rect, on its layer, where no
/// shape takes the press. The root takes no press and no focus by it, so it is no click target.
@@ -50,6 +51,10 @@ bitflags! {
/// with `DRAG` by a part whose click does nothing a drag could be mistaken for (a transform box's handles).
/// The component begins the gesture from `PressPhase::Held`.
const FOLLOWS_IN_SLOP = 65536;
/// A press on this shape that moves past slop is not the shape's: the press passes to the shape ranked under
/// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`,
/// without `DRAG`.
const PASSES_DRAG = 131072;
}
}
+18
View File
@@ -238,4 +238,22 @@ mod tests {
typing.edit(&mut run, &Some(5.0), "9");
assert_eq!(typing.escape(&mut run), Escaped::Restore(Some(5.0)));
}
/// A field's value can change under a half-typed draft (a panel's selection changes): the draft and the value the
/// run began from must stay, so the commit and Escape work from what the user started typing over.
#[test]
fn a_draft_survives_an_outside_value_change_until_commit() {
let typing = TypingRun::new(NumberCodec::default());
let (began, outside) = (Some(12.0), Some(24.0));
let mut run = EditRun::new(began);
typing.edit(&mut run, &began, "+");
typing.edit(&mut run, &outside, "+6");
assert_eq!(typing.shown(&run, &outside), "+6", "the open draft is shown, not the value that changed under it");
assert_eq!(run.start, began, "the run keeps the value it began from");
assert_eq!(typing.commit(&mut run), Ended::Commit(Some(18.0)), "relative input applies to the value the run began from");
typing.edit(&mut run, &began, "9");
typing.edit(&mut run, &outside, "90");
assert_eq!(typing.escape(&mut run), Escaped::Restore(began), "Escape restores the value from before the run");
}
}
+164
View File
@@ -88,6 +88,133 @@ pub struct Wheel {
pub touch_rotation: f32,
/// Two fingers' movement this pass, in points.
pub touch_pan: Vec2,
/// The running gesture's scroll gathered so far, this share included, in its owner's points.
pub gathered: Vec2,
/// Whether the owner marked the running gesture moved (`Pointer::mark_wheel_moved`).
pub moved: bool,
}
/// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WheelEase {
owed: kurbo::Vec2,
burst: u32,
last_notch: f64,
last_sign: Vec2,
last_paid: f64,
}
/// Notches closer than this many seconds are a fast spin and grow the burst.
const FAST_NOTCH: f64 = 0.08;
/// Notches this many seconds apart, or more, start a new burst.
const BURST_RESET: f64 = 0.3;
/// The multiplier one fast notch adds.
const BURST_STEP: f32 = 0.4;
/// The burst notches that count toward the multiplier.
const BURST_TICKS: u32 = 13;
/// Notches kept past `BURST_TICKS`, so a few slower notches in a spin do not drop the multiplier at once.
const BURST_HOLD: u32 = 4;
/// The largest multiplier.
const BURST_CAP: f32 = 6.0;
/// The most motion owed on an axis, in points: a hostile run of notches cannot grow it without bound.
const MAX_OWED: f32 = 16384.0;
/// The longest pass the ease pays for, in seconds: after a stall it does not jump the whole way at once.
const LONGEST_PASS: f64 = 0.1;
/// The seconds a pass is taken to last when the ease starts from rest, so the first notch moves in its own pass.
const FIRST_PASS: f64 = 1.0 / 60.0;
/// Owed motion this small, in points, is paid whole.
const SETTLE: f32 = 0.01;
/// The sign of `v`: 0 for zero, where `f32::signum` gives 1.
fn sign(v: f32) -> f32 {
if v > 0.0 {
1.0
} else if v < 0.0 {
-1.0
} else {
0.0
}
}
impl WheelEase {
/// Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart
/// accelerates it, a reversal or 0.3 s idle resets the burst.
pub fn feed(&mut self, pan: Vec2, now: f64) {
if !now.is_finite() || !pan.is_finite() || pan == Vec2::ZERO {
return;
}
let signs = Vec2::new(sign(pan.x), sign(pan.y));
let idle = now - self.last_notch;
let reversed = signs.x * self.last_sign.x < 0.0 || signs.y * self.last_sign.y < 0.0;
if self.last_sign == Vec2::ZERO || !(0.0..BURST_RESET).contains(&idle) || reversed {
self.burst = 0;
} else if idle < FAST_NOTCH {
self.burst = (self.burst + 1).min(BURST_TICKS + BURST_HOLD);
} else {
// A slower notch in the same direction sheds one, rather than extending the burst.
self.burst = self.burst.saturating_sub(1);
}
self.last_notch = now;
self.last_sign = signs;
let boost = (1.0 + BURST_STEP * self.burst.min(BURST_TICKS) as f32).min(BURST_CAP);
if !self.owes() {
self.last_paid = now - FIRST_PASS;
}
self.owed = kurbo::Vec2::new(owe(self.owed.x, f64::from(pan.x * boost)), owe(self.owed.y, f64::from(pan.y * boost)));
}
/// Drops the owed motion on the axes marked.
pub fn cancel_axis(&mut self, x: bool, y: bool) {
if x {
self.owed.x = 0.0;
}
if y {
self.owed.y = 0.0;
}
}
/// The step this pass pays at time `now`: `1 − 0.1^(dt/0.1)` of the owed motion, with `dt` since the last paid pass.
pub fn step(&mut self, now: f64) -> Vec2 {
if !now.is_finite() || now < self.last_paid {
// A clock that runs backwards or breaks cannot tell how much to pay: the tail goes.
self.owed = kurbo::Vec2::ZERO;
self.last_paid = if now.is_finite() { now } else { self.last_paid };
return Vec2::ZERO;
}
let dt = (now - self.last_paid).min(LONGEST_PASS);
self.last_paid = now;
if !self.owes() || dt <= 0.0 {
return Vec2::ZERO;
}
let fraction = 1.0 - 0.1_f64.powf(dt / 0.1);
let paid = Vec2::new(pay(self.owed.x, fraction), pay(self.owed.y, fraction));
self.owed -= kurbo::Vec2::new(f64::from(paid.x), f64::from(paid.y));
// A tail below normal f32 precision cannot move a view and must not keep scheduling frames.
if self.owed.x.abs() < f64::from(f32::MIN_POSITIVE) {
self.owed.x = 0.0;
}
if self.owed.y.abs() < f64::from(f32::MIN_POSITIVE) {
self.owed.y = 0.0;
}
paid
}
/// Whether motion is still owed.
pub fn owes(&self) -> bool {
self.owed != kurbo::Vec2::ZERO
}
}
/// `owed` with `more` added on one axis: motion the other way drops what was owed, and the sum stays within
/// `MAX_OWED`.
fn owe(owed: f64, more: f64) -> f64 {
let owed = if more * owed < 0.0 { 0.0 } else { owed };
(owed + more).clamp(-f64::from(MAX_OWED), f64::from(MAX_OWED))
}
/// The part of `owed` one pass pays, `fraction` of it; a remainder under `SETTLE` is paid whole.
fn pay(owed: f64, fraction: f64) -> f32 {
if owed.abs() <= f64::from(SETTLE) { owed as f32 } else { (owed * fraction) as f32 }
}
impl Wheel {
@@ -107,6 +234,8 @@ impl Wheel {
rotation: 0.0,
touch_rotation: 0.0,
touch_pan: Vec2::ZERO,
gathered: Vec2::ZERO,
moved: false,
}
}
@@ -658,4 +787,39 @@ mod tests {
let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0);
assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::<Vec<_>>(), [(2, false)], "the horizontal share passes the zone");
}
#[test]
fn fast_notches_accelerate_to_a_cap_and_reset_on_reversal_or_idle_but_a_lone_notch_does_not() {
const NOTCH: f64 = 40.0;
// What one notch of `y` points adds to the owed motion.
let notch = |ease: &mut WheelEase, y: f64, now: f64| {
let before = ease.owed.y;
ease.feed(Vec2::new(0.0, y as f32), now);
ease.owed.y - before
};
let mut ease = WheelEase::default();
assert_eq!(notch(&mut ease, NOTCH, 1.0), NOTCH, "a lone notch is one notch");
assert_eq!(notch(&mut ease, NOTCH, 1.5), NOTCH, "a slow notch is one notch");
let mut gains = Vec::new();
for i in 1..=20 {
gains.push(notch(&mut ease, NOTCH, 1.5 + f64::from(i) * 0.02));
}
// The owed sum rounds in its last bits, so per-notch gains compare within a hundredth of a point.
let near = |a: f64, b: f64| (a - b).abs() < 0.01;
assert!(gains.windows(2).all(|pair| pair[1] > pair[0] - 0.01), "a fast run never pays less per notch: {gains:?}");
let fastest = gains.iter().copied().fold(0.0, f64::max);
assert!(fastest > 2.0 * NOTCH, "a fast run accelerates: {gains:?}");
assert!(fastest < 6.0 * NOTCH + 0.01, "the acceleration is capped: {gains:?}");
assert!(gains.last().is_some_and(|&last| near(last, 6.0 * NOTCH)), "a long run reaches the cap and stays there: {gains:?}");
notch(&mut ease, -NOTCH, 1.5 + 21.0 * 0.02);
assert_eq!(ease.owed.y, -NOTCH, "a reversal drops what was owed and starts again at one notch");
for i in 1..=10 {
notch(&mut ease, -NOTCH, 2.0 + f64::from(i) * 0.02);
}
assert!(notch(&mut ease, -NOTCH, 2.0 + 11.0 * 0.02) < -NOTCH - 1.0, "precondition: the run is fast again");
assert!(near(notch(&mut ease, -NOTCH, 5.0), -NOTCH), "an idle gap starts again at one notch");
}
}
+16 -2
View File
@@ -1,7 +1,8 @@
//! The direction lock of the move gesture.
use craft_behavior::geometry::{Directions, lock_direction};
use kurbo::Vec2;
use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, lock_direction};
use craft_keymap::Mods;
use kurbo::{Point, Vec2};
fn polar(deg: f64, len: f64) -> Vec2 {
let a = deg.to_radians();
@@ -19,3 +20,16 @@ fn lock_direction_keeps_the_axis_until_eight_degrees_past_half() {
let switched = lock_direction(polar(31.0, 10.0), Some(axis), Directions::Eight);
assert!((switched.y - switched.x).abs() < 1e-9 && switched.y > 0.0);
}
#[test]
fn a_shift_move_with_four_directions_locks_an_axis_and_frees_it_when_shift_is_let_go() {
let mut drag = MoveGesture::press(&ConstrainStyle::new(4.0, 4.0), Point::ZERO, Mods::SHIFT, Directions::Four);
let at = Point::new(10.0, 3.0);
let locked = drag.follow(at, Mods::SHIFT, 1.0).expect("the move changed the value");
assert_eq!(locked.delta.y, 0.0, "Shift holds the offset to the horizontal axis: {:?}", locked.delta);
assert!(locked.delta.x > 0.0, "{:?}", locked.delta);
assert!(drag.locked().is_some(), "the lock is remembered while Shift is down");
let free = drag.follow(at, Mods::NONE, 1.0).expect("letting Shift go changed the value");
assert_eq!(free.delta, Vec2::new(10.0, 3.0), "without Shift the offset is free");
assert_eq!(drag.locked(), None, "the lock is forgotten when Shift is let go");
}
+21
View File
@@ -13,6 +13,18 @@ fn session() -> BoxState {
BoxState::from_rect(Rect::new(0.0, 0.0, 100.0, 50.0))
}
#[test]
fn corner_drag_preserves_the_offset_of_the_press() {
let start = session();
let press = p(96.0, 47.0);
let rules = BoxRules::default();
let back = drag(&start, &start, BoxPart::Corner(2), press, press, Mods::default(), &rules);
assert_eq!(back, start, "returning to the press must restore the box");
let moved = drag(&start, &start, BoxPart::Corner(2), press, press + Vec2::new(20.0, 10.0), Mods::SHIFT, &rules);
assert!(near(moved.quad[2], start.quad[2] + Vec2::new(20.0, 10.0)), "the corner follows the movement, keeping the press offset");
assert!(near(moved.quad[0], start.quad[0]), "the opposite corner stays fixed");
}
fn dragged(from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState {
let start = session();
drag(&start, &start, start.part_at(from, 8.0), from, to, mods, rules)
@@ -31,6 +43,15 @@ fn turns(q: &[Point; 4]) -> [f64; 4] {
std::array::from_fn(|k| (q[(k + 1) % 4] - q[k]).cross(q[(k + 2) % 4] - q[(k + 1) % 4]))
}
#[test]
fn proportional_corner_uses_the_larger_relative_drag_even_when_shrinking() {
let rules = BoxRules::default().with_scale(ScaleRule::LargerAxis);
let wider = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, &rules);
assert!(corners_are(&wider, 0.0, 0.0, 200.0, 100.0));
let smaller = dragged(p(100.0, 50.0), p(75.0, 50.0), Mods::NONE, &rules);
assert!(corners_are(&smaller, 0.0, 0.0, 75.0, 37.5));
}
#[test]
fn a_proportional_corner_follows_the_diagonal_and_flips_past_the_anchor() {
let rules = BoxRules::default();
+1
View File
@@ -10,3 +10,4 @@ mod fit;
mod geometry;
mod hit_excluding;
mod key_table;
mod middle_scroll;
+77
View File
@@ -0,0 +1,77 @@
//! The middle button's auto-scroll latch.
use craft_behavior::{MiddleScroll, PointerButton, PressCancel, PressPhase, PressStart};
use emath::{Vec2, pos2};
/// One frame's elapsed time.
const FRAME: f64 = 1.0 / 60.0;
/// A click keeps the latch, as does a hold of one frame even when that frame runs a second pass; a hold of two frames
/// past the dead zone ends it on release.
#[test]
fn a_click_inside_the_dead_zone_latches_and_a_hold_past_it_ends_on_release() {
let anchor = pos2(100.0, 100.0);
let past = pos2(100.0, 140.0);
let mut latch = MiddleScroll::default();
latch.press(anchor, true);
assert_eq!(latch.step(pos2(100.0, 105.0), true, FRAME, false), Vec2::ZERO, "inside the dead zone nothing scrolls");
latch.release();
assert!(latch.active(), "a click latches");
assert_eq!(latch.anchor(), Some(anchor));
let scroll = latch.step(past, false, FRAME, false);
assert!(scroll.y < 0.0 && scroll.x == 0.0, "past the dead zone below the anchor the view scrolls down: {scroll:?}");
latch.step(past, false, FRAME, false);
latch.release();
assert!(latch.active(), "passes with the button up count no hold");
latch.press(anchor, true);
assert!(!latch.active(), "a second press ends the latch");
assert_eq!(latch.anchor(), None);
// One frame held past the dead zone, rerun as a second pass with no elapsed time.
latch.press(anchor, true);
latch.step(past, true, FRAME, false);
latch.step(past, true, 0.0, false);
latch.release();
assert!(latch.active(), "one held frame is a click, however many passes it runs");
// A fresh latch starts its count over: one more held frame is still a click.
latch.press(anchor, true);
latch.press(anchor, true);
latch.step(past, true, FRAME, false);
latch.release();
assert!(latch.active(), "the count starts over at each latch");
latch.press(anchor, true);
latch.press(anchor, true);
latch.step(past, true, FRAME, false);
latch.step(past, true, FRAME, false);
latch.release();
assert!(!latch.active(), "a hold of two frames past the dead zone ends on release");
assert_eq!(latch.anchor(), None);
}
/// A primary click that ends the latch is swallowed from its press through its release; the next click is not.
#[test]
fn a_primary_click_that_ends_auto_scroll_is_swallowed_through_its_release() {
let at = pos2(100.0, 100.0);
let start = PressStart::new(at, PointerButton::Primary, 0.0, 1);
let down = PressPhase::Down { start };
let held = PressPhase::Held { start, pos: at };
let release = PressPhase::Release { start, pos: at, click: true };
let mut latch = MiddleScroll::default();
latch.press(at, true);
assert!(latch.swallows(down), "the press that ends the latch is swallowed");
assert!(!latch.active());
assert!(latch.swallows(held), "its later phases are too");
assert!(latch.swallows(release), "through its release");
assert!(!latch.swallows(down), "the next click, with nothing latched, is not");
assert!(!latch.swallows(held));
assert!(!latch.swallows(release));
latch.press(at, true);
assert!(latch.swallows(down));
assert!(latch.swallows(PressPhase::Cancel { start, reason: PressCancel::Escape }));
assert!(!latch.swallows(held), "a cancel ends the swallowed press");
}
+1 -1
View File
@@ -223,7 +223,7 @@ impl<K: Clone + Send + 'static> SearchRun<K> {
wake: Wake,
) -> Self {
// filmcraft: crates/ui-egui/src/panels/media_dialogs.rs:146 (`link_media` ran `media.search` on the UI thread).
let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search" });
let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search", ..QueueOptions::default() });
let updates = Arc::new(Mutex::new(Vec::new()));
let cancel = Cancel::new();
let inbox = Arc::clone(&updates);
+2 -2
View File
@@ -11,7 +11,7 @@ use craft_ui::contract::{
use craft_ui::list::ThumbAspect;
use craft_ui::primitives::ContentPainterCx;
use craft_ui::primitives::textures::{Priority, TextureKey, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails};
use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid, TilePartEvent};
use craft_ui::tile_grid::{CaptionPlace, GridZoom, Tile, TileGrid, TilePartEvent};
use egui::{Rect, Ui};
use super::list::{drop_items, inside_any, item_of, open_event, rename_event, reorder_event, sort_entries, stack_event};
@@ -172,7 +172,7 @@ where
.caption(CaptionPlace::Below)
.detail_line()
.aspect(ASPECT)
.zoom(state.settings.zoom as f32)
.zoom(GridZoom::Fixed(state.settings.zoom))
.rename(true)
.deletable(true)
.rows_stamp(stamp_of(state.shown.as_ref(), &state.search, state.settings.icon_sort.as_ref()))
+1 -1
View File
@@ -634,7 +634,7 @@ impl<K: Clone + PartialEq + Send + Sync + 'static> Model<K> {
let ctx = ctx.clone();
Wake::new(move || ctx.request_repaint())
};
let checks = JobQueue::new(Arc::clone(&jobs), wake.clone(), QueueOptions { lanes: 1, name: "relink-check" });
let checks = JobQueue::new(Arc::clone(&jobs), wake.clone(), QueueOptions { lanes: 1, name: "relink-check", ..QueueOptions::default() });
self.runtime = Some(Runtime { jobs, wake, checks });
}
self.poll_pick();
+7 -7
View File
@@ -20,7 +20,6 @@ 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 _,
};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Row;
use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetRowMenu, PresetState};
use craft_ui::primitives::textures::CachedTexture;
@@ -217,7 +216,7 @@ pub struct PaintChipStyle {
radius: egui::CornerRadius,
/// The ring on the chip's outline.
edge: StyleColor,
/// The fill of an empty chip: the field's.
/// The fill of a picture chip with no texture yet: the field's.
none_fill: StyleColor,
/// The No Color diagonal.
none_mark: StyleColor,
@@ -594,7 +593,7 @@ impl Component for PaintChip<'_> {
let solid = cx.memory::<LastSolid>().0.unwrap_or(self.fallback);
let current = FillKind::of(&paint);
let sampled = self.sampled;
let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
let recent = self.recent;
let full_picker = self.full_picker;
let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated());
let solid_now = if let Paint::Solid(color) = &paint { Some(*color) } else { None };
@@ -624,11 +623,12 @@ impl Component for PaintChip<'_> {
compact_picker(name.clone(), Bind::given(PickedColor::rgb(*color)), sampled).alpha(true).eyedropper(true).show(ui);
shown.edit = picked.events;
shown.screen_pick = picked.screen_pick;
if !recent_cells.is_empty() {
Text::new(words.recent.clone()).shade(Shade::Faint).show(ui);
if !recent.is_empty() {
// A palette of no swatches: the recent row alone, under its caption.
let mut chosen = *color;
let recent = SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &recent_cells).show(ui);
shown.picked = recent.edit.as_ref().and_then(|edit| edit.value()).copied();
let row =
SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &[]).recent(words.recent.clone(), recent).show(ui);
shown.picked = row.picked;
}
if let Some((groups, state)) = swatches.as_mut() {
let groups: &[SwatchGroup] = groups;
+2 -2
View File
@@ -8,7 +8,7 @@ use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, DragPreview, DropMark, DropOperation, DropTarget, Edit as _, EditResponse, Focus as _, MeasureCx,
Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
};
use craft_ui::primitives::{Glyph, IconSpec, PaintShape, StrokeWidth};
use craft_ui::primitives::{Glyph, IconSpec, PaintShape, StrokeWidth, WellFill};
use craft_ui::runtime::commands::FireSource;
use craft_ui::runtime::env::Label;
use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, SurfaceEdge, SurfaceStyle, UiTokens};
@@ -606,7 +606,7 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
};
paint_well(ui, cx, at, paint, &look);
}
None => ui.draw().swatch_well(at, style.radius, None),
None => ui.draw().swatch_well(at, style.radius, WellFill::Mixed),
}
// A ring well draws its own outlines.
if shown.paint.same().is_none() || !shown.ring {
+173 -31
View File
@@ -1,12 +1,16 @@
//! `SwatchPalette`: a wrapping grid of colour cells that chooses one colour. Its table of cells is
//! `craft_ui::choice::SwatchTable`.
use craft_behavior::{EditEvent, Mixed, Selection};
use craft_behavior::{EditEvent, IconId, Mixed, Selection};
use craft_theme::Srgba;
use craft_ui::choice::{SwatchSpacing, SwatchTable};
use craft_ui::contract::{Bind, Held, ListDrag, NoValue, Outcome, Pattern, ShowContainer as _};
use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::StageAccess;
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::style::TypeRole;
use egui::{Response, Ui};
use std::sync::Arc;
@@ -23,9 +27,14 @@ type TableMap = Arc<dyn for<'t> Fn(SwatchTable<'t>) -> SwatchTable<'t>>;
pub struct SwatchPaletteOutput {
/// The palette's response.
pub response: Response,
/// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked. The palette has
/// already written it to its binding.
/// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked or the pick was the
/// colour already bound. The palette has already written it to its binding.
pub edit: Option<EditEvent<Srgba>>,
/// The request of the Other… cell for the host's colour picker, at the bound colour and keyed by the key given to
/// [`SwatchPalette::other`], when it was activated this pass.
pub pick_color: Option<ColorRequest>,
/// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`.
pub picked: Option<Srgba>,
}
impl Outcome for SwatchPaletteOutput {
@@ -39,27 +48,104 @@ impl Outcome for SwatchPaletteOutput {
/// A wrapping grid of colour cells from the host's list of named colours that chooses one colour.
///
/// - The swatch equal to the colour (compared in 8 bits, the first when several are) is selected; the name is its
/// tooltip.
/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`.
/// tooltip. An [`optional`](Self::optional) palette bound to no colour, or to a mixed one, selects none.
/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`; a click on the
/// colour already bound sets nothing and still reports `picked`.
/// - The palette is one Tab stop: Tab enters on the selected swatch (the first when none is) and the next Tab leaves.
/// Arrows move the focus through the cells as the rows lie, Up and Down to the cell above or below; they choose
/// nothing.
/// - [`other`](Self::other) adds an Other… cell after the swatches, in the same Tab stop and arrow walk: activating it
/// files `pick_color` and sets nothing. [`recent`](Self::recent) adds a captioned row of recent colours under the
/// grid, its own Tab stop, whose pick sets the colour as a swatch's does.
/// - AccessKit: a list box named by the label; each cell a list box option named by its name, with the hex colour as
/// its value.
#[must_use = "show the palette with `show`"]
#[derive(Pattern)]
pub struct SwatchPalette<'a> {
label: Label,
color: Bind<'a, Srgba>,
color: PaletteColor<'a>,
swatches: &'a [(Label, Srgba)],
spacing: SwatchSpacing,
drag: Option<TableMap>,
/// The Other… cell: the key of its colour request and its name.
other: Option<(String, Label)>,
/// The recent row: its caption and colours.
recent: Option<(Label, &'a [Srgba])>,
}
/// What a palette binds: a colour, or a colour that may be none.
enum PaletteColor<'a> {
Color(Held<'a, Srgba>),
Optional(Bind<'a, Option<Srgba>>),
}
impl PaletteColor<'_> {
/// The bound colour as the palette shows it: `Same(None)` for no colour (or an optional binding that holds
/// nothing), `Mixed` for several. `None` while a plain colour's binding holds no single colour, and the palette
/// shows nothing.
fn read(&mut self, cx: &mut impl StageAccess) -> Option<Mixed<Option<Srgba>>> {
match self {
PaletteColor::Color(held) => held.read(cx).map(|color| Mixed::Same(Some(color))),
PaletteColor::Optional(bind) => Some(bind.reborrow().read(cx).unwrap_or(Mixed::Same(None))),
}
}
/// Writes `after` over `before` as one `Set` named `name`.
fn write(&mut self, cx: &mut impl StageAccess, before: Mixed<Option<Srgba>>, after: Srgba, name: &str) {
match self {
PaletteColor::Color(held) => {
if let Mixed::Same(Some(before)) = before {
held.write(cx, &before, after, name);
}
}
PaletteColor::Optional(bind) => {
let _ = bind.reborrow().write(cx, &EditEvent::set(before, Some(after), Arc::from(name), None));
}
}
}
}
/// What the body picked in its pass.
#[derive(Clone, Copy)]
enum Pick {
/// A swatch or a recent colour.
Color(Srgba),
/// The Other… cell.
Other,
}
/// The cell of `swatches` whose colour is `color`, compared in 8 bits: the first when several are.
fn cell_of(swatches: &[(Label, Srgba)], color: Option<Srgba>) -> Selection<usize> {
color.and_then(|color| swatches.iter().position(|(_, c)| c.to_rgba() == color.to_rgba())).map_or_else(Selection::default, Selection::single)
}
impl<'a> SwatchPalette<'a> {
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
SwatchPalette { label: label.into(), color, swatches, spacing: SwatchSpacing::Touching, drag: None }
SwatchPalette {
label: label.into(),
color: PaletteColor::Color(Held::new(color)),
swatches,
spacing: SwatchSpacing::Touching,
drag: None,
other: None,
recent: None,
}
}
/// A palette over a colour that may be none: a host binds its `Mixed<Option<Srgba>>` with `Bind::bound_mixed`.
/// No swatch is selected for `Same(None)` or `Mixed`, and a pick writes `Mixed::Same(Some(colour))` and reports
/// the same `edit` as [`new`](Self::new), its `before` the colour or `Mixed` when there was none.
pub fn optional(label: impl Into<Label>, color: Bind<'a, Option<Srgba>>, swatches: &'a [(Label, Srgba)]) -> Self {
SwatchPalette {
label: label.into(),
color: PaletteColor::Optional(color),
swatches,
spacing: SwatchSpacing::Touching,
drag: None,
other: None,
recent: None,
}
}
/// The gap between the cells, passed on to its `SwatchTable`.
@@ -78,36 +164,92 @@ impl<'a> SwatchPalette<'a> {
self
}
/// An Other… cell after the swatches, named `label`: activating it files a `ColorRequest` keyed `key` at the bound
/// colour as `pick_color`, for the host's own picker, and sets nothing.
pub fn other(mut self, key: impl Into<String>, label: impl Into<Label>) -> Self {
self.other = Some((key.into(), label.into()));
self
}
/// A row of recent `colors` under `caption`, below the grid, each named by its hex; an empty slice shows no row.
pub fn recent(mut self, caption: impl Into<Label>, colors: &'a [Srgba]) -> Self {
self.recent = Some((caption.into(), colors));
self
}
/// Shows the palette.
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
let SwatchPalette { label, color, swatches, spacing, drag } = self;
let mut held = Held::new(color);
let SwatchPalette { label, mut color, swatches, spacing, drag, other, recent } = self;
let recent = recent.filter(|(_, colors)| !colors.is_empty());
let recent_cells: Vec<(Label, Srgba)> =
recent.iter().flat_map(|(_, colors)| colors.iter()).map(|color| (Label::from(color.to_hex()), *color)).collect();
let name = label.clone();
let mut shown = Stack::new().show(ui, |ui, cx| {
let before = held.read(cx)?;
let selected = swatches.iter().position(|(_, c)| c.to_rgba() == before.to_rgba());
let mut current = selected.map_or_else(Selection::default, Selection::single);
let table = SwatchTable::new(label.clone(), swatches).tips(true).wells(true).spacing(spacing).selection(Bind::bound(&mut current));
let table = match &drag {
Some(map) => map(table),
None => table,
};
let table = table.show_all(ui);
let picked = table.selected.or(table.open)?;
let after = swatches.get(picked)?.1;
if after.to_rgba() == before.to_rgba() {
return None;
let before = color.read(cx)?;
let bound = before.same().copied().flatten();
let mut current = cell_of(swatches, bound);
// A palette of recent colours alone has no grid: an empty table would be an empty list box in the tree.
let mut pick = None;
if !swatches.is_empty() || other.is_some() {
// Every click activates, so a click on the swatch already selected, which changes no selection, still picks.
let mut table = SwatchTable::new(label.clone(), swatches)
.tips(true)
.wells(true)
.spacing(spacing)
.activate(ActivateOn::Click)
.selection(Bind::bound(&mut current));
if let Some(map) = &drag {
table = map(table);
}
if let Some((_, other_label)) = &other {
table = table.trailing(other_label.clone(), IconId::new("plus"));
}
let table = table.show_all(ui);
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
// on its release, so only the activation files the request: one request for one click.
pick = table.selected.or(table.open).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color(*picked)),
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
});
}
Some((before, after))
if let Some((caption, _)) = &recent {
Text::new(caption.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
let mut current = cell_of(&recent_cells, bound);
let row = SwatchTable::new(caption.clone(), &recent_cells)
.tips(true)
.wells(true)
.activate(ActivateOn::Click)
.selection(Bind::bound(&mut current))
.show_all(ui);
if let Some((_, picked)) = row.selected.or(row.open).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color(*picked));
}
}
Some((before, pick))
});
// Once per pass, after the real run: the picked colour is stored and reported.
let edit = shown
.settle(|cx, picked| {
let (before, after) = picked.take()?;
held.write(cx, &before, after, name.as_str());
Some(EditEvent::set(Mixed::Same(before), after, Arc::from(name.as_str()), None))
// Once per pass, after the real run: a changed colour is stored and reported, every pick is reported.
let settled = shown
.settle(|cx, result| {
let (before, pick) = result.take()?;
let bound = before.same().copied().flatten();
match pick? {
Pick::Other => {
let key = other.as_ref().map(|(key, _)| key.clone())?;
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone()))))
}
Pick::Color(after) => {
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
let edit = (!unchanged).then(|| {
color.write(cx, before, after, name.as_str());
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
});
Some((Some(after), edit, None))
}
}
})
.flatten();
SwatchPaletteOutput { response: shown.output, edit }
let (picked, edit, pick_color) = settled.unwrap_or((None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked }
}
}
+35
View File
@@ -1,6 +1,7 @@
//! Stories of `SwatchPalette`.
use super::SwatchPalette;
use craft_behavior::Mixed;
use craft_theme::Srgba;
use craft_ui::choice::SwatchSpacing;
use craft_ui::runtime::env::Label;
@@ -23,10 +24,44 @@ const PALETTE: [(&str, Srgba); 12] = [
("Grey", Srgba::rgb(0.53, 0.55, 0.57)),
];
/// The recent colours of the Other… story.
const RECENT: [Srgba; 3] = [Srgba::rgb(0.10, 0.20, 0.30), Srgba::rgb(0.98, 0.80, 0.70), Srgba::rgb(0.40, 0.10, 0.50)];
fn named(entries: impl IntoIterator<Item = (String, Srgba)>) -> Vec<(Label, Srgba)> {
entries.into_iter().map(|(name, color)| (Label::from(name), color)).collect()
}
/// The twelve colours, the Other… cell after them and a row of recent colours; the readout shows the last request
/// for the host's picker.
#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)]
fn swatch_palette_other_and_recent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
let shown = SwatchPalette::new("Swatches", data.bind("color", PALETTE[8].1), &swatches)
.other("custom", "Other colour…")
.recent("Recent colours", &RECENT)
.show(ui);
let last = data.note("request", String::new());
if let Some(request) = &shown.pick_color {
*last = format!("{} at {}", request.key, request.color.map_or_else(|| String::from("none"), Srgba::to_hex));
}
let readout = format!("Last request: {last}");
StoryOutput::from(shown).readout(readout)
}
/// A palette over no colour: no swatch is selected until a pick sets one; the readout shows the bound value.
#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)]
fn no_colour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
let shown = SwatchPalette::optional("Swatches", data.bind_mixed("color", Mixed::<Option<Srgba>>::Same(None)), &swatches).show(ui);
let bound = *data.value("color", Mixed::<Option<Srgba>>::Same(None));
let readout = match bound {
Mixed::Same(Some(color)) => format!("Colour: {}", color.to_hex()),
Mixed::Same(None) => String::from("Colour: none"),
Mixed::Mixed => String::from("Colour: mixed"),
};
StoryOutput::from(shown).readout(readout)
}
/// The palette of the twelve colours, set up by `options`, with the readout of its latest event.
fn shown_palette(ui: &mut Ui, data: &mut StoryData, options: impl for<'a> FnOnce(SwatchPalette<'a>) -> SwatchPalette<'a>) -> StoryOutput {
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
+126 -1
View File
@@ -4,7 +4,7 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_behavior::{EditEvent, Selection};
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,
@@ -322,6 +322,131 @@ fn the_palette_arrows_walk_the_wrapped_grid() {
assert_eq!(rig.events.get(), 0);
}
/// What a palette reported over the passes since the last `take`.
#[derive(Default)]
struct PaletteReports {
edits: Vec<EditEvent<Srgba>>,
requests: Vec<ColorRequest>,
picked: Vec<Srgba>,
}
type Reports = Rc<RefCell<PaletteReports>>;
/// Collects what one pass of a palette reported.
fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
let mut reports = reports.borrow_mut();
reports.edits.extend(shown.edit);
reports.requests.extend(shown.pick_color);
reports.picked.extend(shown.picked);
}
fn palette_swatches() -> Vec<(Label, Srgba)> {
SWATCHES.iter().map(|(name, [r, g, b])| (Label::from(*name), Srgba::rgb(*r, *g, *b))).collect()
}
/// The colour of `SWATCHES` named `name`.
fn swatch(name: &str) -> Srgba {
SWATCHES.iter().find(|(n, _)| *n == name).map(|(_, [r, g, b])| Srgba::rgb(*r, *g, *b)).unwrap_or_else(|| panic!("no swatch {name}"))
}
const RECENT: [Srgba; 1] = [Srgba::rgb(0.40, 0.10, 0.50)];
/// Activating the Other… cell files a request keyed by the host's key at the bound colour and sets nothing; a pick in
/// the recent row is one `Set` of its colour; a click on the swatch of the bound colour reports `picked` and no edit.
#[trial]
fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
let swatches = palette_swatches();
let green = swatch("Green");
let bound = Rc::new(Cell::new(green));
let reports = Reports::default();
let (c, r) = (bound.clone(), reports.clone());
let mut fixture = Fixture::new(move |ui| {
let mut current = c.get();
let shown = SwatchPalette::new("Swatches", Bind::bound(&mut current), &swatches)
.other("custom", "Other colour…")
.recent("Recent colours", &RECENT)
.show(ui);
c.set(current);
collect(&r, shown);
});
fixture.room(PALETTE_WIDE).settle();
let other = fixture.by_label("Other colour…").expect("the Other… cell is named by its label");
let palette = fixture.by_label("Swatches").expect("the palette's list box");
assert!(palette.rect.contains_rect(other.rect), "the Other… cell is a cell of the palette's table: {other:?} in {palette:?}");
fixture.click(&other).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(taken.requests.len(), 1, "one request for one activation");
assert_eq!(taken.requests[0].key, "custom", "the request carries the host's key");
assert_eq!(taken.requests[0].color.map(Srgba::to_rgba), Some(green.to_rgba()), "the picker opens at the bound colour");
assert!(taken.edits.is_empty() && taken.picked.is_empty(), "the Other… cell sets nothing");
assert_eq!(bound.get().to_rgba(), green.to_rgba(), "the bound colour stays");
let recent = fixture.by_label(&RECENT[0].to_hex()).expect("a recent colour is named by its hex");
fixture.click(&recent).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert!(taken.requests.is_empty(), "a recent pick files no request");
assert_eq!(taken.edits.len(), 1, "one edit for one recent pick");
assert!(
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Same(before), after, .. }
if before.to_rgba() == green.to_rgba() && after.to_rgba() == RECENT[0].to_rgba()),
"a Set from the bound colour to the recent one: {:?}",
taken.edits[0]
);
assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written");
let violet = fixture.by_label("Violet").expect("violet");
fixture.click(&violet).settle();
let _ = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba());
// Past the double-click time, so the repeat is a single click of its own.
fixture.advance(1.0);
let violet = fixture.by_label("Violet").expect("violet");
fixture.click(&violet).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert!(taken.edits.is_empty(), "a click on the bound colour changes nothing: {:?}", taken.edits);
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
}
/// 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]
fn an_optional_palette_bound_to_no_colour_selects_nothing_and_a_pick_writes_a_colour() {
let swatches = palette_swatches();
let bound = Rc::new(Cell::new(Mixed::<Option<Srgba>>::Same(None)));
let reports = Reports::default();
let (c, r) = (bound.clone(), reports.clone());
let mut fixture = Fixture::new(move |ui| {
let mut current = c.get();
let shown = SwatchPalette::optional("Swatches", Bind::bound_mixed(&mut current), &swatches).show(ui);
let _ = craft_ui::buttons::Button::new("After").show(ui);
c.set(current);
collect(&r, shown);
});
fixture.room(PALETTE_WIDE).settle();
for (name, _) in SWATCHES {
let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the {name} cell"));
assert_ne!(fixture.tree().selected_of(cell.node), Some(true), "no colour selects no swatch, {name} is selected");
}
fixture.key(Key::Tab, Modifiers::NONE);
let tree = fixture.tree();
assert_eq!(tree.name_of(craft_ui::testing::access::focused_key(tree)), Some("Red"), "Tab enters on the first swatch");
let blue = fixture.by_label("Blue").expect("blue");
fixture.click(&blue).settle();
let written = bound.get();
assert!(matches!(written, Mixed::Same(Some(color)) if color.to_rgba() == swatch("Blue").to_rgba()), "the pick is written: {written:?}");
let taken = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(taken.edits.len(), 1, "one edit for one pick");
assert!(
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Mixed, after, .. } if after.to_rgba() == swatch("Blue").to_rgba()),
"a Set from no colour, reported as from Mixed: {:?}",
taken.edits[0]
);
let blue = fixture.by_label("Blue").expect("blue");
assert_eq!(fixture.tree().selected_of(blue.node), Some(true), "the written colour's swatch is selected");
}
/// The Swatches panel over two groups, collecting the edits it reports and never applying them.
fn swatches_rig(groups: Vec<SwatchGroup>, state: SwatchesState) -> (Fixture, Rc<RefCell<Vec<SwatchEdit>>>) {
let edits = Rc::new(RefCell::new(Vec::new()));
+10
View File
@@ -71,6 +71,16 @@ const CLOSED: &[&str] = &[
"LineBreakOptions", // built field by field in WordCraft's paragraph dialog, a record of check boxes that mirrors the format
"AsianTypography", // built field by field in WordCraft's paragraph dialog, a record of check boxes that mirrors the format
"GapEdge", // the start and the end of a column gap: two edges, fixed by meaning, matched in WordCraft's column ruler
"StrokePlace", // inside, centred on or outside an edge: three places, fixed by meaning
"PagerStep", // back or next: two steps, fixed by meaning, matched in craft-pages, craft-print and PdfCraft
"PanePager", // built in craft-pages, craft-print and PdfCraft's print and printer-marks dialogs
"PageRevision", // built in PdfCraft's ui-egui, which keys its page pictures by the document and page revision
"GoTo", // built in PdfCraft's ui-egui (link and zoom navigation) and craft-pages' tests, one per target kind
"NotePopupMessage", // built in PdfCraft's ui-egui, one literal per message of a note's thread
"DialogLayout", // built in PdfCraft's ui-egui, which sets the dialogs' layout environment value
"RunWord", // built in PdfCraft's ui-egui, one literal per word of an OCR result
"ScanEvent", // matched in PdfCraft's ui-egui, whose scan tab answers each event
"FolderListing", // built in PdfCraft's ui-egui and craft-ui-shell's tests, one listing per pinned folder
"ToastEnd", // built or matched in craft-ui-widgets
"TrackLook", // built or matched in craft-ui-widgets
"VariantParts", // built or matched in craft-ui-widgets
+50 -3
View File
@@ -5,10 +5,10 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use craft_host::{FileError, FileFilter, Files, PickId, PickRequest, Picked};
use craft_host::{FileError, FileFilter, Files, PickId, PickRequest, Picked, WriteIntent};
use craft_platform::watch::FileWatch;
use crate::save::{SaveDocument, SaveFlow, SaveStep, SaveTarget};
use crate::save::{SaveDocument, SaveFlow, SaveStep, SaveTarget, save_dialog_folder};
/// Records every request; the test answers tickets by hand.
#[derive(Default)]
@@ -55,7 +55,7 @@ impl Files for ScriptedFiles {
Err(FileError::Unsupported)
}
fn write(&self, _path: &Path, _bytes: &[u8]) -> Result<(), FileError> {
fn write(&self, _path: &Path, _bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
Err(FileError::Unsupported)
}
@@ -196,3 +196,50 @@ fn a_late_write_does_not_free_another_save() {
flow.written(&mut watch, 8, Path::new("/x/b.pdf"));
assert!(!flow.is_busy());
}
// An email attachment's temporary copy (Outlook's cache, Apple Mail's downloads) is no place to
// keep work: Save asks where, as for a new document, and the picker does not start in that folder.
// The paths need not exist: the mail check comes before any look at the disk.
#[trial]
fn mail_attachment_copies_always_ask_where_to_save() {
let (files, watch, mut flow) = (ScriptedFiles::default(), watch(), SaveFlow::new());
for copy in [
r"C:\Users\me\AppData\Local\Microsoft\Windows\INetCache\Content.Outlook\AB12CD34\Quote.pdf",
"/Users/me/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/6F1C2A9E/booking.pdf",
] {
assert_eq!(flow.start(&files, &watch, document(Some(Path::new(copy)), "Quote.pdf"), SaveTarget::InPlace), SaveStep::Picking, "{copy}");
assert_eq!(files.last_request().directory, None, "{copy}");
assert_eq!(flow.cancel(&files), Some(SaveStep::Cancelled { key: 7 }));
}
let ordinary = Path::new("/home/me/Documents/Quote.pdf");
assert_eq!(
flow.start(&files, &watch, document(Some(ordinary), "Quote.pdf"), SaveTarget::InPlace),
SaveStep::Write { key: 7, path: ordinary.to_path_buf(), target: SaveTarget::InPlace, file_type: None }
);
}
// Save As starts in the folder of the document's own file; a new document, a bare name, the root
// and a mail attachment's copy give the picker no folder.
#[trial]
fn the_save_picker_opens_in_the_documents_own_folder() {
let (files, watch, mut flow) = (ScriptedFiles::default(), watch(), SaveFlow::new());
let mut folder_of = |path: Option<&str>| {
assert_eq!(flow.start(&files, &watch, document(path.map(Path::new), "f.pdf"), SaveTarget::As), SaveStep::Picking);
let folder = files.last_request().directory;
flow.cancel(&files);
assert_eq!(folder, save_dialog_folder(path.map(Path::new)), "the picker starts where save_dialog_folder says");
folder
};
assert_eq!(folder_of(Some("/home/a/plans/f.pdf")), Some(PathBuf::from("/home/a/plans")));
assert_eq!(folder_of(None), None);
assert_eq!(folder_of(Some("f.pdf")), None);
assert_eq!(folder_of(Some("/")), None);
assert_eq!(folder_of(Some(r"C:\Users\a\AppData\Local\Microsoft\Windows\INetCache\Content.Outlook\AB12\f.pdf")), None);
assert_eq!(folder_of(Some("/Users/a/Library/Containers/com.apple.mail/Data/Library/Mail Downloads/UUID/f.pdf")), None);
// Network shares follow the Windows rules for `Path::parent`, which only apply on Windows.
#[cfg(windows)]
{
assert_eq!(folder_of(Some(r"\\server\share\plans\f.pdf")), Some(PathBuf::from(r"\\server\share\plans")));
assert_eq!(folder_of(Some(r"\\server\share\")), None);
}
}
+132 -11
View File
@@ -22,7 +22,7 @@ use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use craft_host::{FileError, FileFilter, Files, PendingPick, PickAnswer, PickId, PickRequest, Wake};
use craft_host::{FileError, FileFilter, Files, PendingPick, PickAnswer, PickId, PickRequest, Wake, WriteIntent};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
#[cfg(feature = "ui")]
@@ -294,6 +294,8 @@ struct Inner {
pending: HashMap<PickId, Pending>,
answered: VecDeque<PickAnswer>,
last_folder: HashMap<String, PathBuf>,
/// The answers `Files::answer_next` gave, which the panels answer the next requests with.
forced: VecDeque<Answer>,
}
impl Inner {
@@ -308,7 +310,13 @@ impl FileService {
// pc: apps/photocraft/src/services.rs:203 show_file_dialog; crates/ui-egui/src/file_dialog.rs:310 poll_file_dialog
pub fn new(wake: Wake) -> (Self, FilePanels) {
probe::start();
let inner = Arc::new(Mutex::new(Inner { next: 0, pending: HashMap::new(), answered: VecDeque::new(), last_folder: HashMap::new() }));
let inner = Arc::new(Mutex::new(Inner {
next: 0,
pending: HashMap::new(),
answered: VecDeque::new(),
last_folder: HashMap::new(),
forced: VecDeque::new(),
}));
let (to_panels, requests) = std::sync::mpsc::channel();
let panels = FilePanels {
inner: inner.clone(),
@@ -398,7 +406,12 @@ impl FilePanels {
/// the answer becomes a [`PickAnswer`].
// pc: crates/ui-egui/src/file_dialog.rs:310 poll_file_dialog, :349 finish_file_dialog, :365 saved_path
pub fn pump<W: HasWindowHandle + HasDisplayHandle>(&mut self, parent: Option<&W>) {
self.start_requests();
// Forced answers settle first, with no panel.
for (id, answer) in self.start_requests() {
if let Some(question) = self.finish(id, answer, false) {
self.dialogs.ask_message(self.replace_message(&question.settled), id);
}
}
self.cancel_forgotten();
// A replace question queued by `finish` shows in the same pass, so the loop runs until no
// answer is left to settle.
@@ -433,7 +446,11 @@ impl FilePanels {
self.collect_prompt_answers(dialogs);
self.collect_chooser_answers(dialogs);
while let Ok((id, request)) = self.requests.try_recv() {
if request.fallback {
if let Some(answer) = self.forced_answer(id) {
if let Some(question) = self.finish(id, answer, false) {
self.prompts.push(AskedPrompt { id, question, dialog: None });
}
} else if request.fallback {
self.choosers.push(AskedChooser { id, request, cause: None, dialog: None });
} else {
self.ask_panel(id, &request);
@@ -576,11 +593,28 @@ impl FilePanels {
}
}
/// Drains the requests the service queued into the native panels' queue.
fn start_requests(&mut self) {
/// Drains the requests the service queued into the native panels' queue. A request that finds
/// a forced answer waiting takes it instead of a panel; those answers are returned for the
/// caller to settle.
fn start_requests(&mut self) -> Vec<(PickId, Answer)> {
let mut forced = Vec::new();
while let Ok((id, request)) = self.requests.try_recv() {
self.ask_panel(id, &request);
match self.forced_answer(id) {
Some(answer) => forced.push((id, answer)),
None => self.ask_panel(id, &request),
}
}
forced
}
/// The oldest answer [`Files::answer_next`] gave, taken for pick `id`. A ticket forgotten
/// before it got here takes none, which leaves the answer for the next request.
fn forced_answer(&self, id: PickId) -> Option<Answer> {
let mut inner = lock(&self.inner);
if !inner.pending.contains_key(&id) {
return None;
}
inner.forced.pop_front()
}
/// Queues the native panel of pick `id`.
@@ -675,7 +709,8 @@ impl FilePanels {
/// cause. A Save that needs the replace
/// question stays pending and returns the question for the caller to ask. The answer of a
/// forgotten pick is dropped. `from_panel` says a native panel answered, not the fallback
/// chooser, whose Cancel is always the user's.
/// chooser, whose Cancel is always the user's, nor a forced answer ([`Files::answer_next`]),
/// whose Cancel is the caller's.
fn finish(&mut self, id: PickId, answer: Answer, from_panel: bool) -> Option<ReplaceQuestion> {
let Pending { request, forgotten, awaiting_replace, bytes } = lock(&self.inner).pending.remove(&id)?;
if forgotten {
@@ -697,7 +732,20 @@ impl FilePanels {
Picked::Saved { path: settled, file_type: filter }
}
(Answer::Paths(paths), _) if paths.is_empty() => Picked::Cancelled,
(Answer::Paths(paths), _) => Picked::Paths(paths),
(Answer::Paths(mut paths), _) => {
if request.kind == PickKind::Save && paths.len() == 1 {
let path = paths.remove(0);
let settled = Self::settled_save_path(self.extension_policy, &path, &request, None);
if self.replace_guard == ReplaceGuard::AskWhenUnasked && Self::replaces_unasked(&path, &settled) {
let question = ReplaceQuestion { answered: path, settled, file_type: None };
lock(&self.inner).pending.insert(id, Pending { request, forgotten: false, awaiting_replace: Some(question.clone()), bytes });
return Some(question);
}
Picked::Paths(vec![settled])
} else {
Picked::Paths(paths)
}
}
(Answer::Unavailable(why), _) => Picked::Unavailable(why),
// A panel that answers nothing on a system without a dialog backend did not get
// cancelled; the probe knows why.
@@ -794,8 +842,14 @@ impl Files for FileService {
std::fs::read(path).map_err(|e| file_error(e, path))
}
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
write_file(path, bytes)
// A desktop app has no host page: every intent writes the path, and no page took the bytes.
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
write_file(path, bytes)?;
Ok(false)
}
fn exists(&self, path: &Path) -> bool {
path.exists()
}
/// Queues a Save pick, then writes `bytes` to the settled path and answers `Saved` or
@@ -815,6 +869,22 @@ impl Files for FileService {
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
self.inner.lock().unwrap_or_else(|e| e.into_inner()).last_folder.get(purpose).cloned()
}
/// Answers the next pick with `picked` instead of showing a panel, through the settling a native answer passes.
/// `Picked::Contents`, `Failed` and `Downloaded` have no `Answer` form: they are `Err(FileError::Unsupported)`.
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
let answer = match picked {
Picked::Paths(paths) => Answer::Paths(paths),
Picked::Saved { path, .. } => Answer::Saved { path, filter: None },
Picked::Cancelled => Answer::Cancelled,
Picked::Unavailable(why) => Answer::Unavailable(why),
// A native service reads paths; it has no file contents to hand over, and a write's
// outcome is its own to report.
Picked::Contents(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(FileError::Unsupported),
};
lock(&self.inner).forced.push_back(answer);
Ok(())
}
}
#[cfg(test)]
@@ -918,6 +988,40 @@ pub(crate) mod service_tests {
assert_eq!(saved_as(&service, &mut panels, add_only), path("/x/Photo.png"));
}
// A forced answer answers the next pick with no panel, through the same settling: the folder
// is remembered and a Save gets the extension policy. The pick after it reaches the panel, and
// a forced cancel stays a cancel on a system without a dialog backend.
#[trial]
fn a_forced_answer_answers_the_next_pick_without_a_panel() {
let (service, mut panels, log) = service_with(vec![]);
let dir = PathBuf::from("/x/forced");
assert_eq!(service.answer_next(Picked::Paths(vec![dir.join("a.pdf")])), Ok(()));
let forced = service.pick(PickRequest::open("document"));
panels.pump(NONE);
assert_eq!(answered(&service, forced), Picked::Paths(vec![dir.join("a.pdf")]));
assert!(log.borrow().is_empty(), "no request reached a panel");
assert!(service.pending_pick().is_none());
assert_eq!(service.last_folder("document"), Some(dir.clone()));
let shown = service.pick(PickRequest::open("document"));
panels.pump(NONE);
assert_eq!(log.borrow().len(), 1, "the next pick reaches the panel");
assert_eq!(answered(&service, shown), Picked::Cancelled);
assert_eq!(service.answer_next(Picked::Paths(vec![dir.join("Report")])), Ok(()));
let saved = service.pick(PickRequest::save("export").suggested_extension("pdf"));
panels.pump(NONE);
assert_eq!(answered(&service, saved), Picked::Paths(vec![dir.join("Report.pdf")]), "the extension policy completes it");
assert_eq!(log.borrow().len(), 1);
panels.backend_problem = || Some("no dialog backend".into());
assert_eq!(service.answer_next(Picked::Cancelled), Ok(()));
let cancelled = service.pick(PickRequest::open("document"));
panels.pump(NONE);
assert_eq!(answered(&service, cancelled), Picked::Cancelled);
assert_eq!(service.answer_next(Picked::Contents(vec![])), Err(FileError::Unsupported));
}
// The panel asked about the file it answered; the extension change can name another existing
// file, and that one is asked about here. Cancel ends the pick; an answer the panel already
// asked about is not asked again.
@@ -1141,4 +1245,21 @@ pub(crate) mod service_tests {
assert_eq!(answered(&service, id), Picked::Cancelled);
let _ = std::fs::remove_dir_all(&dir);
}
// `FileService::exists` checks the real file system, so batch writers on desktop see files already on disk.
#[trial]
fn exists_checks_the_file_system() {
let dir = std::env::temp_dir().join(format!("craft-dialogs-exists-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch dir");
let present = dir.join("present.pdf");
let missing = dir.join("missing.pdf");
let _ = std::fs::remove_file(&present);
let _ = std::fs::remove_file(&missing);
let (service, _panels) = FileService::new(Wake::none());
assert!(!service.exists(&present));
assert_eq!(service.write(&present, b"data", WriteIntent::SaveAs), Ok(false));
assert!(service.exists(&present));
assert!(!service.exists(&missing));
let _ = std::fs::remove_dir_all(&dir);
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
//! The path field and the picker ticket it keeps, against a file service that records its requests.
use craft_dialogs::ui::PathField;
use craft_host::{AppInfo, FileError, Files, Host, PickAnswer, PickId, PickRequest, Picked};
use craft_host::{AppInfo, FileError, Files, Host, PickAnswer, PickId, PickRequest, Picked, WriteIntent};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
use std::cell::{Cell, RefCell};
@@ -55,7 +55,7 @@ impl Files for StubFiles {
Err(FileError::Unsupported)
}
fn write(&self, _path: &Path, _bytes: &[u8]) -> Result<(), FileError> {
fn write(&self, _path: &Path, _bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
Err(FileError::Unsupported)
}
+58 -1
View File
@@ -1,6 +1,6 @@
//! `craft_docpath::names`.
use crate::names::{CopyNumbering, MAX_NAME_BYTES, safe_file_name, unique_file_name};
use crate::names::{CopyNumbering, MAX_NAME_BYTES, is_plain_file_name, safe_file_name, safe_file_stem, unique_file_name};
// Reserved and control characters become `_`, bidi controls go, trailing dots and spaces go,
// "NUL.txt" becomes "_NUL.txt", a 300-byte name is cut to 200 bytes on a char boundary keeping
@@ -19,6 +19,63 @@ fn user_text_becomes_a_safe_file_name() {
assert!(safe_file_name(&"a".repeat(300), "x").len() == MAX_NAME_BYTES);
}
// ".." leaves nothing; ".PDF" goes in any case; a path stays one name; a 900-byte CJK stem is cut
// to 198 bytes, the last whole character under the limit.
#[test]
fn user_text_becomes_a_safe_file_stem() {
assert_eq!(safe_file_stem("..", "pdf"), "");
assert_eq!(safe_file_stem("Report.PDF", "pdf"), "Report");
assert_eq!(safe_file_stem("Report.pdf.txt", "pdf"), "Report.pdf.txt");
assert_eq!(safe_file_stem("../../etc/passwd", "pdf"), ".._.._etc_passwd");
let long = safe_file_stem(&"文".repeat(300), "pdf");
assert!(long.len() <= MAX_NAME_BYTES && long.chars().all(|c| c == '文'), "{}", long.len());
assert_eq!(long.len(), 198);
}
// Device names, in any case, with any extension and with the superscript digits, get a `_`;
// longer names that start like one do not.
#[test]
fn windows_device_names_get_a_prefix() {
for name in ["NUL.tar.gz", "con.txt", "COM1.exe", "LPT9.txt", "COM¹.txt", "LPT³.pdf", "lpt9.tar", "nul"] {
assert_eq!(safe_file_name(name, "x"), format!("_{name}"));
assert_eq!(safe_file_stem(name, "zip"), format!("_{name}"));
}
assert_eq!(safe_file_stem("COM1.pdf", "pdf"), "_COM1");
assert_eq!(safe_file_stem("LPT³.pdf", "pdf"), "_LPT³");
for name in ["COM10", "Console", "COM10.txt", "LPT.txt"] {
assert_eq!(safe_file_name(name, "x"), name);
assert_eq!(safe_file_stem(name, "pdf"), name);
}
}
// Right-to-left scripts, joiners and double extensions are left alone; a name with nothing usable
// gives the fallback; a safe name is already safe.
#[test]
fn ordinary_names_pass_unchanged_and_making_safe_is_stable() {
for name in ["report.pdf", "archive.tar.gz", "مرحبا.pdf", "שלום.txt", "資料.pdf", "می\u{200c}روم.txt", "👩\u{200d}💻.png"] {
assert_eq!(safe_file_name(name, "attachment"), name);
}
for name in ["", " ", ".", "..", " . . ", "\u{202e}"] {
assert_eq!(safe_file_name(name, "attachment"), "attachment", "{name:?}");
}
let long = format!("{}.pdf", "é".repeat(150));
for name in ["invoice\u{202e}fdp.exe", "../a.pdf", "NUL.txt", " . . ", "report.pdf . ", "資料.pdf", "a\tb/c", long.as_str()] {
let once = safe_file_name(name, "attachment");
assert_eq!(safe_file_name(&once, "attachment"), once, "{name:?}");
}
}
// A plain name sits directly in its folder: no separator, no drive, no trailing dot or space.
#[test]
fn plain_file_names_stay_directly_in_the_folder() {
for good in ["report.pdf", "report", ".hidden", "a b.pdf", "資料.pdf"] {
assert!(is_plain_file_name(good), "{good}");
}
for bad in ["", "report.", "report.pdf.", "report.pdf ", "report. . ", " ", "...", ". ", "..", "C:x.pdf", "sub\\x.pdf", "sub/x.pdf"] {
assert!(!is_plain_file_name(bad), "{bad:?}");
}
}
// "a.txt", "a 2.txt" taken: Space gives "a 3.txt", Parenthesized "a (2).txt" when only "a.txt"
// is taken; "photo (2).jpg" counts on to "photo (3).jpg"; a name with no extension numbers its end.
#[test]
+65 -16
View File
@@ -2,7 +2,7 @@
//! the canvas's arena; the perspective grid shows while the quad can be committed.
use craft_behavior::geometry::{Homography, screen_step};
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
use craft_behavior::{
CanvasView, CursorIcon, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PaintedCursor, PartKey, PartRef, PointerButton, PressPhase,
Roving, Sense,
@@ -119,6 +119,9 @@ struct Report {
/// - Shift on a corner drag keeps the axis the pointer moved less along; Alt on a corner of an upright quad moves the
/// neighbouring corners too, so it stays a rectangle.
/// - With a `shield` the document outside a valid quad is dimmed, under the grid.
/// - With `bounds` a drag or an arrow key stops each corner it moves at the bounds' edge; a whole-quad move stops when
/// its farthest corner reaches the edge, so the quad keeps its shape. The shield then dims the bounds outside the
/// quad.
/// - The corners stay where the user puts them: a quad wound counter-clockwise (a box flipped on one axis) applies
/// mirrored, a box turned half way round applies upside down.
/// - A quad that is not convex draws in the invalid colour without the grid and cannot be committed.
@@ -140,13 +143,17 @@ pub struct PerspectiveCropQuad<'a> {
/// The shield painted over the document outside a valid quad; `None` paints none.
#[prop]
shield: Option<CropShield>,
/// The rectangle every corner stays inside while dragged or moved by keys, in document units; the shield covers it
/// outside the quad. `None` leaves the corners unbounded and shields the whole document.
#[prop]
bounds: Option<DocRect>,
report: Report,
}
impl<'a> PerspectiveCropQuad<'a> {
/// A quad named `label` over `quad`, in document units.
pub fn new(label: impl Into<Label>, quad: Bind<'a, PerspectiveQuad>) -> Self {
PerspectiveCropQuad { common: Common::new(), quad, show_grid: true, shield: None, report: Report::default() }.label(label)
PerspectiveCropQuad { common: Common::new(), quad, show_grid: true, shield: None, bounds: None, report: Report::default() }.label(label)
}
}
@@ -234,6 +241,43 @@ fn dragged(drag: &Drag, to: Point, mods: Mods) -> [Point; 4] {
}
}
/// The quad `after` that `grab` made of `before`, kept inside `bounds`.
///
/// - A corner grab clamps each coordinate it moved. A coordinate nothing moved stays as it lies, even outside the
/// bounds: that corner is the caller's. So a click with no drag changes nothing, and Alt's neighbours, clamped from
/// the same coordinate as the corner, keep the rectangle.
/// - A move shifts the whole quad back by the overshoot of its farthest corner on each axis, so it keeps its shape.
/// - Nothing is pushed further out than `before` lay: the allowed range on each axis takes in what `before` covered.
fn clamped(before: &[Point; 4], after: [Point; 4], grab: Grab, bounds: Option<DocRect>) -> [Point; 4] {
let Some(b) = bounds.map(|b| b.abs()) else { return after };
match grab {
Grab::Corner { .. } => {
// `max` then `min` rather than `f64::clamp`, which panics on reversed or NaN limits.
let keep = |was: f64, to: f64, lo: f64, hi: f64| to.max(lo.min(was)).min(hi.max(was));
std::array::from_fn(|i| Point::new(keep(before[i].x, after[i].x, b.x0, b.x1), keep(before[i].y, after[i].y, b.y0, b.y1)))
}
Grab::Move => {
let span = |q: &[Point; 4], axis: fn(&Point) -> f64| {
q.iter().map(axis).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)))
};
let x = kept_in(span(before, |p| p.x), span(&after, |p| p.x), b.x0, b.x1);
let y = kept_in(span(before, |p| p.y), span(&after, |p| p.y), b.y0, b.y1);
after.map(|p| p + DocVec::new(x, y))
}
}
}
/// The shift along one axis that brings the span `after` (min, max) inside `lo..hi`, widened to the span `before`
/// covered: the max side is pulled back first, then the min side while the span fits.
fn kept_in(before: (f64, f64), after: (f64, f64), lo: f64, hi: f64) -> f64 {
let (lo, hi) = (lo.min(before.0), hi.max(before.1));
let mut shift = (hi - after.1).min(0.0);
if after.1 - after.0 <= hi - lo {
shift += (lo - (after.0 + shift)).max(0.0);
}
shift
}
impl PerspectiveCropQuad<'_> {
/// Starts the drag of the part pressed at screen point `origin`.
fn begin(cx: &mut Cx<'_, Self>, view: &CanvasView, quad: [Point; 4], corner: Option<usize>, origin: Pos2) -> Drag {
@@ -246,9 +290,9 @@ impl PerspectiveCropQuad<'_> {
Drag { grab, at_press: quad, from }
}
/// Follows the pointer at screen point `pos`.
fn step(cx: &mut Cx<'_, Self>, view: &CanvasView, drag: &Drag, pos: Pos2, mods: Mods) {
let next = dragged(drag, view.to_doc(pos), mods);
/// Follows the pointer at screen point `pos`, inside `bounds`.
fn step(cx: &mut Cx<'_, Self>, view: &CanvasView, drag: &Drag, pos: Pos2, mods: Mods, bounds: Option<DocRect>) {
let next = clamped(&drag.at_press, dragged(drag, view.to_doc(pos), mods), drag.grab, bounds);
if finite(&next) {
cx.propose(Some(next));
}
@@ -266,15 +310,18 @@ impl PerspectiveCropQuad<'_> {
let Some((direction, mods)) = cx.intents().take_nudge() else { return };
let distance = if mods.shift { NUDGE_FAR } else { NUDGE };
let by = screen_step(view, DocVec::new(f64::from(direction.x), f64::from(direction.y)) * distance);
let next = match corner {
let (next, grab) = match corner {
Some(index) => {
let index = index as usize;
let mut moved = quad;
moved[index as usize] += by;
moved
moved[index] += by;
(moved, Grab::Corner { index, offset: DocVec::ZERO })
}
None => quad.map(|p| p + by),
None => (quad.map(|p| p + by), Grab::Move),
};
if finite(&next) {
let next = clamped(&quad, next, grab, self.bounds);
// A nudge into the bounds' edge leaves the quad as it is and sets nothing.
if finite(&next) && next != quad {
cx.set(Some(next));
}
}
@@ -336,6 +383,7 @@ impl Component for PerspectiveCropQuad<'_> {
let space = space_of(&cx.env, cx.rect);
let Some(quad) = shown(cx.value()) else { return };
let view = space.view;
let bounds = self.bounds;
let mut live = cx.memory::<Live>().clone();
let grabs = std::iter::once((PartRef::from(INSIDE), None)).chain((0..CORNERS).map(|at| (CORNER.at(at), Some(at as usize))));
for (part, corner) in grabs {
@@ -346,12 +394,12 @@ impl Component for PerspectiveCropQuad<'_> {
match press.phase {
PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => {
let drag = Self::begin(cx, &view, quad, corner, start.origin);
Self::step(cx, &view, &drag, pos, mods);
Self::step(cx, &view, &drag, pos, mods, bounds);
live.drag = Some(drag);
}
PressPhase::Drag { pos, .. } => {
if let Some(drag) = live.drag {
Self::step(cx, &view, &drag, pos, mods);
Self::step(cx, &view, &drag, pos, mods, bounds);
}
}
PressPhase::Release { start, pos, click: false, .. } => {
@@ -362,7 +410,7 @@ impl Component for PerspectiveCropQuad<'_> {
None => None,
};
if let Some(drag) = drag {
Self::step(cx, &view, &drag, pos, mods);
Self::step(cx, &view, &drag, pos, mods, bounds);
cx.commit();
}
}
@@ -383,10 +431,11 @@ impl Component for PerspectiveCropQuad<'_> {
let style = &cx.style;
let draw = ui.draw();
let screen: Vec<Pos2> = quad.iter().map(|p| view.to_screen(*p)).collect();
// The shield dims the document outside a quad that can be committed, before the grid.
// The shield dims the bounds, or the whole document, outside a quad that can be committed, before the grid.
if valid && let (Some(shield), Some(document)) = (&self.shield, space.document()) {
let (w, h) = (document.width, document.height);
let canvas = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| view.to_screen(p));
let area = self.bounds.unwrap_or_else(|| DocRect::new(0.0, 0.0, document.width, document.height));
let canvas = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]
.map(|p| view.to_screen(p));
if let Some(fill) = shield.fill_on(&space, style.canvas.egui(), self.report.dragging) {
paint_outside(&draw, canvas, &screen, DataColor::new(fill));
}
@@ -4,7 +4,7 @@
use super::super::{PerspectiveCropTool, PerspectiveInput};
use super::{CORNER, PerspectiveCropQuad, PerspectiveQuad};
use craft_behavior::CanvasView;
use craft_behavior::kurbo::{BezPath, Point};
use craft_behavior::kurbo::{BezPath, Point, Rect as DocRect};
use craft_ui::canvas::{CropShield, RasterSource as _};
use craft_ui::contract::{Show as _, Validity};
use craft_ui::runtime::env::Message;
@@ -16,6 +16,8 @@ use egui::{Color32, Ui};
const PAGE: [Point; 4] = [Point::new(250.0, 110.0), Point::new(430.0, 130.0), Point::new(400.0, 290.0), Point::new(220.0, 250.0)];
/// The same corners with the last one pulled in: the quad is not convex.
const BENT: [Point; 4] = [Point::new(250.0, 110.0), Point::new(430.0, 130.0), Point::new(400.0, 290.0), Point::new(380.0, 150.0)];
/// A frame a little larger than the page, inside the larger document: the corners of a bounded quad stay in it.
const FRAME: DocRect = DocRect::new(200.0, 90.0, 450.0, 310.0);
/// The story document with the page the quad is marked on, as the camera saw it: blue with a dark grey edge.
fn paper() -> StoryPicture<impl Fn(Point) -> Color32> {
@@ -44,6 +46,21 @@ fn skewed_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
})
}
/// The page's quad kept inside a frame around the page: a corner dragged past the frame stops at its edge, and the
/// shield dims the frame outside the quad.
#[story(PerspectiveCropQuad<'static>, covers = [], drive = Drive::Drag(Grip::part(CORNER.at(0))))]
fn bounded_quad(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let (quad, quad_at) = data.value_at("quad", Some(PAGE));
on_canvas(ui, |ui, at| {
PerspectiveCropQuad::new("Perspective crop", quad_at.bind(&mut *quad))
.show_grid(false)
.shield(CropShield::PERSPECTIVE)
.bounds(FRAME)
.show_at(ui, at)
.edit
})
}
#[story(PerspectiveCropQuad<'static>, covers = [Invalid], drive = Drive::Drag(Grip::part(CORNER.at(0))))]
fn bent_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let (quad, quad_at) = data.value_at("quad", Some(BENT));
+15 -5
View File
@@ -11,7 +11,7 @@ use craft_behavior::geometry::{CropBox, SnapLine, crop_view};
use craft_behavior::kurbo::Size;
use craft_behavior::{CancelReason, CanvasView, EditEvent};
use craft_keymap::{Chord, Key, Mods};
use craft_ui::canvas::{CanvasTool, CropOverlay, CropOverlayOutput, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::canvas::{CanvasTool, CropApply, CropOverlay, CropOverlayOutput, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::patterns::form_dialogs::{Param, ParamDialog, ParamKind};
use craft_ui::primitives::Draw;
@@ -46,12 +46,15 @@ pub struct CropCommit {
pub delete_pixels: bool,
/// What fills the area beyond the canvas.
pub fill: CropFill,
/// What the overlay applied for (Enter, a double click, a click away), so the app can let the selection go on
/// a click away; `None` for the check mark, Image > Crop and leaving the tool.
pub cause: Option<CropApply>,
}
impl CropCommit {
/// The commit of `frame` with `settings` on `document`, with the environment's `units`.
/// The commit of `frame` with `settings` on `document`, with the environment's `units`; it has no `cause`.
pub fn new(frame: CropBox, settings: &CropSettings, document: &CropDocument, units: &Units) -> Self {
Self { frame, target: settings.target(document, units), delete_pixels: settings.delete_pixels, fill: settings.fill }
Self { frame, target: settings.target(document, units), delete_pixels: settings.delete_pixels, fill: settings.fill, cause: None }
}
/// The size the document has after the crop: the target's, else the frame's.
@@ -337,7 +340,9 @@ impl CropTool {
self.straightened(angle, fit, input.document, &mut out.events);
}
}
if apply && let Some(event) = self.apply(input.settings, input.document, units) {
if let Some(cause) = apply
&& let Some(event) = self.apply_for(Some(cause), input.settings, input.document, units)
{
out.events.push(event);
}
if discard && let Some(event) = self.discard() {
@@ -477,13 +482,18 @@ impl CropTool {
/// The check mark in the bar, Enter or Image > Crop: [`CropEvent::Apply`] for a drawn frame or the
/// untouched selection frame, `None` for another default frame or no frame.
pub fn apply(&mut self, settings: &CropSettings, document: &CropDocument, units: &Units) -> Option<CropEvent> {
self.apply_for(None, settings, document, units)
}
/// [`CropTool::apply`] for what the overlay reported: the commit carries `cause`.
fn apply_for(&mut self, cause: Option<CropApply>, settings: &CropSettings, document: &CropDocument, units: &Units) -> Option<CropEvent> {
if !self.session.applies() {
return None;
}
let frame = self.session.frame()?;
self.end_nudges();
let view = self.seen_view.filter(|_| settings.image_mode());
let commit = CropCommit::new(frame, settings, document, units);
let commit = CropCommit { cause, ..CropCommit::new(frame, settings, document, units) };
self.kept = Some((self.session.keep(view, commit.size()), false));
Some(CropEvent::Apply(commit))
}
+121 -27
View File
@@ -35,6 +35,10 @@ pub const BOX: PartKey = PartKey::new("box");
/// outside.
const OUTSIDE: PartKey = PartKey::new("outside");
/// The round rotate handle of [`RotateZone::Knob`], `KNOB.at(0)`: it stands for the outside, so a drag on it turns the
/// box as a drag outside does.
const KNOB: PartKey = PartKey::new("knob");
/// The pointer-only part of an edge: the band along the whole side, outside it, beside the midpoint handle `BOX.at(Edge(k))` that the keyboard
/// and the focus ring use. One part key carries one shape, so the side cannot reuse the handle's key.
const EDGE: PartKey = PartKey::new("edge");
@@ -114,6 +118,9 @@ pub enum RotateZone {
Outside,
/// Only the band outside a corner (PhotoCraft's Move tool controls); the rest of the outside is the tool's.
Band,
/// A round handle on a stem above the box's top side, or below its bottom side when the canvas has no room above.
/// It rotates like the outside under the grab pointer (grabbing while it turns), and no outside region is declared.
Knob,
/// Only within `points` screen points of the box's sides (PhotoCraft's type box with ⌘ held). The whole outside is
/// still the box's: a press further out starts nothing and applies nothing, and reaches neither the content under
/// the box nor the tool, and the pointer there is the arrow.
@@ -138,7 +145,7 @@ impl RotateZone {
fn rotates_at(self, quad: &[Point; 4], pointer: Pos2) -> bool {
match self {
RotateZone::Border { points } => border_distance(quad, pointer) <= points,
RotateZone::Outside | RotateZone::Band => true,
RotateZone::Outside | RotateZone::Band | RotateZone::Knob => true,
// The handle is the zone's only outside part, so a press that reaches the outside is on it.
RotateZone::Handle => true,
}
@@ -274,6 +281,7 @@ craft_ui::words! {
bottom_edge: "transform.bottomEdge" = "Bottom edge";
left_edge: "transform.leftEdge" = "Left edge";
pivot: "transform.pivot" = "Reference point";
rotate_knob: "transform.rotateKnob" = "Rotate";
readout_angle: "transform.readoutAngle" = "Angle:";
readout_width: "transform.readoutWidth" = "W:";
readout_height: "transform.readoutHeight" = "H:";
@@ -349,6 +357,7 @@ pub enum ApplyBy {
#[derive(Clone, Debug, Default)]
struct Report {
apply: Option<ApplyBy>,
clicked: Option<(BoxPart, Point)>,
discard: bool,
hovered: Option<BoxPart>,
picked: Option<BoxPart>,
@@ -480,6 +489,9 @@ pub struct TransformBox<'a> {
/// Ellipse tool's. It takes no press: a press there is the inside's, or the tool's.
#[prop]
centre_mark: bool,
/// Whether the corner and side handles are circles (a rounded document editor's look) instead of squares.
#[prop]
round_handles: bool,
/// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends
/// take a press and the keys, each as the box handle it points to ([`LineLook`]), so an end drag scales the box as
/// that handle does; while it is dragged, the box shows as it scales. No other part is declared.
@@ -521,6 +533,7 @@ impl<'a> TransformBox<'a> {
overflow: false,
session_arrows: true,
centre_mark: false,
round_handles: false,
line: None,
reach: TransformReach::Box,
color: None,
@@ -572,6 +585,12 @@ impl<'a> TransformBox<'a> {
self.move_only().filter(|&points| points > 0.0 && self.rules.allows(BoxPart::Inside))
}
/// Whether the box declares, draws and names a rotate knob: the knob zone on a box drawn as a box, where the rules
/// let it turn.
fn has_knob(&self) -> bool {
matches!(self.rotate_zone, RotateZone::Knob) && self.line.is_none() && self.move_only().is_none() && self.rules.allows(BoxPart::Outside)
}
/// The parts the keyboard walks, in order. A box whose inside does not move has no inside part, so a press or drag
/// over its body reaches what lies beneath (a type editor under a paragraph frame). A box that offers only its
/// move reach or only a display has none.
@@ -684,6 +703,10 @@ impl<'a> TransformBox<'a> {
let turn = || Cursor::from(PaintedCursor::turn(quad::bisector(screen, corner)));
let along = |from: usize| vec2_of(screen.quad[(from + 1) % 4] - screen.quad[from % 4]);
match (kind, part) {
// The knob is a handle the pointer takes hold of and swings, not a stretch of the outside.
(BoxDrag::Rotate, BoxPart::Outside) if self.rotate_zone == RotateZone::Knob => {
if dragging { CursorIcon::Grabbing } else { CursorIcon::Grab }.into()
}
// The rotate handle turns the cursor with the box: it points in across the side the handle stands on.
(BoxDrag::Rotate, BoxPart::Outside) if self.rotate_zone == RotateZone::Handle => {
Cursor::from(PaintedCursor::turn(-outward_normals(&screen.quad.map(pos))[0]))
@@ -756,8 +779,8 @@ impl<'a> TransformBox<'a> {
}
/// The parts that take a press, with the box part each stands for. Mirrors what [`parts`](Component::parts)
/// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside or the
/// rotate handle; or only the move strips; or none for a shown box.
/// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside, the knob in
/// [`RotateZone::Knob`] or the rotate handle; or only the move strips; or none for a shown box.
fn pointer_parts(&self) -> Vec<(PartRef, BoxPart)> {
if !self.takes_input() {
return Vec::new();
@@ -779,8 +802,14 @@ impl<'a> TransformBox<'a> {
if self.declares_centre() {
parts.push((CENTRE.at(0), BoxPart::Inside));
}
parts.extend((0..4).map(|corner| (OUTSIDE.at(corner), BoxPart::Outside)));
parts.push((ROTATE_HANDLE.at(0), BoxPart::Outside));
if matches!(self.rotate_zone, RotateZone::Knob) {
if self.has_knob() {
parts.push((KNOB.at(0), BoxPart::Outside));
}
} else {
parts.extend((0..4).map(|corner| (OUTSIDE.at(corner), BoxPart::Outside)));
parts.push((ROTATE_HANDLE.at(0), BoxPart::Outside));
}
parts
}
@@ -808,9 +837,10 @@ impl<'a> TransformBox<'a> {
PressPhase::Down { start, .. } if part == BoxPart::Outside && !self.rotate_zone.rotates_at(&screen.quad, start.origin) => {}
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
let from = space.view.to_doc(start.origin);
// The move reach only moves: an Alt press there is a move too. The rotate handle is a handle, so
// an Alt press on it rotates.
let away_from_handles = part == BoxPart::Inside || (part == BoxPart::Outside && self.rotate_zone != RotateZone::Handle);
// The move reach only moves: an Alt press there is a move too. The knob and the rotate handle are
// handles, so an Alt press on one turns the box rather than moving the reference point onto it.
let knob = reference.key == KNOB;
let away_from_handles = part == BoxPart::Inside || (part == BoxPart::Outside && self.rotate_zone != RotateZone::Handle && !knob);
let moves_pivot = acting.alt && self.move_only().is_none() && away_from_handles;
let follows = follows_in_slop(part);
let (part, begin) = if moves_pivot { (BoxPart::Pivot, BoxState::new(shown.quad, from)) } else { (part, *shown) };
@@ -851,6 +881,14 @@ impl<'a> TransformBox<'a> {
self.report.apply = Some(ApplyBy::DoubleClick);
}
let Some(grip) = held.take() else { continue };
if click
&& start.button == PointerButton::Primary
&& grip.part != BoxPart::Outside
&& !grip.moves_pivot
&& self.move_only().is_none()
{
self.report.clicked = Some((grip.part, grip.from));
}
if grip.began && click && grip.last == grip.pressed {
// A click that ended where it began moved nothing: no step.
cx.cancel(CancelReason::Unchanged);
@@ -976,12 +1014,21 @@ impl<'a> TransformBox<'a> {
}
impl TransformBox<'_> {
/// The shape of a handle of `side` at `at`: a square, or a circle of that diameter with round handles.
fn handle_shape(&self, at: Pos2, side: f32) -> PaintShape {
if self.round_handles {
PaintShape::Circle(at, side / 2.0)
} else {
PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO)
}
}
/// The square of handle `part` at `at` on the screen, filled as the part's state shows when the rules let it take a
/// press; `enlarged` with the overflow plus.
fn paint_handle(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, part: BoxPart, at: Pos2, enlarged: bool) {
let look = &cx.style.handle;
let side = if enlarged { look.side * OVERFLOW_IN_HANDLES } else { look.side };
self.paint_square(draw, cx, at, side, self.rules.allows(part).then(|| BOX.at(part.index())));
self.paint_handle_shape(draw, cx, self.handle_shape(at, side), self.rules.allows(part).then(|| BOX.at(part.index())));
if enlarged {
Handle::plus(draw, look, at, side);
}
@@ -995,22 +1042,22 @@ impl TransformBox<'_> {
let corners = outline.map(|corner| view.to_screen(corner));
paint_frame(draw, style, self.ink(style.line), corners);
for k in 0..4 {
self.paint_square(draw, cx, corners[k].lerp(corners[(k + 1) % 4], 0.5), style.handle.side, None);
let middle = corners[k].lerp(corners[(k + 1) % 4], 0.5);
self.paint_handle_shape(draw, cx, self.handle_shape(middle, style.handle.side), None);
}
}
for (part, end) in line.end_parts() {
self.paint_handle(draw, cx, part, view.to_screen(end), false);
}
for (end, at) in line.free_ends() {
self.paint_square(draw, cx, view.to_screen(at), style.handle.side, Some(LINE_END.at(end.index())));
self.paint_handle_shape(draw, cx, self.handle_shape(view.to_screen(at), style.handle.side), Some(LINE_END.at(end.index())));
}
paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget, None);
}
/// A handle square of `side` centred on `at`, filled as the state of `part` shows, or at rest without one.
fn paint_square(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, at: Pos2, side: f32, part: Option<PartRef>) {
/// A handle's `square` (a circle with round handles), filled as the state of `part` shows, or at rest without one.
fn paint_handle_shape(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, square: PaintShape, part: Option<PartRef>) {
let look = &cx.style.handle;
let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO);
let fill = match part {
Some(part) => cx.resolve_part(part, &look.fill),
None => cx.resolve(&look.fill),
@@ -1090,6 +1137,19 @@ fn outward_normals(quad: &[Pos2; 4]) -> [Vec2; 4] {
})
}
/// The rotate knob of the box whose corners are `quad` on the screen, in the canvas body `within`: the knob and the foot
/// of its stem. The knob stands `rotate_reach` out from the middle of the top side, along the side's outward normal so a
/// turned box's knob turns with it; where that point is outside `within`, it stands out from the bottom side instead.
fn knob_at(quad: &[Pos2; 4], within: Rect, style: &TransformBoxStyle) -> (Pos2, Pos2) {
let outward = outward_normals(quad);
let off = |side: usize| {
let foot = quad[side].lerp(quad[(side + 1) % 4], 0.5);
(foot + outward[side] * style.rotate_reach, foot)
};
let top = off(0);
if within.contains(top.0) { top } else { off(2) }
}
/// The reference point's glyph centred at `centre`: a circle crossed by two arms, over its halo. The one glyph of the
/// reference point and of the centre mark; `line` is the colour over the halo.
fn paint_centre_glyph(draw: &Draw<'_>, centre: Pos2, style: &TransformBoxStyle, line: StrokeColor) {
@@ -1175,7 +1235,7 @@ impl Component for TransformBox<'_> {
}
/// The whole box, the corners, the edges and the reference point the rules allow, in keyboard order, then each
/// side as a pointer-only band outside it, each corner's stretch of the two bands beside it, the centre and the move
/// side as a pointer-only band outside it (either side of its line with the rules' edge band), each corner's stretch of the two bands beside it, the centre and the move
/// strips where declared, and the outside. A handle, a corner's stretch, the reference point and the centre rank
/// alike, so the nearest wins where they overlap on a small box;
/// they rank above a side, which ranks above the inside, which ranks above the outside. Every part takes a press's
@@ -1236,7 +1296,9 @@ impl Component for TransformBox<'_> {
}
for k in (0..4u8).filter(|&k| self.rules.allows(BoxPart::Edge(k))) {
let side = usize::from(k);
cx.part(EDGE.at(u64::from(k)), side_band(&quad, side, style.side_band))
let band =
if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) };
cx.part(EDGE.at(u64::from(k)), band)
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)))
.priority(HitPriority::new(HitLevel::Handle, EDGE_SUB))
.pointer_only(EDGE_BY_KEY);
@@ -1263,7 +1325,7 @@ impl Component for TransformBox<'_> {
cx.roving(Roving::new(NavShape::Flat).page(Some(1)));
}
match self.rotate_zone {
RotateZone::Outside | RotateZone::Border { .. } => {
RotateZone::Outside | RotateZone::Border { .. } if self.rules.allows(BoxPart::Outside) => {
for (corner, region) in outside_regions(&quad, rect).into_iter().enumerate() {
cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(region))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
@@ -1279,7 +1341,17 @@ impl Component for TransformBox<'_> {
.pointer_only(ROTATE_BY_KEY);
}
}
RotateZone::Band => {}
RotateZone::Outside | RotateZone::Border { .. } | RotateZone::Band => {}
// The knob alone turns the box; the rest of the outside is the tool's.
RotateZone::Knob => {
if self.has_knob() {
let (knob, _) = knob_at(&quad, rect, style);
cx.part(KNOB.at(0), HitShape::circle(knob, style.handle_reach))
.sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside))
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(ROTATE_BY_KEY);
}
}
RotateZone::Handle if self.rules.allows(BoxPart::Outside) => {
let (_, knob) = rotate_handle(&quad, style.rotate_stem);
cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach))
@@ -1332,12 +1404,17 @@ impl Component for TransformBox<'_> {
let centre = screen.quad.iter().fold(Vec2::ZERO, |sum, corner| sum + pos(*corner).to_vec2()) / 4.0;
paint_centre_glyph(&draw, centre.to_pos2(), style, self.ink(style.line));
}
for i in 0..4u8 {
for part in [BoxPart::Corner(i), BoxPart::Edge(i)] {
let Some(at) = handle_point(&screen, part) else { continue };
let enlarged = self.overflow && part == BoxPart::Corner(2);
self.paint_handle(&draw, cx, part, pos(at), enlarged);
}
// A handle the handle set hides is not drawn; one the mode refuses still draws, dimmed by
// `paint_handle`.
for part in (0..4u8).flat_map(|i| [BoxPart::Corner(i), BoxPart::Edge(i)]).filter(|part| self.rules.shows(*part)) {
let Some(at) = handle_point(&screen, part) else { continue };
let enlarged = self.overflow && part == BoxPart::Corner(2);
self.paint_handle(&draw, cx, part, pos(at), enlarged);
}
if self.has_knob() {
let (knob, foot) = knob_at(&screen.quad.map(pos), cx.rect, style);
draw.stroke(&PaintShape::Path(vec![foot, knob]), StrokeWidth::Thin, style.line);
paint_widget(&draw, knob, &style.widget, self.color);
}
}
}
@@ -1347,7 +1424,7 @@ impl Component for TransformBox<'_> {
}
/// One node per part: the whole box, the corners, the edges and the reference point, each described by its point
/// in the canvas's units.
/// in the canvas's units, and the rotate knob where the box has one.
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let (Some(space), Some(state)) = (canvas_space(&cx.env), cx.value()) else { return };
let words = cx.words::<TransformBoxWords>();
@@ -1361,11 +1438,15 @@ impl Component for TransformBox<'_> {
node.description = Some(format!("{}, {}", across_x.format_value(&units, at.x, zero_x), across_y.format_value(&units, at.y, zero_y)));
}
}
// The knob is pointer-only, so it is not among the keyboard parts; its node names it for assistive tools.
if self.has_knob() {
access.node(KNOB.at(0), Role::BUTTON).name = Name::Text(words.rotate_knob.as_str().to_owned());
}
}
fn finish(self, cx: Cx<'_, Self>) -> TransformBoxOutput {
let Report { apply, discard, hovered, picked, held, snapped, line_end } = self.report;
TransformBoxOutput { edit: cx.edit_response(), apply, discard, picked, hovered, held, snapped, line_end }
let Report { apply, clicked, discard, hovered, picked, held, snapped, line_end } = self.report;
TransformBoxOutput { edit: cx.edit_response(), apply, discard, picked, hovered, held, snapped, clicked, line_end }
}
}
@@ -1373,6 +1454,8 @@ impl Component for TransformBox<'_> {
#[derive(Debug)]
#[non_exhaustive]
pub struct TransformBoxOutput {
/// The part and press point in document units of a primary click on the box or a grip, including a release within click slop.
pub clicked: Option<(BoxPart, Point)>,
/// A drag (`Begin` on the first move, `Update`, `Commit` on the release; Escape cancels it) or an arrow key's
/// `Set`.
pub edit: EditResponse<BoxState>,
@@ -1517,6 +1600,17 @@ fn side_band(quad: &[Pos2; 4], side: usize, width: f32) -> HitShape {
}
}
/// The grab band of side `side` of the box `quad` by [`BoxRules::edge_band`]: `reach` out from the line and past each
/// end, and as far in, but no more than a quarter of the way to the opposite side. A side with no length is its line.
fn edge_band(quad: &[Pos2; 4], side: usize, reach: f32) -> HitShape {
let (a, b) = (quad[side], quad[(side + 1) % 4]);
let Some(out) = outward(quad, side) else { return HitShape::segment(a, b) };
let along = (b - a).normalized() * reach;
let across = (quad[(side + 2) % 4] - b).length();
let (inner, outer) = (out * -reach.min(across / 4.0).max(SIDE_LINE_INSIDE), out * reach);
HitShape::Polygon(vec![a - along + inner, b + along + inner, b + along + outer, a - along + outer])
}
/// The stretch of side `side`'s band next to its end `corner`: a quarter of the side, at most `width` along it, as far
/// out as the band. `None` for a side with no length.
fn corner_reach(quad: &[Pos2; 4], side: usize, corner: usize, width: f32) -> Option<HitShape> {
@@ -1,10 +1,11 @@
//! Stories of the transform box: Free Transform with its reference point, the Move tool's controls, Distort, the
//! Ellipse tool's centre mark, the rotate handle and the Line tool's live-line controls, with box or free ends.
//! Ellipse tool's centre mark, the rotate handle and the Line tool's live-line controls, with box or free ends, the
//! corner-only and side-only handle sets, sides grabbed along an edge band, and the rotate knob.
use super::{BOX, LINE_END, LineEnd, LineEnds, LineLook, ROTATE_HANDLE, RotateZone, TransformBox, TransformBoxOutput, TransformReach};
use super::{BOX, EDGE, LINE_END, LineEnd, LineEnds, LineLook, ROTATE_HANDLE, RotateZone, TransformBox, TransformBoxOutput, TransformReach};
use craft_behavior::GesturePhase;
use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, TransformMode};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::geometry::quad::{BoxHandles, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
use craft_ui::buttons::Button;
use craft_ui::canvas::Canvas;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _, clicked};
@@ -32,14 +33,30 @@ fn free_box(state: Bind<'_, BoxState>) -> TransformBox<'_> {
/// Shows the box `make` builds over the story's box as the only canvas control of a canvas.
fn on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> StoryOutput {
shown_on_canvas(ui, data, make).map(|output| StoryOutput::from(output.edit)).unwrap_or_default()
show_on_canvas(ui, data, false, make)
}
/// [`on_canvas`] with the box's whole output.
fn shown_on_canvas(ui: &mut Ui, data: &mut StoryData, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> Option<TransformBoxOutput> {
/// [`on_canvas`], the view centred on the picture; `at_top` scrolls it so the picture's top side lies on the
/// canvas's top edge.
fn show_on_canvas(ui: &mut Ui, data: &mut StoryData, at_top: bool, make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>) -> StoryOutput {
shown_on_canvas(ui, data, at_top, make).map(|output| StoryOutput::from(output.edit)).unwrap_or_default()
}
/// [`show_on_canvas`] with the box's whole output.
fn shown_on_canvas(
ui: &mut Ui,
data: &mut StoryData,
at_top: bool,
make: impl for<'a> Fn(Bind<'a, BoxState>) -> TransformBox<'a>,
) -> Option<TransformBoxOutput> {
let (state, state_at) = data.value_at("box", BoxState::from_rect(PICTURE));
let room = craft_ui::testing::stage(ui);
let view = craft_ui::testing::canvas_story::story_view(room, ui.pixels_per_point(), PICTURE.center(), 100.0);
let ppp = ui.pixels_per_point();
let mut view = craft_ui::testing::canvas_story::story_view(room, ppp, PICTURE.center(), 100.0);
if at_top {
let top = view.to_doc(room.center_top());
view = craft_ui::testing::canvas_story::story_view(room, ppp, PICTURE.center() + DocVec::new(0.0, PICTURE.y0 - top.y), 100.0);
}
let layer = layer();
let shown = Canvas::new("Document").view(view).show_at(ui, room, |ui, body| {
show_document(ui, body.rect, &StoryDocument::STANDARD);
@@ -54,6 +71,12 @@ fn free_transform(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).reference_point(true))
}
/// Proportional corners follow the axis with the larger relative change.
#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(BOX.at(BoxPart::Corner(2).index())).toward(vec2(1.0, 0.5))))]
fn larger_axis_scale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).rules(BoxRules::default().with_scale(ScaleRule::LargerAxis)))
}
#[story(TransformBox<'static>, covers = [Default])]
fn move_tool_controls(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false))
@@ -64,6 +87,38 @@ fn distort(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).rules(BoxRules::in_mode(TransformMode::Distort)))
}
/// A box with handles at its corners only: a picture that scales from its corners.
#[story(TransformBox<'static>, covers = [Default])]
fn corners_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).rules(BoxRules::default().with_handles(BoxHandles::Corners)))
}
/// A box with handles on its right and left sides only: a paragraph frame that changes only its width.
#[story(TransformBox<'static>, covers = [Default])]
fn sides_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).rules(BoxRules::default().with_handles(BoxHandles::Sides)))
}
/// A paragraph frame whose right and left sides are grabbed anywhere along their length within 8 points either side of
/// the line (`BoxRules::edge_band`), not only at their handles; the middle of the frame is the tool's.
#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(EDGE.at(1)).toward(vec2(1.0, 0.0))))]
fn sides_edge_band(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rules = BoxRules::default().with_scale(ScaleRule::Free).with_aspect_linked(false).with_handles(BoxHandles::Sides).with_edge_band(8.0);
on_canvas(ui, data, |state| free_box(state).rules(rules).inside_moves(false).reference_point(false))
}
/// A box that turns by a round knob on a stem above its top side; the rest of the outside is the tool's.
#[story(TransformBox<'static>, covers = [Default])]
fn rotate_knob(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, |state| free_box(state).rotate_zone(RotateZone::Knob).reference_point(false))
}
/// The knob of a box at the canvas's top edge, with no room above: it stands below the bottom side.
#[story(TransformBox<'static>, covers = [Default])]
fn rotate_knob_at_top(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
show_on_canvas(ui, data, true, |state| free_box(state).rotate_zone(RotateZone::Knob).reference_point(false))
}
/// The box of an upright paragraph frame: free sides, no rotation, no reference point.
#[story(TransformBox<'static>, covers = [Default])]
fn text_frame(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
@@ -131,8 +186,9 @@ fn line_free_ends(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let quad = BoxState::from_rect(PICTURE).quad;
let ends = *data.value("ends", [quad[3], quad[1]]);
let line = LineLook::new(ends[0], ends[1]).ends(LineEnds::Free);
let shown =
shown_on_canvas(ui, data, move |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false).line(line));
let shown = shown_on_canvas(ui, data, false, move |state| {
free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false).line(line)
});
let Some(output) = shown else { return StoryOutput::default() };
if let Some(drag) = output.line_end {
let index = usize::from(drag.end == LineEnd::To);
+2 -2
View File
@@ -364,7 +364,7 @@ impl Harness {
fn press_at(&mut self, at: Pos2) {
self.fixture.frame(vec![pointer::moved(at)]);
self.fixture.frame(vec![pointer::press(at)]);
self.fixture.frame_held(vec![pointer::press(at)]);
}
fn move_to(&mut self, at: Pos2) {
@@ -372,7 +372,7 @@ impl Harness {
}
fn release_at(&mut self, at: Pos2) {
self.fixture.frame(vec![pointer::release(at)]);
self.fixture.frame_held(vec![pointer::release(at)]);
self.fixture.frame(Vec::new());
}
+117 -19
View File
@@ -6,10 +6,12 @@ use std::rc::Rc;
use craft_behavior::CanvasView;
use craft_behavior::geometry::Constraint;
use craft_behavior::kurbo::{Point, Size};
use craft_draw::ui::crop::{CropDocKey, PerspectiveCropEvent, PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid};
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
use craft_draw::ui::crop::{
CropDocKey, PerspectiveCropEvent, PerspectiveCropQuad, PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid,
};
use craft_ui::canvas::{Canvas, ToolHost, tool_pass};
use craft_ui::contract::ShowContainer as _;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::runtime::access::Role;
use craft_ui::testing::{Fixture, trial};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2};
@@ -18,6 +20,35 @@ const SIZE: Size = Size::new(400.0, 300.0);
const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE };
const ALT: Modifiers = Modifiers { alt: true, ..Modifiers::NONE };
const BOTH: Modifiers = Modifiers { shift: true, alt: true, ..Modifiers::NONE };
/// The bounds of the bounded quad, around the upright quad of the trials.
const BOUNDS: DocRect = DocRect::new(60.0, 50.0, 340.0, 240.0);
/// The screen point of document point `(x, y)` on the fixture's canvas: the view shows (200, 150) at its centre.
fn screen(fixture: &Fixture, x: f64, y: f64) -> Pos2 {
let canvas = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas");
canvas.center() + Vec2::new(x as f32 - 200.0, y as f32 - 150.0)
}
fn button(fixture: &mut Fixture, at: Pos2, pressed: bool, modifiers: Modifiers) {
fixture.hold(modifiers);
fixture.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }]);
}
/// A drag in document points over four moves; the last move and the release hold `last`, the others `first`.
fn drag_on(fixture: &mut Fixture, from: (f64, f64), to: (f64, f64), first: Modifiers, last: Modifiers) {
let (from, to) = (screen(fixture, from.0, from.1), screen(fixture, to.0, to.1));
fixture.hold(first);
fixture.frame(vec![Event::PointerMoved(from)]);
button(fixture, from, true, first);
for step in 1..=4 {
let mods = if step == 4 { last } else { first };
fixture.hold(mods);
fixture.frame(vec![Event::PointerMoved(from + (to - from) * (step as f32 / 4.0))]);
}
button(fixture, to, false, last);
fixture.hold(Modifiers::NONE);
fixture.frame(Vec::new());
}
/// The tool on a canvas showing its quad, driven by pointer events.
struct Rig {
@@ -55,29 +86,16 @@ impl Rig {
/// The screen point of document point `(x, y)`: the view shows (200, 150) at the canvas's centre.
fn at(&self, x: f64, y: f64) -> Pos2 {
let canvas = self.fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas");
canvas.center() + Vec2::new(x as f32 - 200.0, y as f32 - 150.0)
screen(&self.fixture, x, y)
}
fn button(&mut self, at: Pos2, pressed: bool, modifiers: Modifiers) {
self.fixture.hold(modifiers);
self.fixture.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }]);
button(&mut self.fixture, at, pressed, modifiers);
}
/// A drag over four moves; the last move and the release hold `last`, the others `first`.
fn drag_with(&mut self, from: (f64, f64), to: (f64, f64), first: Modifiers, last: Modifiers) {
let (from, to) = (self.at(from.0, from.1), self.at(to.0, to.1));
self.fixture.hold(first);
self.fixture.frame(vec![Event::PointerMoved(from)]);
self.button(from, true, first);
for step in 1..=4 {
let mods = if step == 4 { last } else { first };
self.fixture.hold(mods);
self.fixture.frame(vec![Event::PointerMoved(from + (to - from) * (step as f32 / 4.0))]);
}
self.button(to, false, last);
self.fixture.hold(Modifiers::NONE);
self.fixture.frame(Vec::new());
drag_on(&mut self.fixture, from, to, first, last);
}
fn drag(&mut self, from: (f64, f64), to: (f64, f64), mods: Modifiers) {
@@ -136,6 +154,36 @@ fn rectangle((a, b): (Point, Point)) -> [(f64, f64); 4] {
[(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
}
/// The quad alone on a canvas, kept inside [`BOUNDS`], starting at `start`; and its value.
fn bounded(start: [Point; 4]) -> (Fixture, Rc<RefCell<Option<[Point; 4]>>>) {
let quad = Rc::new(RefCell::new(Some(start)));
let shown = Rc::clone(&quad);
let mut fixture = Fixture::new(move |ui| {
let room = ui.available_rect_before_wrap();
let view = CanvasView::new(room, Point::new(200.0, 150.0), 1.0);
let _ = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| {
let mut quad = shown.borrow_mut();
let _ = PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)).bounds(BOUNDS).show_at(ui, body.rect);
});
});
fixture.settle();
(fixture, quad)
}
fn inside(q: &[Point; 4]) -> bool {
q.iter().all(|p| p.x >= BOUNDS.x0 - 1e-6 && p.x <= BOUNDS.x1 + 1e-6 && p.y >= BOUNDS.y0 - 1e-6 && p.y <= BOUNDS.y1 + 1e-6)
}
/// Whether `b` is `a` moved without a change of shape.
fn same_shape(a: &[Point; 4], b: &[Point; 4]) -> bool {
let by = b[0] - a[0];
a.iter().zip(b).all(|(p, q)| ((*q - *p) - by).hypot() < 1e-6)
}
fn on_right_edge(x: f64) -> bool {
(x - BOUNDS.x1).abs() < 1e-6
}
#[trial]
fn grid_lines_meet_at_the_quads_vanishing_points() {
let view = CanvasView::new(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(400.0, 300.0)), Point::new(200.0, 150.0), 1.0);
@@ -242,6 +290,56 @@ fn perspective_box_and_corner_modifiers_and_clicks() {
assert!(near(rig.quad(), upright), "a click moves nothing: {:?}", rig.quad());
}
#[trial]
fn a_bounded_quad_stays_inside_its_bounds_whatever_moves_it() {
let upright = [(100.0, 80.0), (300.0, 80.0), (300.0, 220.0), (100.0, 220.0)].map(|(x, y)| Point::new(x, y));
let (mut fixture, quad) = bounded(upright);
let value = |quad: &Rc<RefCell<Option<[Point; 4]>>>| quad.borrow().expect("a quad");
// An Alt corner drag past the bounds' corner: the corner and its moved neighbours stop at the edges.
drag_on(&mut fixture, (300.0, 220.0), (370.0, 270.0), ALT, ALT);
let q = value(&quad);
assert!(inside(&q), "an Alt corner drag stays inside: {q:?}");
assert!(on_right_edge(q[2].x) && (q[2].y - BOUNDS.y1).abs() < 1e-6, "the dragged corner stops at the edges: {q:?}");
assert!((q[1].x - q[2].x).abs() < 1e-6 && (q[3].y - q[2].y).abs() < 1e-6 && q[0] == upright[0], "Alt still keeps the rectangle: {q:?}");
// A whole-quad drag past the bounds keeps its shape: the farthest corner stops at the edge, the rest follow.
*quad.borrow_mut() = Some(upright);
fixture.frame(Vec::new());
drag_on(&mut fixture, (200.0, 150.0), (290.0, 180.0), Modifiers::NONE, Modifiers::NONE);
let moved = value(&quad);
assert!(inside(&moved) && same_shape(&upright, &moved), "a moved quad stays inside with its shape: {moved:?}");
assert!(on_right_edge(moved[1].x) && moved != upright, "the move stops at the edge: {moved:?}");
// The arrows on the whole quad: one step in, then a far step out stops at the edge.
fixture.key(Key::ArrowLeft, Modifiers::NONE);
fixture.frame(Vec::new());
let left = value(&quad);
assert!(left[1].x < moved[1].x && same_shape(&moved, &left), "an arrow moves the whole quad: {left:?}");
fixture.key(Key::ArrowRight, SHIFT);
fixture.frame(Vec::new());
let back = value(&quad);
assert!(inside(&back) && same_shape(&moved, &back) && on_right_edge(back[1].x), "a nudge out stops at the edge: {back:?}");
// The arrows on a picked corner: a press on it picks it, and a far nudge out stops it at the edge.
let corner = screen(&fixture, back[2].x, back[2].y);
fixture.frame(vec![Event::PointerMoved(corner)]);
button(&mut fixture, corner, true, Modifiers::NONE);
button(&mut fixture, corner, false, Modifiers::NONE);
fixture.frame(Vec::new());
assert_eq!(value(&quad), back, "a click on a corner moves nothing");
fixture.key(Key::ArrowLeft, SHIFT);
fixture.frame(Vec::new());
let pulled = value(&quad);
assert!(pulled[2].x < back[2].x && pulled[1] == back[1], "an arrow moves the picked corner alone: {pulled:?}");
for _ in 0..2 {
fixture.key(Key::ArrowRight, SHIFT);
fixture.frame(Vec::new());
}
let pushed = value(&quad);
assert!(inside(&pushed) && on_right_edge(pushed[2].x), "a corner nudged out stops at the edge: {pushed:?}");
}
#[trial]
fn a_session_starts_once_and_a_document_switch_discards_it() {
let mut rig = Rig::new();
+285 -3
View File
@@ -2,7 +2,7 @@
//! keys, the readout and the overlay's edits.
use super::presses::Presses;
use craft_behavior::geometry::quad::{BoxAllow, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::geometry::quad::{BoxAllow, BoxHandles, BoxPart, BoxRules, BoxState, ScaleRule, TransformMode};
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapSuspend, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{Affine, Point, Rect};
use craft_behavior::{CanvasView, EditEvent, GesturePhase, RulerUnits, Ticks};
@@ -51,12 +51,15 @@ struct Config {
snap: bool,
/// The box is `TransformBox::text_frame`; `rules`, `zone`, `inside_moves` and `reference_point` are then unused.
text_frame: bool,
/// Show the frame only while hovered or while its part owns the pointer.
hover_frame: bool,
overflow: bool,
/// The canvas's rulers on both axes.
rulers: Option<RulerText>,
/// The host keeps the box in f32, as a text layer keeps its box, and gives it back with its centre as the pivot.
f32_host: bool,
centre_mark: bool,
round_handles: bool,
line: Option<LineLook>,
/// Snap targets beside the guides at [`SNAP_XS`].
targets: Vec<SnapTarget>,
@@ -73,12 +76,14 @@ struct Config {
/// What the host keeps of the box and what the passes reported.
struct Host {
state: BoxState,
shown: Option<BoxState>,
before: Option<BoxState>,
events: Vec<Seen>,
applied: usize,
discarded: usize,
picked: Option<BoxPart>,
hovered: Option<BoxPart>,
clicks: Vec<(BoxPart, Point)>,
id: egui::Id,
view: CanvasView,
guide_events: usize,
@@ -108,10 +113,12 @@ fn defaults() -> Config {
guides: false,
snap: false,
text_frame: false,
hover_frame: false,
overflow: false,
rulers: None,
f32_host: false,
centre_mark: false,
round_handles: false,
line: None,
targets: Vec::new(),
suspend: SnapSuspend::Control,
@@ -134,12 +141,14 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
let kept_config = Rc::clone(&shown_config);
let host = Rc::new(RefCell::new(Host {
state,
shown: None,
before: None,
events: Vec::new(),
applied: 0,
discarded: 0,
picked: None,
hovered: None,
clicks: Vec::new(),
id: egui::Id::NULL,
view: CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0),
guide_events: 0,
@@ -186,6 +195,12 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
let output = Guides::new("Guides", canvas_id, Bind::bound(&mut guides)).interactive(true).show_at(ui, body.rect);
guide_edits = usize::from(!output.edit.events.is_empty());
}
let frame_id = egui::Id::unique("hover frame");
let frame_rect = egui::Rect::from_two_pos(view.to_screen(RECT.origin()), view.to_screen(Point::new(RECT.x1, RECT.y1))).expand(8.0);
let hovered = ui.ctx().pointer_hover_pos().is_some_and(|pos| frame_rect.contains(pos));
if config.hover_frame && !hovered && craft_ui::runtime::pointer::active_part(ui.ctx(), frame_id).is_none() {
return None;
}
let mut control = if config.text_frame {
TransformBox::text_frame("Free Transform", Bind::given(state), RECT).overflow(config.overflow)
} else {
@@ -195,6 +210,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
.inside_moves(config.inside_moves)
.reference_point(config.reference_point)
.centre_mark(config.centre_mark)
.round_handles(config.round_handles)
};
if let Some(mods) = config.mods {
control = control.mods(mods);
@@ -203,15 +219,20 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
control = control.line(line);
}
control = control.reach(config.reach).session_commit(config.session_commit);
(control.show_at(ui, body.rect), guide_edits)
if config.hover_frame {
control = control.id(frame_id);
}
Some((control.show_at(ui, body.rect), guide_edits))
});
if config.twice && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the frame runs twice");
}
if let Some((output, guide_edits)) = canvas.inner {
if let Some(Some((output, guide_edits))) = canvas.inner {
let mut host = shown_host.borrow_mut();
host.shown = output.edit.shown.as_ref().and_then(|value| value.same()).map(|value| **value);
host.guide_events += guide_edits;
absorb(&mut host, &output, config.f32_host);
host.clicks.extend(output.clicked);
}
});
fixture.settle();
@@ -367,6 +388,24 @@ fn drag(h: &mut Harness, from: Point, to: Point) {
frame(h, Vec::new());
}
/// A handle's accessible location follows the box in the same frame as its painted preview.
#[trial]
fn a_dragged_corner_reports_its_current_location() {
let mut h = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules());
let start = h.screen(Point::new(RECT.x1, RECT.y0));
let end = start + Vec2::new(-40.0, 20.0);
frame(&mut h, vec![pointer::moved(start)]);
frame(&mut h, vec![pointer::press(start)]);
frame(&mut h, vec![pointer::moved(end)]);
let first_move_passes = h.fixture.passes();
frame(&mut h, vec![pointer::moved(end + Vec2::new(-10.0, 5.0))]);
assert!(h.fixture.passes() <= first_move_passes, "a continued drag needs no extra pass");
let shown = h.host.borrow().shown.unwrap();
let painted_corner = h.screen(shown.quad[1]);
let accessible_corner = h.fixture.by_label("Top right corner").unwrap().rect.center();
assert!((accessible_corner - painted_corner).length() < 0.5, "accessible {accessible_corner:?}, painted {painted_corner:?}");
}
#[trial]
fn an_edge_takes_a_press_along_its_side_and_a_corner_wins_where_both_reach() {
let mut h = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules());
@@ -383,6 +422,33 @@ fn an_edge_takes_a_press_along_its_side_and_a_corner_wins_where_both_reach() {
assert!((quad[0].x - RECT.x0).abs() < 1e-6 && (quad[3].x - RECT.x0).abs() < 1e-6, "the far side stayed: {quad:?}");
}
#[trial]
fn an_edge_band_grabs_a_side_from_inside_the_box_along_its_whole_length() {
// A frame like a paragraph's: nothing inside moves it, so a press inside is the side's or nothing's.
let paragraph = |band: f32| {
harness(BoxState::from_rect(RECT), |config| {
config.rules = free_rules().with_edge_band(band);
config.inside_moves = false;
config.reference_point = false;
})
};
// The right edge runs from (300, 80) to (300, 220); 6 points inside it, away from its middle handle.
let inside = Point::new(294.0, 110.0);
let mut plain = paragraph(0.0);
hover(&mut plain, inside);
assert_ne!(plain.host.borrow().hovered, Some(BoxPart::Edge(1)), "without a band the side reaches outside only");
let mut h = paragraph(8.0);
hover(&mut h, inside);
assert_eq!(h.host.borrow().hovered, Some(BoxPart::Edge(1)), "within the band inside the box, the side");
hover(&mut h, Point::new(200.0, 110.0));
assert_eq!(h.host.borrow().hovered, None, "the middle of the box is past the band");
drag(&mut h, inside, Point::new(314.0, 110.0));
let quad = h.state().quad;
assert!((quad[1].x - 314.0).abs() < 1e-6 && (quad[2].x - 314.0).abs() < 1e-6, "the grab dragged the side as its handle: {quad:?}");
assert!((quad[0].x - RECT.x0).abs() < 1e-6, "the far side stayed: {quad:?}");
}
#[trial]
fn the_arrows_move_the_whole_box_after_a_handle_drag_leaves_focus_on_the_handle() {
let mut h = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules());
@@ -475,6 +541,40 @@ fn a_text_frame_fed_back_through_an_f32_host_follows_every_move_to_the_commit()
assert!((h.state().quad[2].y - 280.0).abs() < 0.01 && events.last() == Some(&Seen::Commit), "the commit holds the last move");
}
/// A hover-revealed frame remains declared through release after its drag leaves the original box.
#[trial]
fn a_hover_frame_commits_a_drag_released_outside() {
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.text_frame = true;
config.hover_frame = true;
});
let start = h.screen(Point::new(300.0, 150.0));
let end = start + by(120.0, 0.0);
frame(&mut h, vec![pointer::moved(start)]);
frame(&mut h, vec![pointer::press(start)]);
frame(&mut h, vec![pointer::moved(end)]);
frame(&mut h, vec![pointer::release(end)]);
frame(&mut h, Vec::new());
let events = &h.host.borrow().events;
assert!(events.contains(&Seen::Commit), "the host receives the release: {events:?}");
}
#[trial]
fn transform_box_shows_each_drag_proposal_in_the_same_frame() {
let mut h = upright();
let start = h.screen(Point::new(300.0, 220.0));
frame(&mut h, vec![pointer::moved(start)]);
frame(&mut h, vec![pointer::press(start)]);
let mut previous = h.state();
for delta in [Vec2::new(30.0, 21.0), Vec2::new(60.0, 42.0)] {
frame(&mut h, vec![pointer::moved(start + delta)]);
let host = h.host.borrow();
assert_ne!(host.state, previous, "the drag changed the box");
assert_eq!(host.shown, Some(host.state), "the reported preview follows this frame's edit");
previous = host.state;
}
}
/// A frame egui runs twice reports each move of a drag once: its second pass proposes the box the first did, and an
/// equal proposal reports no `Update` again, so a host that applies each `Update` (a text layer's box) applies it once
/// per move.
@@ -908,6 +1008,46 @@ fn a_click_on_the_box_moves_nothing_and_a_jittery_click_outside_applies_the_box_
assert_eq!(h.host.borrow().applied, 1, "the click outside applies");
}
#[trial]
fn inside_click_reports_press_point_but_drag_does_not() {
let mut h = upright();
let point = Point::new(150.0, 120.0);
let inside = h.screen(point);
frame(&mut h, vec![pointer::moved(inside)]);
frame(&mut h, vec![pointer::press(inside)]);
frame(&mut h, vec![pointer::release(inside)]);
assert_eq!(h.host.borrow().clicks, vec![(BoxPart::Inside, point)]);
frame(&mut h, vec![pointer::press(inside)]);
frame(&mut h, vec![pointer::moved(inside + by(40.0, 0.0))]);
frame(&mut h, vec![pointer::release(inside + by(40.0, 0.0))]);
assert_eq!(h.host.borrow().clicks, vec![(BoxPart::Inside, point)], "a drag reports no click");
let mut jitter = upright();
let at = jitter.screen(point);
let slop = craft_ui::testing::input::slop(jitter.fixture.ctx());
frame(&mut jitter, vec![pointer::moved(at)]);
frame(&mut jitter, vec![pointer::press(at)]);
frame(&mut jitter, vec![pointer::moved(at + by(slop / 3.0, 0.0))]);
frame(&mut jitter, vec![pointer::release(at + by(slop / 3.0, 0.0))]);
assert_eq!(jitter.host.borrow().clicks, vec![(BoxPart::Inside, point)], "a release within slop reports the press point");
}
#[trial]
fn a_grip_click_reports_its_press_point() {
let mut h = upright();
let point = Point::new(RECT.x0, RECT.y0);
let at = h.screen(point);
frame(&mut h, vec![pointer::moved(at)]);
frame(&mut h, vec![pointer::press(at)]);
frame(&mut h, vec![pointer::release(at)]);
assert_eq!(h.host.borrow().clicks, vec![(BoxPart::Corner(0), point)]);
let edge = Point::new((RECT.x0 + RECT.x1) / 2.0, RECT.y0);
let at = h.screen(edge);
frame(&mut h, vec![pointer::moved(at)]);
frame(&mut h, vec![pointer::press(at)]);
frame(&mut h, vec![pointer::release(at)]);
assert_eq!(h.host.borrow().clicks, vec![(BoxPart::Corner(0), point), (BoxPart::Edge(0), edge)]);
}
// A double click inside whose presses wobble within the slop and come back applies the box as it was: the wobble the
// box followed is cancelled, never committed as a move before the apply.
#[trial]
@@ -1273,12 +1413,14 @@ fn pad() -> (Fixture, Rc<RefCell<Pad>>) {
let state = BoxState::from_rect(RECT);
let host = Host {
state,
shown: None,
before: None,
events: Vec::new(),
applied: 0,
discarded: 0,
picked: None,
hovered: None,
clicks: Vec::new(),
id: egui::Id::NULL,
view: CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0),
guide_events: 0,
@@ -1357,3 +1499,143 @@ fn a_drags_escape_still_cancels_it_in_a_box_without_session_commit() {
assert_eq!(pad.host.state, BoxState::from_rect(RECT), "Escape put the box back");
assert!(pad.host.events.contains(&Seen::Cancel), "the drag was cancelled: {:?}", pad.host.events);
}
/// A box whose handle set shows only some handles takes no press, key or drag on the others: a sides-only box (a
/// paragraph frame's width) takes its right and left edges only, a corners-only box no edge.
#[trial]
fn a_sides_only_box_takes_presses_on_its_side_edges_only() {
// Rotation refused: no outside parts and no knob, so a press off the shown handles reaches nothing of the box.
let no_turn = || free_rules().with_allow(BoxAllow::new(false, true, true));
let sides = |config: &mut Config| {
config.rules = no_turn().with_handles(BoxHandles::Sides);
config.inside_moves = false;
config.reference_point = false;
};
// Just off the bottom right corner: within the corner's reach, outside both side bands that meet there.
let off_corner = Point::new(305.0, 225.0);
let mut all = harness(BoxState::from_rect(RECT), |config| {
sides(config);
config.rules = no_turn();
});
hover(&mut all, off_corner);
assert_eq!(all.host.borrow().hovered, Some(BoxPart::Corner(2)), "with every handle the corner takes the point");
let mut h = harness(BoxState::from_rect(RECT), sides);
hover(&mut h, off_corner);
assert_eq!(h.host.borrow().hovered, None, "a hidden corner takes no press");
drag(&mut h, off_corner, Point::new(325.0, 245.0));
assert_eq!(h.state(), BoxState::from_rect(RECT), "a drag from a hidden corner moves nothing");
assert!(h.host.borrow().events.is_empty(), "and starts no gesture: {:?}", h.host.borrow().events);
for hidden in [Point::new(200.0, 80.0), Point::new(200.0, 220.0)] {
hover(&mut h, hidden);
assert_eq!(h.host.borrow().hovered, None, "the hidden edge at {hidden:?} takes no press");
}
drag(&mut h, Point::new(300.0, 110.0), Point::new(320.0, 110.0));
let quad = h.state().quad;
assert!((quad[1].x - 320.0).abs() < 1e-6 && (quad[2].x - 320.0).abs() < 1e-6, "the right side moved: {quad:?}");
drag(&mut h, Point::new(100.0, 110.0), Point::new(80.0, 110.0));
let quad = h.state().quad;
assert!((quad[0].x - 80.0).abs() < 1e-6 && (quad[3].x - 80.0).abs() < 1e-6, "the left side moved: {quad:?}");
let mut picks = Vec::new();
h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).settle();
picks.extend(h.host.borrow().picked);
for _ in 0..3 {
h.fixture.key(egui::Key::PageDown, egui::Modifiers::NONE).settle();
picks.extend(h.host.borrow().picked);
}
assert!(picks.iter().all(|part| matches!(part, BoxPart::Edge(1) | BoxPart::Edge(3))), "the keys reach the shown sides only: {picks:?}");
assert!(picks.contains(&BoxPart::Edge(1)) && picks.contains(&BoxPart::Edge(3)), "and both of them: {picks:?}");
let mut corners = harness(BoxState::from_rect(RECT), |config| {
sides(config);
config.rules = no_turn().with_handles(BoxHandles::Corners);
});
for hidden in [Point::new(200.0, 80.0), Point::new(200.0, 220.0), Point::new(300.0, 150.0)] {
hover(&mut corners, hidden);
assert_eq!(corners.host.borrow().hovered, None, "a corners-only box's edge at {hidden:?} takes no press");
}
hover(&mut corners, off_corner);
assert_eq!(corners.host.borrow().hovered, Some(BoxPart::Corner(2)), "its corners still do");
}
/// The rotate knob stands above the box, or below it at the canvas's top edge; a ⇧ drag on it turns the box by whole
/// rotate steps under the grab pointer, and a click on it applies nothing. The knob is found as the app finds it, by
/// its access-tree name.
#[trial]
fn a_knob_sits_below_a_box_at_the_top_turns_in_shift_steps_and_a_click_on_it_applies_nothing() {
let knob_of = |h: &Harness| h.fixture.by_label("Rotate").map(|target| target.center());
let knob_zone = |config: &mut Config| {
config.zone = RotateZone::Knob;
config.reference_point = false;
};
// The harness's view puts the document's origin at the canvas's top left: a box at y 0 has no room above.
let at_top = Rect::new(100.0, 0.0, 300.0, 140.0);
let h = harness(BoxState::from_rect(at_top), knob_zone);
let knob = knob_of(&h).expect("the knob has a node named by the box's words");
let bottom = h.screen(Point::new(200.0, 140.0));
assert!((knob.x - bottom.x).abs() < 0.5 && knob.y > bottom.y, "at the top edge the knob stands below: {knob:?} vs {bottom:?}");
let mut h = harness(BoxState::from_rect(RECT), knob_zone);
let knob = knob_of(&h).expect("the knob has a node");
let top = h.screen(Point::new(200.0, 80.0));
assert!((knob.x - top.x).abs() < 0.5 && knob.y < top.y, "with room above the knob stands above: {knob:?} vs {top:?}");
frame(&mut h, vec![pointer::moved(knob)]);
frame(&mut h, vec![pointer::press(knob)]);
frame(&mut h, vec![pointer::release(knob)]);
frame(&mut h, Vec::new());
assert_eq!(h.host.borrow().applied, 0, "a click on the knob is not a click outside");
assert_eq!(h.state(), BoxState::from_rect(RECT), "and turns nothing");
h.config.borrow_mut().mods = Some(Mods::SHIFT);
let centre = h.screen(RECT.center());
let around = |degrees: f32| {
let (sin, cos) = degrees.to_radians().sin_cos();
let v = knob - centre;
centre + by(v.x * cos - v.y * sin, v.x * sin + v.y * cos)
};
frame(&mut h, vec![pointer::moved(knob)]);
assert_eq!(h.fixture.cursor_icon(), egui::CursorIcon::Grab, "the knob offers to be taken hold of");
frame(&mut h, vec![pointer::press(knob)]);
frame(&mut h, vec![pointer::moved(around(10.0))]);
frame(&mut h, vec![pointer::moved(around(25.0))]);
assert_eq!(h.fixture.cursor_icon(), egui::CursorIcon::Grabbing, "and holds it while it turns");
frame(&mut h, vec![pointer::release(around(25.0))]);
frame(&mut h, Vec::new());
let angle = h.state().angle().rem_euclid(360.0);
let step = BoxRules::default().rotate_step;
let steps = angle / step;
assert!(steps.round() >= 1.0 && (steps - steps.round()).abs() < 1e-6, "a ⇧ drag turns the box by whole rotate steps: {angle}");
assert!((angle - 25.0).abs() > 1.0, "not by the unstepped 25° of the drag: {angle}");
assert_eq!(h.host.borrow().events.last(), Some(&Seen::Commit));
assert_eq!(h.host.borrow().applied, 0, "a drag on the knob applies nothing");
}
/// A linked corner dragged inward along one axis, the other barely moving, still shrinks both sides in proportion
/// (#4477): the box does not freeze because one axis did not shrink.
#[trial]
fn a_linked_corner_dragged_inward_along_one_axis_shrinks_both_sides() {
let mut h = upright();
drag(&mut h, Point::new(300.0, 220.0), Point::new(220.0, 222.0));
let quad = h.state().quad;
let (width, height) = (quad[2].x - quad[0].x, quad[2].y - quad[0].y);
assert_eq!(quad[0], Point::new(RECT.x0, RECT.y0), "the opposite corner stays: {quad:?}");
assert!(width < RECT.width() - 1.0 && height < RECT.height() - 1.0, "both sides shrink: {width} by {height}");
assert!((width / height - RECT.width() / RECT.height()).abs() < 1e-6, "in proportion: {width} by {height}");
// PLAN: the framework scales a linked corner by the drag's projection on the anchor–corner diagonal (here 0.736 of
// the box); production scaled by the larger axis share (0.6, the 40 % the app test asserted). The rule is left as it is.
}
/// Round handles draw the eight corner and side handles as circles, where the default draws squares.
#[trial]
fn round_handles_are_circles() {
let circles = |round: bool| {
let mut h = harness(BoxState::from_rect(RECT), |config| config.round_handles = round);
h.fixture.frame_shapes().iter().filter(|shape| matches!(shape, egui::Shape::Circle(_))).count()
};
// Each handle is a filled circle and its stroke.
assert_eq!(circles(true), circles(false) + 16, "the four corners and four sides are circles");
}
+5
View File
@@ -497,6 +497,11 @@ impl Catalog {
}
}
/// A catalog of exactly `files`, built on the existing scan with no font folders and no store.
pub fn of_files(files: Vec<PathBuf>) -> Catalog {
Catalog::new(FontEnv { os: Os::None, ..FontEnv::default() }).with_font_service(false).with_lister(Arc::new(move || files.clone()))
}
/// The process's catalog, for [`FontEnv::from_process`].
pub fn global() -> &'static Arc<Catalog> {
static GLOBAL: OnceLock<Arc<Catalog>> = OnceLock::new();
+6 -6
View File
@@ -24,7 +24,7 @@ use craft_ui::primitives::textures::{Priority, Revision, ThumbPaint, ThumbRender
use craft_ui::runtime::commands::{CommandState, Commands as _};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::style::{DataColor, SurfaceKind};
use craft_ui::tile_grid::{CaptionPlace, ThumbnailSlider, Tile, TileGrid, TilePartEvent, TileZoom};
use craft_ui::tile_grid::{CaptionPlace, GridZoom, ThumbnailSlider, Tile, TileGrid, TilePartEvent, TileZoom};
use egui::{ColorImage, Context, Rect, Response, Ui};
use serde::{Deserialize, Serialize};
@@ -266,7 +266,7 @@ const RECENT_LIMIT: usize = 25;
/// The cell size of the grid and its zoom: factors of the medium thumbnail.
pub const ZOOM: TileZoom = TileZoom::bounded(1.0, 2.625, 0.125, 1.25);
/// The cells of the recents strip, as a factor of the medium thumbnail.
const RECENT_ZOOM: f32 = 0.75;
const RECENT_ZOOM: f64 = 0.75;
/// The room round a glyph in its cell, as a fraction of the cell.
const GLYPH_INSET_RATIO: f32 = 0.1;
/// The most columns the alternates popup lays its cells in.
@@ -552,7 +552,7 @@ impl<'a> GlyphsPanel<'a> {
let mut activated: Option<GlyphCell> = None;
let strip = TileGrid::<usize>::new(words.recent.clone())
.thumb_size(ThumbSize::Medium)
.zoom(RECENT_ZOOM)
.zoom(GridZoom::Fixed(RECENT_ZOOM))
.caption(CaptionPlace::None)
.select(SelectMode::Single)
.activate(ActivateOn::Click)
@@ -586,7 +586,7 @@ impl<'a> GlyphsPanel<'a> {
_ => {
let mut grid = TileGrid::<usize>::new(words.grid.clone())
.thumb_size(ThumbSize::Medium)
.zoom(size as f32)
.zoom(GridZoom::Fixed(size))
.caption(CaptionPlace::None)
.select(SelectMode::Single)
.selection(Bind::bound(&mut marked.0));
@@ -601,7 +601,7 @@ impl<'a> GlyphsPanel<'a> {
tile = tile.dimmed();
}
if info.has_alternates {
tile = tile.corner_action(IconId::new(ALTERNATES_ICON), GlyphsCommand::Alternates);
tile = tile.action(IconId::new(ALTERNATES_ICON), GlyphsCommand::Alternates);
}
match info.note {
Some(note) => tile.tooltip(note),
@@ -611,7 +611,7 @@ impl<'a> GlyphsPanel<'a> {
for event in shown_grid.response.events {
match event {
CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated),
CollectionEvent::Item(key, TilePartEvent::CornerAction) => {
CollectionEvent::Item(key, TilePartEvent::Action(0)) => {
if let Some(&cell) = cells.get(key) {
*cx.memory::<Popup>() = Popup { open: true, cell: Some(cell), cells: source.alternates(face.0, face.1, cell) };
}
@@ -35,6 +35,8 @@ pub(crate) struct FontSampleStyle {
pub(crate) enum SampleFace<'a> {
/// A face of `catalog`, which the document-face registry loads when the sample is measured or painted.
Face { catalog: &'a Arc<Catalog>, owner: Owner, face: &'a FaceInfo },
/// A face the host gives, ready as it is (a host row of the picker).
Font(&'a FontRef),
/// No face is here to draw with: the sample keeps its band and shows nothing.
Missing,
}
@@ -49,6 +51,7 @@ impl SampleFace<'_> {
Shown::Ready(font) => Some(font),
_ => None,
},
SampleFace::Font(font) => Some((*font).clone()),
SampleFace::Missing => None,
}
}
+168 -26
View File
@@ -19,10 +19,11 @@ use craft_host::Section;
use craft_theme::variant::Tone;
use craft_ui::buttons::{ControlPlace, IconButton};
use craft_ui::contract::{
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Access, Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop,
};
use craft_ui::controls::disclosure::DisclosureGlyph;
use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow};
use craft_ui::fonts::FontRef;
use craft_ui::list::{ListRow, ThumbSize, TrailingPart};
use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun};
use craft_ui::runtime::edit::PreviewWatch;
@@ -58,6 +59,8 @@ craft_ui::words! {
/// The name of the preview banner, with `{family}` for the family it shows.
preview_of: template "fontPicker.previewOf" = "Font preview: {family}";
no_match: "fontPicker.noMatch" = "No fonts match";
/// The family field's label when the selection has several families.
mixed: "fontPicker.mixed" = "Mixed";
/// The name of a row's star, with `{row}` for the row's label.
favorite: template "fontPicker.favorite" = "Favorite {row}";
list: "fontPicker.list" = "Fonts";
@@ -428,6 +431,64 @@ pub enum MissingAdvice {
AddFont,
}
/// A group of host rows listed above the catalogue families, under an optional heading.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct HostFontGroup<'a> {
/// The group's heading, if it has one.
pub heading: Option<Label>,
/// The group's rows, in order.
pub rows: &'a [HostFontRow],
}
impl<'a> HostFontGroup<'a> {
/// A group of `rows` under `heading`.
pub fn new(heading: Option<Label>, rows: &'a [HostFontRow]) -> Self {
HostFontGroup { heading, rows }
}
}
/// A row the host adds to the picker: a face, an action or a notice.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct HostFontRow {
/// The key `host_picked` reports when the row is run.
pub key: String,
/// The row's name.
pub name: Label,
/// What the row is.
pub kind: HostFontKind,
}
impl HostFontRow {
/// A face row; it shows its sample in `face` when given.
pub fn face(key: impl Into<String>, name: impl Into<Label>, face: Option<FontRef>) -> Self {
HostFontRow { key: key.into(), name: name.into(), kind: HostFontKind::Face(face) }
}
/// An action row; it runs and picks no family.
pub fn action(key: impl Into<String>, name: impl Into<Label>) -> Self {
HostFontRow { key: key.into(), name: name.into(), kind: HostFontKind::Action }
}
/// A notice row: disabled text.
pub fn notice(name: impl Into<Label>) -> Self {
HostFontRow { key: String::new(), name: name.into(), kind: HostFontKind::Notice }
}
}
/// What a [`HostFontRow`] is.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum HostFontKind {
/// A face to pick, with the face its sample shows in.
Face(Option<FontRef>),
/// An action that runs and picks no family.
Action,
/// Disabled text.
Notice,
}
/// What a [`FontPicker`] reports.
#[derive(Debug)]
#[non_exhaustive]
@@ -447,6 +508,8 @@ pub struct FontPickerOutput {
pub preview: Preview<String>,
/// The index of the action row picked, in the `actions` the host gave.
pub action: Option<usize>,
/// The key of the host face or action row run in this pass; a host pick does not write the `family` binding.
pub host_picked: Option<String>,
}
impl Outcome for FontPickerOutput {
@@ -489,6 +552,8 @@ struct FamilyCodec {
language: String,
/// A typed name that is no installed family is a value too (Word's font box applies it as typed).
free: bool,
/// The name of the host row shown as the field's value, which stands in for the family's name.
host: Option<String>,
}
impl FamilyCodec {
@@ -501,6 +566,9 @@ impl Codec for FamilyCodec {
type Value = String;
fn format(&self, family: &String) -> String {
if let Some(name) = &self.host {
return name.clone();
}
self.infos.families.get(family).map_or_else(|| family.clone(), |info| self.shown(family, info))
}
@@ -593,6 +661,12 @@ fn read<T: Value>(bind: &mut Option<Bind<'_, T>>, cx: &mut impl StageAccess) ->
read_bind(bind.as_mut()?, cx)
}
/// A stop of the closed field's arrows and wheel: a host face or action row, or a family.
enum Stop {
Host(String),
Family(String),
}
/// The font family field. Typing filters the list to the families whose name (in any language) matches, the best
/// match first, and opens it; a click on the name while the list is closed, the chevron and Alt+Down open it on every family (the click selects the name), Alt+Up closes it. Rows: a star, the
/// family name in the interface face, the sample text (the preview text, else "Sample") in the family's own face at the
@@ -602,7 +676,8 @@ fn read<T: Value>(bind: &mut Option<Bind<'_, T>>, cx: &mut impl StageAccess) ->
/// restores the field, and Tab picks the keyboard row and moves on. While an input method composes, Enter, Escape
/// and the arrows are the composition's. On the closed, focused field the arrows and the wheel step to the previous
/// or next family in list order and pick it. The list is the field's own popup: filter toggles above, the class
/// column at the reading start and the families beside it.
/// column at the reading start and the families beside it. Host groups (`host`) list above the families: a face or
/// action row is reported as `host_picked` and writes no family, and a notice row is disabled text.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(overlay)]
pub struct FontPicker<'a> {
@@ -648,6 +723,13 @@ pub struct FontPicker<'a> {
#[prop]
advice: MissingAdvice,
action: Option<usize>,
/// Host groups listed above the catalogue families, in order, with a separator between groups.
#[prop]
host: &'a [HostFontGroup<'a>],
/// The key of the host row shown as the field's value.
#[prop]
current_host: Option<String>,
host_picked: Option<String>,
}
impl<'a> FontPicker<'a> {
@@ -673,6 +755,9 @@ impl<'a> FontPicker<'a> {
shown_as: None,
advice: MissingAdvice::default(),
action: None,
host: &[],
current_host: None,
host_picked: None,
}
.label(label)
.enabled(catalog.is_ready())
@@ -680,19 +765,20 @@ impl<'a> FontPicker<'a> {
/// The adornments at the end of the field: the missing mark when `missing`, then the chevron. The mark is a glyph
/// whose part carries the note.
fn trailing(name: Label, missing: bool) -> Vec<Adornment> {
fn trailing(name: Label, missing: bool, arrow: DropdownArrow) -> Vec<Adornment> {
let mut all = Vec::with_capacity(2);
if missing {
all.push(Adornment::glyph(IconSpec::svg(IconId::new(WARNING_ICON))));
}
all.push(Adornment::button(CHEVRON, DisclosureGlyph::dropdown(), name));
all.push(Adornment::button(CHEVRON, DisclosureGlyph::dropdown_of(arrow), name));
all
}
/// The note for `family` when it is shown in another face because the catalog lacks it, by the rule the Missing
/// Fonts dialog uses: the missing-font sentence, then the advice the host chose.
/// Fonts dialog uses: the missing-font sentence, then the advice the host chose. A host row shown as the value
/// has none.
fn missing_note(&self, family: &str, words: &MissingFontsWords) -> Option<Label> {
let face = self.shown_as.filter(|_| self.catalog.is_ready())?;
let face = self.shown_as.filter(|_| self.catalog.is_ready() && self.host_name().is_none())?;
let status = document_fonts(self.catalog, &[DocumentFont::new(family, "", None)]).into_iter().next()?.status;
if status != FontStatus::Missing {
return None;
@@ -706,7 +792,29 @@ impl<'a> FontPicker<'a> {
}
fn codec(&self, infos: Arc<FamilyInfos>, env: &EnvView<'_>) -> FamilyCodec {
FamilyCodec { infos, language: ui_language(env), free: self.kind == FontPickerKind::Plain }
FamilyCodec { infos, language: ui_language(env), free: self.kind == FontPickerKind::Plain, host: self.host_name() }
}
/// The name of the host row `current_host` names, which the field shows in place of the family.
fn host_name(&self) -> Option<String> {
let key = self.current_host.as_deref()?;
self.host
.iter()
.flat_map(|group| group.rows.iter())
.find(|row| row.key == key && !matches!(row.kind, HostFontKind::Notice))
.map(|row| row.name.as_str().to_owned())
}
/// What the closed field's arrows and wheel step through: the host face and action rows in group order, then the
/// families in the list's narrowed order. A notice takes no step.
fn stops(&self, cx: &Cx<'_, Self>, settings: Option<&FontPickerSettings>, filters: &FontFilters) -> Vec<Stop> {
let folder = cx.env.folder();
let host = rank::host_rows(self.host, "", &folder)
.into_iter()
.filter_map(|(group, at)| self.host.get(group)?.rows.get(at))
.filter(|row| !matches!(row.kind, HostFontKind::Notice))
.map(|row| Stop::Host(row.key.clone()));
host.chain(self.ordered(cx, settings, filters).into_iter().map(|row| Stop::Family(row.family))).collect()
}
/// The families in the list's narrowed order (the bound filters and the host's sets apply) without the Recent
@@ -798,20 +906,21 @@ impl Component for FontPicker<'_> {
/// name, so a row short of room never narrows the box to its menu arrow; where the room allows the style holds
/// the box at the small field length (`FieldStyle::held_at`).
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let current = cx.value().map_or("", String::as_str);
let host = self.host_name();
let current = host.as_deref().or(cx.value().map(String::as_str)).unwrap_or("");
let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max);
let ribbon = cx.env.get::<ControlPlace>() == ControlPlace::Ribbon;
let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest };
let name = cx.words::<FontPickerWords>().list.clone();
let note = self.missing_note(current, &cx.words::<MissingFontsWords>());
Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some())), widest.y)
Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some(), cx.env.get())), widest.y)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let name = cx.words::<FontPickerWords>().list.clone();
let family = cx.value().cloned().unwrap_or_default();
let note = self.missing_note(&family, &cx.words::<MissingFontsWords>());
let trailing = Self::trailing(name, note.is_some());
let trailing = Self::trailing(name, note.is_some(), cx.env.get());
let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.flow.is_rtl());
if let (Some(note), Some(at)) = (note, placed.trailing.first()) {
cx.part(WARNING, *at).tooltip(note);
@@ -825,6 +934,10 @@ impl Component for FontPicker<'_> {
}
let mut options = TextOptions::new();
options.select_on_focus = true;
options.mixed = cx.value().is_none();
if options.mixed {
options.placeholder = Some(cx.words::<FontPickerWords>().mixed.clone());
}
if !self.catalog.is_ready() {
// The first scan runs on a background thread; the field asks again until it ends.
self.catalog.scan_in_background();
@@ -841,9 +954,15 @@ impl Component for FontPicker<'_> {
Some(self.family.reborrow())
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if cx.value().is_none() && cx.text(&text_key()).is_none_or(|text| text.draft.as_deref().is_none_or(str::is_empty)) {
access.value(cx.words::<FontPickerWords>().mixed.as_str());
}
}
/// A changed draft filters the list: it opens on the matches, and closes when the draft ended (committed,
/// cancelled or replaced by a pick). A preview that the list closed on without a pick is cancelled. While the
/// list is closed, the arrows and the wheel step through the families.
/// list is closed, the arrows and the wheel step through the host rows and the families.
fn update(&mut self, cx: &mut Cx<'_, Self>) {
if !self.catalog.is_ready() {
return;
@@ -878,9 +997,12 @@ impl Component for FontPicker<'_> {
typing.rested.clear();
let settings = read(&mut self.settings, cx);
let filters = read(&mut self.filters, cx).unwrap_or_default();
let all = self.ordered(cx, settings.as_ref(), &filters);
let all = self.stops(cx, settings.as_ref(), &filters);
let stops: Vec<usize> = (0..all.len()).collect();
let here = cx.value().and_then(|current| all.iter().position(|row| row.family == *current));
let here = match self.current_host.as_deref() {
Some(key) => all.iter().position(|stop| matches!(stop, Stop::Host(host) if host == key)),
None => cx.value().and_then(|current| all.iter().position(|stop| matches!(stop, Stop::Family(family) if family == current))),
};
let mut to = here;
while let Some((step, mods)) = cx.intents().take_move() {
match step {
@@ -889,12 +1011,17 @@ impl Component for FontPicker<'_> {
_ => {}
}
}
if to != here
&& let Some(row) = to.and_then(|at| all.get(at))
{
cx.set(row.family.clone());
if to != here {
match to.and_then(|at| all.get(at)) {
Some(Stop::Host(key)) => self.host_picked = Some(key.clone()),
Some(Stop::Family(family)) => {
self.picked = Some(family.clone());
cx.set(family.clone());
}
None => {}
}
}
// The wheel steps one family a line down for a step forward, as one run the wheel's end commits.
// The wheel steps one stop a line down for a step forward, as one run the wheel's end commits.
if let Some(wheel) = cx.take_wheel() {
if wheel.phase == WheelPhase::End {
cx.wheel_run(wheel.phase, None);
@@ -902,12 +1029,17 @@ impl Component for FontPicker<'_> {
wheel_step(&ValueSteps::new(0.0, -f64::MAX, f64::MAX, 1.0, 1.0).fine(1.0), ValueAxes::Both, &wheel, cx.env.direction().is_rtl())
&& along != 0.0
{
let mut stop = cx.value().and_then(|current| all.iter().position(|row| row.family == *current));
let mut stop = match self.current_host.as_deref() {
Some(key) => all.iter().position(|stop| matches!(stop, Stop::Host(host) if host == key)),
None => cx.value().and_then(|current| all.iter().position(|stop| matches!(stop, Stop::Family(family) if family == current))),
};
for _ in 0..along.abs().round() as usize {
stop = step_stop(&stops, stop, along < 0.0);
}
if let Some(row) = stop.and_then(|at| all.get(at)) {
cx.wheel_run(wheel.phase, Some(row.family.clone()));
match stop.and_then(|at| all.get(at)) {
Some(Stop::Host(key)) => self.host_picked = Some(key.clone()),
Some(Stop::Family(family)) => cx.wheel_run(wheel.phase, Some(family.clone())),
None => {}
}
}
}
@@ -923,13 +1055,13 @@ impl Component for FontPicker<'_> {
let name = cx.words::<FontPickerWords>().list.clone();
let family = cx.value().cloned().unwrap_or_default();
let missing = self.missing_note(&family, &cx.words::<MissingFontsWords>()).is_some();
let trailing = Self::trailing(name.clone(), missing);
let trailing = Self::trailing(name.clone(), missing, cx.env.get());
let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.env.direction().is_rtl());
if let (true, Some(at)) = (missing, placed.trailing.first()) {
let color = cx.resolve(&cx.style.warning);
ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)).color(color));
}
ui.face(CHEVRON, IconButton::new(DisclosureGlyph::dropdown()).label(name));
ui.face(CHEVRON, IconButton::new(DisclosureGlyph::dropdown_of(cx.env.get())).label(name));
}
fn finish(self, mut cx: Cx<'_, Self>) -> FontPickerOutput {
@@ -938,7 +1070,9 @@ impl Component for FontPicker<'_> {
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => Some(after.clone()),
_ => None,
});
let picked = committed.or(self.picked);
let host_picked = self.host_picked;
// A host row is no family: it writes no binding and is not a recent family.
let picked = if host_picked.is_some() { None } else { committed.or(self.picked) };
let mut bind = self.settings;
if let Some(family) = &picked
&& let Some(mut settings) = read(&mut bind, &mut cx)
@@ -946,6 +1080,14 @@ impl Component for FontPicker<'_> {
settings.note_recent(family);
write(&mut bind, &mut cx, settings, "Recent font");
}
FontPickerOutput { edit, picked, preview: self.preview, picked_style: self.picked_style, rested: self.rested, action: self.action }
FontPickerOutput {
edit,
picked,
preview: self.preview,
picked_style: self.picked_style,
rested: self.rested,
action: self.action,
host_picked,
}
}
}
+17 -1
View File
@@ -12,7 +12,7 @@ use skrifa::GlyphId;
use skrifa::MetadataProvider as _;
use skrifa::raw::{FontRef, TableProvider};
use super::{FamilyRow, FamilySet, FontClass, FontFilters, FontFormat, FontPickerSettings, FontScript, SIMILAR_COUNT};
use super::{FamilyRow, FamilySet, FontClass, FontFilters, FontFormat, FontPickerSettings, FontScript, HostFontGroup, HostFontKind, SIMILAR_COUNT};
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
@@ -397,3 +397,19 @@ pub(super) fn list(
}
(rows, comparable)
}
/// The host rows the list shows for `query`, as (group, row) in group order: every row for an empty query, else the
/// face and action rows whose name matches as a family name would. A notice speaks of its group as a whole, so it
/// shows only in the unfiltered list.
pub(super) fn host_rows(groups: &[HostFontGroup<'_>], query: &str, folder: &Folder) -> Vec<(usize, usize)> {
let matcher = Matcher::new(folder, query);
let listed =
|row: &super::HostFontRow| matcher.is_empty() || (!matches!(row.kind, HostFontKind::Notice) && matcher.score(row.name.as_str()).is_some());
groups
.iter()
.enumerate()
.flat_map(|(group, rows)| rows.rows.iter().enumerate().map(move |(at, row)| (group, at, row)))
.filter(|(_, _, row)| listed(row))
.map(|(group, at, _)| (group, at))
.collect()
}
+125 -30
View File
@@ -1,5 +1,5 @@
//! The picker's popup: the preview banner, the filter toggles, the class column and the list of family rows with the
//! styles of the families opened in it. A family row reads, in reading order: its star, the disclosure of its styles
//! The picker's popup: the preview banner, the filter toggles, the class column and the list of the host's rows and
//! the family rows with the styles of the families opened in it. A family row reads, in reading order: its star, the disclosure of its styles
//! (or the empty disclosure column), the name, the format badge and the sample in the family's face.
use std::borrow::Cow;
@@ -25,10 +25,11 @@ use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::StageAccess;
use super::banner::FontPreviewBanner;
use super::rank::{FamilyInfos, Language, Listing, list, shown_name};
use super::rank::{FamilyInfos, Language, Listing, host_rows, list, shown_name};
use super::{
FamilyRow, FamilySet, FilterLayout, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords,
FontPreviewSize, FontScript, POPUP, SAMPLE_EM, SIMILAR, Sample, Typing, infos_of, read, ui_language, write,
FontPreviewSize, FontScript, HostFontGroup, HostFontKind, HostFontRow, POPUP, SAMPLE_EM, SIMILAR, Sample, Typing, infos_of, read, ui_language,
write,
};
use crate::panel::faces::{self, Owner, Shown};
use crate::panel::specimen::{FontSample, SampleFace};
@@ -50,12 +51,22 @@ enum Heading {
All,
}
/// One position of the list: a family, one style of an open family, the gap between the recents and the other
/// families, a heading of the `Plain` list, or one of the host's action rows.
/// Which gap a gap slot is: the one after a host group (before the next group or the families), or the one between
/// the recents and the other families.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Gap {
Host(usize),
Recents,
}
/// One position of the list: a host group's heading, a host row (`at` in group `group`), a family, one style of an
/// open family, a gap, a heading of the `Plain` list, or one of the host's action rows.
enum Slot {
HostHeading { group: usize, name: Label },
Host { group: usize, at: usize, row: HostFontRow },
Family { row: FamilyRow, open: bool },
Style { family: String, style: String },
Gap,
Gap(Gap),
Heading(Heading),
Action(usize),
}
@@ -72,8 +83,10 @@ struct Layout {
/// they are and the lead stays on its row.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum SlotKey {
Gap,
Gap(Gap),
Heading(Heading),
HostHeading(usize),
Host { group: usize, at: usize },
Action(usize),
Family { family: String, recent: bool },
Style { family: String, style: String },
@@ -82,20 +95,23 @@ enum SlotKey {
impl Slot {
fn key(&self) -> SlotKey {
match self {
Slot::HostHeading { group, .. } => SlotKey::HostHeading(*group),
Slot::Host { group, at, .. } => SlotKey::Host { group: *group, at: *at },
Slot::Family { row, .. } => SlotKey::Family { family: row.family.clone(), recent: row.recent },
Slot::Style { family, style } => SlotKey::Style { family: family.clone(), style: style.clone() },
Slot::Gap => SlotKey::Gap,
Slot::Gap(gap) => SlotKey::Gap(*gap),
Slot::Heading(heading) => SlotKey::Heading(*heading),
Slot::Action(at) => SlotKey::Action(*at),
}
}
/// The family the slot stands for, which the lead previews.
/// The family the slot stands for, which the lead previews. A host row has no catalogue family to preview or
/// rest on.
fn family(&self) -> Option<&str> {
match self {
Slot::Family { row, .. } => Some(&row.family),
Slot::Style { family, .. } => Some(family),
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
Slot::HostHeading { .. } | Slot::Host { .. } | Slot::Gap(_) | Slot::Heading(_) | Slot::Action(_) => None,
}
}
@@ -104,7 +120,7 @@ impl Slot {
match self {
Slot::Family { row, .. } => Some((&row.family, None)),
Slot::Style { family, style } => Some((family, Some(style))),
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
Slot::HostHeading { .. } | Slot::Host { .. } | Slot::Gap(_) | Slot::Heading(_) | Slot::Action(_) => None,
}
}
}
@@ -147,22 +163,30 @@ impl DisplayOrder<SlotKey> for Slots<'_> {
}
fn is_section(&self, at: usize) -> bool {
matches!(self.slots[at], Slot::Gap | Slot::Heading(_))
matches!(self.slots[at], Slot::Gap(_) | Slot::Heading(_) | Slot::HostHeading { .. })
}
/// A notice is text, which neither the keys nor a click take.
fn enabled(&self, at: usize) -> bool {
!matches!(&self.slots[at], Slot::Host { row, .. } if matches!(row.kind, HostFontKind::Notice))
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
match &self.slots[at] {
Slot::HostHeading { name, .. } => Some(Cow::Borrowed(name.as_str())),
Slot::Host { row, .. } => Some(Cow::Borrowed(row.name.as_str())),
Slot::Family { row, .. } => Some(Cow::Borrowed(row.shown.as_str())),
Slot::Style { style, .. } => Some(Cow::Borrowed(style.as_str())),
Slot::Gap | Slot::Heading(_) | Slot::Action(_) => None,
Slot::Gap(_) | Slot::Heading(_) | Slot::Action(_) => None,
}
}
}
impl ItemSource<SlotKey> for Slots<'_> {
fn size_hint(&self, at: usize) -> SizeHint {
match self.slots[at] {
match &self.slots[at] {
Slot::Family { .. } => SizeHint::Height(self.row),
Slot::Host { row, .. } if matches!(row.kind, HostFontKind::Face(_)) => SizeHint::Height(self.row),
_ => SizeHint::Auto,
}
}
@@ -172,11 +196,40 @@ impl ItemSource<SlotKey> for Slots<'_> {
}
}
/// The rows with a gap after the recents (headings over the recents and the families under `layout.sections`), the
/// styles of each expanded family under its row, and the action rows at the end.
fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String], layout: &Layout) -> Vec<Slot> {
/// The `shown` host rows (as `host_rows` lists them) by group, each under its group's heading, with a gap after each
/// group that has rows; then the family rows with a gap after the recents (headings over the recents and the
/// families under `layout.sections`), the styles of each expanded family under its row, and the action rows at the
/// end.
fn slots(
catalog: &Catalog,
host: &[HostFontGroup<'_>],
shown: &[(usize, usize)],
rows: Vec<FamilyRow>,
expanded: &[String],
layout: &Layout,
) -> Vec<Slot> {
let recents = rows.iter().take_while(|row| row.recent).count();
let mut slots: Vec<Slot> = Vec::with_capacity(rows.len() + 2);
let mut slots: Vec<Slot> = Vec::with_capacity(shown.len() + rows.len() + 2);
let mut last_group: Option<usize> = None;
for &(group, at) in shown {
let Some(of) = host.get(group) else { continue };
let Some(row) = of.rows.get(at) else { continue };
if last_group != Some(group) {
if let Some(last) = last_group {
slots.push(Slot::Gap(Gap::Host(last)));
}
if let Some(name) = &of.heading {
slots.push(Slot::HostHeading { group, name: name.clone() });
}
last_group = Some(group);
}
slots.push(Slot::Host { group, at, row: row.clone() });
}
if let Some(last) = last_group
&& !rows.is_empty()
{
slots.push(Slot::Gap(Gap::Host(last)));
}
for (at, row) in rows.into_iter().enumerate() {
if layout.sections {
@@ -187,7 +240,7 @@ fn slots(catalog: &Catalog, rows: Vec<FamilyRow>, expanded: &[String], layout: &
slots.push(Slot::Heading(Heading::All));
}
} else if at == recents && recents > 0 {
slots.push(Slot::Gap);
slots.push(Slot::Gap(Gap::Recents));
}
let open = !row.recent && row.styles > 1 && expanded.contains(&row.family);
let family = row.family.clone();
@@ -417,6 +470,26 @@ fn row_text(at: &impl FacesCx, catalog: &Arc<Catalog>, infos: &FamilyInfos, fami
}
}
/// The line of a host row: a face with its name as the sample in its own face, an action, or a notice that takes no
/// activation. A face row lays out in the list's columns as a family row does.
fn host_line<'r>(row: &'r HostFontRow, checked: bool, cells: &[(ColumnKey, egui::Rect)], size: ThumbSize, sample: Sample) -> ListRow<'r> {
match &row.kind {
HostFontKind::Notice => ListRow::new(row.name.clone()).depth(0).enabled(false),
HostFontKind::Action => ListRow::new(row.name.clone()).option().depth(0),
HostFontKind::Face(face) => {
let line = ListRow::new(row.name.clone()).cells(cells).option().depth(0).check(checked);
match face.as_ref().filter(|_| size != ThumbSize::None) {
Some(font) => {
let text = row.name.as_str();
let sample = FontSample::new(format!("{text}: {text}"), text, SampleFace::Font(font), sample.side * SAMPLE_EM).band(sample.side);
line.cell_field(SAMPLE, sample, |_| {})
}
None => line,
}
}
}
}
/// The name the banner shows for `family`: its row's shown name when the list holds one, else its name in the
/// interface language, else the family key.
fn banner_shown_name(slots: &[Slot], infos: &FamilyInfos, family: &str, language: &str, settings: Option<&FontPickerSettings>) -> String {
@@ -462,15 +535,17 @@ pub(super) fn end_preview<'a>(picker: &mut FontPicker<'a>, cx: &mut Cx<'_, FontP
}
}
/// The list popup: one option row per family, the committed family's row selected, and the styles of the open
/// families under their rows. A pick comes back as `Activate` (Enter, Tab or a click), a row the lead moves to is
/// reported as the preview (the field's value and text stay), and a star flips a favourite. Each pass reports only the events of its own input.
/// The list popup: the host rows above, one option row per family, the current row selected, and the styles of the
/// open families under their rows. A pick comes back as `Activate` (Enter, Tab or a click), a family row the lead
/// moves to is reported as the preview (the field's value and text stay), and a star flips a favourite. A host face
/// or action row picked is reported as `host_picked` and proposes no family. Each pass reports only the events of its
/// own input.
pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, FontPicker<'a>>) {
let popup = cx.popup(POPUP);
let words = cx.words::<FontPickerWords>();
let (query, lead, expanded) = {
let (query, drafting, lead, expanded) = {
let typing = cx.memory::<Typing>();
(typing.draft.clone().unwrap_or_default(), typing.lead.clone(), typing.expanded.clone())
(typing.draft.clone().unwrap_or_default(), typing.draft.is_some(), typing.lead.clone(), typing.expanded.clone())
};
let mut hide_classes = cx.memory::<Typing>().hide_classes;
let family = cx.value().cloned().unwrap_or_default();
@@ -492,8 +567,12 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
let listing = Listing { query: &query, settings: settings.as_ref(), filters: &narrowing, language: &language_code, served: picker.served, sets };
let (found, comparable) = list(catalog, &infos, &listing, &Language { folder: &folder, collator: &collator }, true);
let layout = Layout { sections: plain && query.trim().is_empty(), actions: actions.len() };
let slots = slots(catalog, found, &expanded, &layout);
let current = slots.iter().position(|slot| matches!(slot, Slot::Family { row, .. } if row.family == family));
let shown_host = host_rows(picker.host, &query, &folder);
let slots = slots(catalog, picker.host, &shown_host, found, &expanded, &layout);
let current = match picker.current_host.as_deref() {
Some(key) => slots.iter().position(|slot| matches!(slot, Slot::Host { row, .. } if row.key == key)),
None => slots.iter().position(|slot| matches!(slot, Slot::Family { row, .. } if row.family == family)),
};
let size = settings.as_ref().map_or(ThumbSize::None, |s| s.preview.thumb());
let sample_size = cx.style.sample(size);
let mut columns = Vec::with_capacity(4);
@@ -579,7 +658,9 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
.selection(Bind::given(selection))
.rows_stamp(stamp.finish())
.show_items(ui, &source, &mut |_, item| match &slots[item.at] {
Slot::Gap => ListRow::separator(),
Slot::Gap(_) => ListRow::separator(),
Slot::HostHeading { name, .. } => ListRow::new(name.clone()).heading(),
Slot::Host { row, .. } => host_line(row, current == Some(item.at), item.cells(), size, sample_size),
Slot::Heading(Heading::Recent) => ListRow::new(words.recently_used.clone()).section_heading(),
Slot::Heading(Heading::All) => ListRow::new(words.all_fonts.clone()).section_heading(),
Slot::Action(at) => ListRow::new(actions[*at].clone()).option().depth(0),
@@ -629,8 +710,12 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
for event in events.into_iter().flatten() {
match event {
CollectionEvent::LeadMoved { key, by } => {
if let Some(family) = slot_of(&slots, &key).and_then(Slot::family) {
show_preview(picker, cx, family.to_owned(), by == LeadSource::Pointer);
if let Some(slot) = slot_of(&slots, &key) {
match slot.family() {
Some(family) => show_preview(picker, cx, family.to_owned(), by == LeadSource::Pointer),
// A host row previews nothing, so the family the lead left stops showing.
None => end_preview(picker, cx),
}
}
}
CollectionEvent::Rested(key) => {
@@ -705,6 +790,16 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
picker.action = Some(*at);
end_preview(picker, cx);
popup.close(cx);
} else if let Some(Slot::Host { row, .. }) = chosen
&& !matches!(row.kind, HostFontKind::Notice)
{
picker.host_picked = Some(row.key.clone());
end_preview(picker, cx);
// A host pick writes no family, so a typed query goes back to the field's text.
if drafting {
cx.set_draft(None);
}
popup.close(cx);
} else if let Some((family, style)) = chosen.and_then(Slot::pick) {
picker.picked = Some(family.to_owned());
picker.picked_style = style.map(str::to_owned);
+26 -7
View File
@@ -1,19 +1,22 @@
//! Stories of `FontPicker`: the closed field, the list open with recents and a typed query, and the list open with
//! the class column and a filter on. They draw from the two faces egui ships in an in-memory catalog, with Inter where a
//! story needs a family of two styles, Noto Sans Arabic, from the craft fonts set when the build has
//! `CRAFT_FONTS_DIR`, for the Arabic sample, and the repository's Noto Sans CJK SC subset for the Chinese one.
//! Stories of `FontPicker`: the closed field, the list open with recents and a typed query, the list open with the
//! class column and a filter on, and the list open with host rows above the families. They draw from the two faces
//! egui ships in an in-memory catalog, with Inter where a story needs a family of two styles, Noto Sans Arabic, from
//! the craft fonts set when the build has `CRAFT_FONTS_DIR`, for the Arabic sample, and the repository's Noto Sans CJK
//! SC subset for the Chinese one.
use std::sync::{Arc, OnceLock};
use craft_behavior::Mixed;
use craft_ui::contract::{Bind, Show as _, Validity};
use craft_ui::fonts::EmbeddedFace;
use craft_ui::fonts::{EmbeddedFace, FontRef};
use craft_ui::runtime::env::{Label, Message};
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
use egui::{Key, Modifiers, Ui};
use super::{FamilySet, FilterLayout, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontScript, MissingAdvice};
use super::{
FamilySet, FilterLayout, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontScript, HostFontGroup, HostFontRow, MissingAdvice,
};
use crate::Catalog;
use crate::craft_font_catalog::{Limits, Source};
use crate::panel::fixtures::story_catalog;
@@ -84,6 +87,7 @@ struct Extras<'a> {
actions: &'a [Label],
shown_as: Option<&'a str>,
advice: MissingAdvice,
host: &'a [HostFontGroup<'a>],
}
fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalog>, extras: &Extras<'_>) -> StoryOutput {
@@ -97,7 +101,8 @@ fn show_with(ui: &mut Ui, data: &mut StoryData, init: Demo, catalog: &Arc<Catalo
.filter_layout(extras.layout)
.kind(extras.kind)
.actions(extras.actions)
.advice(extras.advice);
.advice(extras.advice)
.host(extras.host);
if let Some(face) = extras.shown_as {
picker = picker.shown_as(face);
}
@@ -187,6 +192,20 @@ fn font_picker_served(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
)
}
/// A host group above the families: a face with its sample, an action and a notice, under the group's heading.
#[story(FontPicker<'static>, covers = [], drive = Drive::Custom(open_list))]
fn font_picker_host_groups(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let rows = [
HostFontRow::face("document-sans", "Document Sans", Some(FontRef::proportional())),
HostFontRow::face("document-mono", "Document Mono", Some(FontRef::monospace())),
HostFontRow::action("load", "Load font file"),
HostFontRow::notice("Subset fonts can't take new text"),
];
let host = [HostFontGroup::new(Some(Label::from("Document fonts")), &rows)];
let extras = Extras { host: &host, ..Extras::default() };
show_with(ui, data, demo("Ubuntu", FontPickerSettings::default(), FontFilters::default()), &catalog(), &extras)
}
/// The preview banner above the filters.
#[story(FontPicker<'static>, covers = [Open], drive = Drive::Custom(open_list))]
fn font_picker_banner_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+88 -5
View File
@@ -1,5 +1,5 @@
//! The font picker's flows: style rows under an expanded family, served families and the rested report, and similar
//! fonts.
//! The font picker's flows: style rows under an expanded family, served families and the rested report, similar
//! fonts, and the host's rows.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
@@ -10,7 +10,7 @@ use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
use craft_font_manager::missing::MissingFontsWords;
use craft_font_manager::picker::{
FamilyInfos, FamilySet, FontClass, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, FontPreviewSize, FontScript,
MissingAdvice, SIMILAR_COUNT, family_rows,
HostFontGroup, HostFontRow, MissingAdvice, SIMILAR_COUNT, family_rows,
};
use craft_font_manager::{Catalog, FontEnv};
use craft_theme::{Contrast, Mode};
@@ -47,23 +47,54 @@ struct Seen {
actions: Vec<usize>,
/// The id of the shown picker, as the last pass reported it.
id: Option<egui::Id>,
/// The keys of the host rows picked, in order.
host_picks: Vec<String>,
}
fn rig(catalog: Arc<Catalog>, served: Vec<String>) -> (Fixture, Rc<RefCell<Seen>>) {
rig_with(catalog, served, FontPickerSettings::default(), None)
rig_full(catalog, served, FontPickerSettings::default(), None, Vec::new(), None)
}
/// A rig whose picker keeps `settings` and, when given, `filters`.
fn rig_with(catalog: Arc<Catalog>, served: Vec<String>, settings: FontPickerSettings, filters: Option<FontFilters>) -> (Fixture, Rc<RefCell<Seen>>) {
rig_full(catalog, served, settings, filters, Vec::new(), None)
}
/// A picker with one host group (without a heading) per entry of `host`, showing the host row `current_host` as its
/// value when given.
fn rig_with_host(
catalog: Arc<Catalog>,
served: Vec<String>,
host: Vec<Vec<HostFontRow>>,
current_host: Option<String>,
) -> (Fixture, Rc<RefCell<Seen>>) {
rig_full(catalog, served, FontPickerSettings::default(), None, host, current_host)
}
fn rig_full(
catalog: Arc<Catalog>,
served: Vec<String>,
settings: FontPickerSettings,
filters: Option<FontFilters>,
host: Vec<Vec<HostFontRow>>,
current_host: Option<String>,
) -> (Fixture, Rc<RefCell<Seen>>) {
let seen = Rc::new(RefCell::new(Seen::default()));
let shown = Rc::clone(&seen);
let (mut settings, mut filters) = (settings, filters);
let mut fx = Fixture::new(move |ui| {
let mut seen = shown.borrow_mut();
let mut picker = FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog).settings(Bind::bound(&mut settings)).served(&served);
let groups: Vec<HostFontGroup<'_>> = host.iter().map(|rows| HostFontGroup::new(None, rows)).collect();
let mut picker = FontPicker::new("Font family", Bind::bound(&mut seen.family), &catalog)
.settings(Bind::bound(&mut settings))
.served(&served)
.host(&groups);
if let Some(filters) = filters.as_mut() {
picker = picker.filters(Bind::bound(filters));
}
if let Some(key) = &current_host {
picker = picker.current_host(key.clone());
}
let out = picker.show(ui);
match out.preview {
Preview::Shows(family) => seen.preview = Some(family),
@@ -74,6 +105,7 @@ fn rig_with(catalog: Arc<Catalog>, served: Vec<String>, settings: FontPickerSett
seen.picks.push((family, out.picked_style));
}
seen.rested.extend(out.rested);
seen.host_picks.extend(out.host_picked);
});
fx.in_room(Room::Window);
fx.settle();
@@ -90,6 +122,20 @@ fn present(fx: &Fixture, text: &str) -> bool {
fx.by_label(text).is_some() || fx.texts().iter().any(|painted| painted.text == text)
}
#[trial]
fn mixed_family_is_named_until_a_font_is_chosen() {
let catalog = catalog_of(&[INTER_REGULAR]);
let mut family = craft_behavior::Mixed::<String>::Mixed;
let mut fx = Fixture::new(move |ui| {
FontPicker::new("Font family", Bind::bound_mixed(&mut family), &catalog).show(ui);
});
fx.in_room(Room::Window);
fx.settle();
let field = fx.by_role(craft_ui::runtime::access::Role::COMBO_BOX).into_iter().next().expect("the family field");
let label = fx.tree().value_of(field.node).filter(|value| !value.is_empty()).expect("the mixed family has an accessible label");
assert!(present(&fx, label), "the accessible mixed label is also visible");
}
#[trial]
fn a_style_row_under_an_expanded_family_picks_family_and_style_once() {
let (mut fx, seen) = rig(catalog_of(&[INTER_REGULAR, INTER_SEMIBOLD]), vec![]);
@@ -196,6 +242,43 @@ fn a_preview_over_a_typed_query_keeps_the_query_and_the_list() {
assert!(present(&fx, "Ha"), "and the query stays");
}
#[trial]
fn a_host_row_pick_reports_its_key_and_leaves_the_family() {
let host = || {
vec![vec![
HostFontRow::face("document", "Document Sans", None),
HostFontRow::notice("Subset fonts can't take new text"),
HostFontRow::action("load", "Load font file"),
]]
};
let (mut fx, seen) = rig_with_host(catalog_of(&[INTER_REGULAR]), vec![], host(), None);
open(&mut fx);
let load = fx.by_label("Load font file").expect("the action row");
fx.click(&load);
fx.settle();
assert_eq!(seen.borrow().host_picks, ["load"], "the action row reports its key");
assert_eq!(seen.borrow().family, "", "a host pick writes no family");
assert!(seen.borrow().picks.is_empty(), "a host pick is no family pick and no recent family");
assert!(fx.by_label("Load font file").is_none(), "the list closed");
open(&mut fx);
let face = fx.by_label("Document Sans").expect("the face row");
fx.click(&face);
fx.settle();
assert_eq!(seen.borrow().host_picks, ["load", "document"], "the face row reports its key");
assert_eq!(seen.borrow().family, "", "a host face writes no family");
assert!(seen.borrow().picks.is_empty(), "a host face is no family pick");
// The closed field shows the host face; ArrowDown steps over the notice to the action row.
let (mut fx, seen) = rig_with_host(catalog_of(&[INTER_REGULAR]), vec![], host(), Some("document".to_owned()));
fx.key(Key::Tab, Modifiers::NONE);
fx.key(Key::ArrowDown, Modifiers::NONE);
fx.settle();
assert_eq!(seen.borrow().host_picks, ["load"], "the arrow skips the notice");
assert!(seen.borrow().picks.is_empty(), "and picks no family");
assert_eq!(seen.borrow().family, "");
}
#[trial]
fn a_click_on_the_focused_closed_field_selects_the_name_so_typing_replaces_it() {
let (mut fx, seen) = rig(catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]), vec![]);
+5 -3
View File
@@ -99,8 +99,9 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names (
`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")` or `None`; craft-ui's font
stack leads the Monospace family with the `mono` face. `EmbeddedFace` itself has `name()`,
`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()`,
`has_script(tag)`, `is_cjk()` and `weight()`.
## Document fonts
@@ -201,5 +202,6 @@ exact only for the catalogs it was cut to. It also reruns the build script when
One face per line, eight or nine fields separated by `" | "`; craft-fonts' `docs/integration.md`
defines them. Lines starting with `#` are comments. A file field ending in `#<n>` names face `n` of
a font collection (`fonts/noto-sans-cjk/NotoSansCJK.ttc#2`); without it the index is 0. The ninth
field, `role`, is `ui` on interface faces, `mono` on the monospace face and absent elsewhere. Fields
field, `role`, is `ui` on interface faces, `mono` on the monospace face, `signature` on the signature
face and absent elsewhere. Fields
after the ninth are ignored.
+3 -2
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, UI_ROLE, parse_manifest};
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, UI_ROLE, parse_manifest};
/// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`.
///
@@ -81,7 +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`]), `None` for a line without one.
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a
/// line without one.
pub role: Option<&'static str>,
}
+6 -2
View File
@@ -8,7 +8,8 @@
//! Blank lines and lines starting with `#` are skipped. `file` is relative to the checkout and may
//! end in `#<index>` to pick one face of a font collection (`.ttc`). The optional `role` is `ui` for
//! an interface face: a full Regular TrueType face that an app's build cuts to the characters of its
//! translation catalogs; or `mono` for the monospace face, which leads an app's Monospace family.
//! 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.
use std::fmt;
@@ -35,7 +36,7 @@ pub struct ManifestEntry {
/// Where the file came from.
pub source: String,
/// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the
/// monospace face, `None` when the line has no role.
/// monospace face, `Some("signature")` for the signature face, `None` when the line has no role.
pub role: Option<String>,
}
@@ -68,6 +69,9 @@ pub const UI_ROLE: &str = "ui";
/// The `role` of the monospace face (JetBrains Mono): the Monospace stack leads with the embedded face that has it.
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";
/// 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"];
+95 -15
View File
@@ -8,7 +8,7 @@
//! [`PickRequest::purpose`]. It applies the extension policy to a saved name before the app sees it,
//! and a Save answer ([`Picked::Saved`]) reports the file type picked in the panel.
use std::collections::{HashMap, VecDeque};
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
@@ -245,6 +245,18 @@ pub struct PickAnswer {
pub picked: Picked,
}
/// Why a file is written: a Save to the document's own place, or a Save As to a new one. A
/// service that hands the bytes to an embedding page passes it on, so the page can tell the two
/// apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WriteIntent {
/// Save to the place the document already has.
Save,
/// Save to a new place.
SaveAs,
}
/// Why a read or write failed. The message reads the same in every app (F15.06).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FileError {
@@ -299,8 +311,15 @@ pub trait Files: Send + Sync {
fn pending_pick(&self) -> Option<PendingPick>;
/// Reads the whole file at `path`.
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError>;
/// Writes atomically where the platform allows (temp file and rename).
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError>;
/// Writes atomically where the platform allows (temp file and rename). `Ok(true)` when a host page took the bytes
/// (a browser embedded in a page), `Ok(false)` when they were written here.
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError>;
/// Whether something already exists at `path`. `false` when the service has no file system to
/// check (a browser).
fn exists(&self, path: &Path) -> bool {
let _ = path;
false
}
/// The folder the last answered pick of `purpose` chose.
fn last_folder(&self, purpose: &str) -> Option<PathBuf>;
/// Queues a save of `bytes` as ticket `request`'s answer, taken with
@@ -312,6 +331,12 @@ pub trait Files: Send + Sync {
fn can_pick(&self) -> bool;
/// Whether [`save`](Files::save) hands the bytes to the browser instead of writing a path.
fn browser_saves(&self) -> bool;
/// Answers the next pick, or the oldest pick still open, with `picked` instead of showing a
/// picker; the answer arrives through [`take_answer`](Files::take_answer) on a later pass.
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
let _ = picked;
Err(FileError::Unsupported)
}
}
/// No pickers (every pick answers `Cancelled`); reads and writes go to the file system. The
@@ -355,18 +380,30 @@ impl Files for NoPickFiles {
Err(FileError::Unsupported)
}
// No page to hand the bytes to: every intent writes the path, and no page took them.
#[cfg(not(target_arch = "wasm32"))]
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
let tmp = path.with_extension(format!("{}.tmp", path.extension().and_then(|e| e.to_str()).unwrap_or("")));
std::fs::write(&tmp, bytes).map_err(|e| with_path(e, path))?;
std::fs::rename(&tmp, path).map_err(|e| with_path(e, path))
std::fs::rename(&tmp, path).map_err(|e| with_path(e, path))?;
Ok(false)
}
#[cfg(target_arch = "wasm32")]
fn write(&self, _path: &Path, _bytes: &[u8]) -> Result<(), FileError> {
fn write(&self, _path: &Path, _bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
Err(FileError::Unsupported)
}
#[cfg(not(target_arch = "wasm32"))]
fn exists(&self, path: &Path) -> bool {
path.exists()
}
#[cfg(target_arch = "wasm32")]
fn exists(&self, _path: &Path) -> bool {
false
}
fn last_folder(&self, _purpose: &str) -> Option<PathBuf> {
None
}
@@ -415,6 +452,10 @@ struct ScriptState {
open: Vec<(PickId, PickRequest)>,
answered: Vec<PickAnswer>,
files: HashMap<PathBuf, Vec<u8>>,
/// Paths a write to is refused ([`ScriptedFiles::failing_writes`]).
refused: HashSet<PathBuf>,
/// The path of every write that took, in order ([`ScriptedFiles::written`]).
written: Vec<PathBuf>,
/// The bytes of the saves not answered yet, written to the chosen path with the answer.
saves: HashMap<PickId, Vec<u8>>,
/// Stands in for a browser host.
@@ -447,8 +488,9 @@ impl ScriptedFiles {
}
/// A service whose picks stay open until the test answers them with
/// [`answer`](ScriptedFiles::answer) or [`answer_to`](ScriptedFiles::answer_to): the state of
/// a user who has the dialog on screen.
/// [`answer`](ScriptedFiles::answer), [`answer_to`](ScriptedFiles::answer_to) or
/// [`Files::answer_next`]: the state of a user who has the dialog on screen. A pick that finds
/// an answer queued takes it at once.
pub fn held() -> Self {
let files = Self::default();
files.state().held = true;
@@ -481,6 +523,14 @@ impl ScriptedFiles {
self
}
/// Refuses every write to `path`: [`Files::write`] returns [`FileError::PermissionDenied`] for it and keeps the
/// bytes it had. Other paths write as before.
#[must_use]
pub fn failing_writes(self, path: impl Into<PathBuf>) -> Self {
self.state().refused.insert(path.into());
self
}
/// Queues the answer of the next pick that has none yet.
pub fn queue(&self, picked: Picked) {
self.state().queued.push_back(picked);
@@ -518,6 +568,12 @@ impl ScriptedFiles {
self.state().files.get(path).cloned()
}
/// The path of every write so far that took, in the order of the writes: a path written twice is listed twice. A
/// refused write and a file put there with [`with_file`](ScriptedFiles::with_file) are not listed.
pub fn written(&self) -> Vec<PathBuf> {
self.state().written.clone()
}
fn state(&self) -> std::sync::MutexGuard<'_, ScriptState> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
@@ -538,12 +594,12 @@ impl ScriptedFiles {
}
let suggested = (state.save_suggested && request.kind == PickKind::Save).then(|| Self::suggested(&request));
state.asked.push(request.clone());
if state.held {
state.open.push((id, request));
return id;
let picked =
if state.held { state.queued.pop_front() } else { Some(suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled)) };
match picked {
Some(picked) => state.settle(id, request, picked),
None => state.open.push((id, request)),
}
let picked = suggested.or_else(|| state.queued.pop_front()).unwrap_or(Picked::Cancelled);
state.settle(id, request, picked);
id
}
}
@@ -575,8 +631,32 @@ impl Files for ScriptedFiles {
self.file(path).ok_or_else(|| FileError::NotFound(path.to_owned()))
}
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
self.state().files.insert(path.to_owned(), bytes.to_vec());
// Kept in memory whatever the intent; no page takes the bytes.
fn write(&self, path: &Path, bytes: &[u8], _intent: WriteIntent) -> Result<bool, FileError> {
let mut state = self.state();
if state.refused.contains(path) {
return Err(FileError::PermissionDenied(path.to_owned()));
}
state.files.insert(path.to_owned(), bytes.to_vec());
state.written.push(path.to_owned());
Ok(false)
}
fn exists(&self, path: &Path) -> bool {
self.state().files.contains_key(path)
}
/// Answers the oldest open pick of a [`held`](ScriptedFiles::held) service; otherwise the
/// answer is queued for the next pick. [`answer`](ScriptedFiles::answer) answers the newest
/// instead, so this does not go through it.
fn answer_next(&self, picked: Picked) -> Result<(), FileError> {
let mut state = self.state();
if state.held && !state.open.is_empty() {
let (id, request) = state.open.remove(0);
state.settle(id, request, picked);
} else {
state.queued.push_back(picked);
}
Ok(())
}
+62 -1
View File
@@ -12,7 +12,9 @@ use std::sync::Arc;
use craft_i18n::{I18n, Lang, Words};
pub use files::{FileError, FileFilter, Files, NoPickFiles, PendingPick, PickAnswer, PickId, PickKind, PickRequest, Picked, ScriptedFiles};
pub use files::{
FileError, FileFilter, Files, NoPickFiles, PendingPick, PickAnswer, PickId, PickKind, PickRequest, Picked, ScriptedFiles, WriteIntent,
};
#[cfg(not(target_arch = "wasm32"))]
pub use services::ThreadJobs;
pub use services::{AppInfo, Commands, InlineJobs, Jobs, ManualJobs, MemorySections, NoCommands, Section, SectionStore, Wake};
@@ -294,6 +296,65 @@ mod tests {
const APP: AppInfo = AppInfo { id: "test", name: "Test", version: "1.0" };
/// A write to a path set with `failing_writes` returns the refused-write error and keeps what the path held; every
/// other path writes: a refusal that wrote anyway, or that refused every path, would test a failed save on the
/// wrong path.
#[test]
fn failing_writes_refuse_only_their_path() {
let files = ScriptedFiles::new().with_file("/docs/a.pdf", b"old".to_vec()).failing_writes("/docs/a.pdf");
let refused = files.write(std::path::Path::new("/docs/a.pdf"), b"new", WriteIntent::Save);
assert_eq!(refused, Err(FileError::PermissionDenied("/docs/a.pdf".into())));
assert_eq!(files.file(std::path::Path::new("/docs/a.pdf")).as_deref(), Some(&b"old"[..]), "the refused write kept the old bytes");
assert_eq!(files.write(std::path::Path::new("/docs/b.pdf"), b"new", WriteIntent::Save), Ok(false));
assert_eq!(files.file(std::path::Path::new("/docs/b.pdf")).as_deref(), Some(&b"new"[..]));
}
/// The written paths list each write that took, in order, and nothing else: a list that took in a refused write or a
/// file the test put there would let "nothing was written outside the folder" fail, or pass, on the wrong paths.
#[test]
fn written_lists_the_writes_that_took_in_order() {
let files = ScriptedFiles::new().with_file("/docs/kept.pdf", b"old".to_vec()).failing_writes("/docs/refused.pdf");
for path in ["/out/b.pdf", "/docs/refused.pdf", "/out/a.pdf", "/out/b.pdf"] {
let _ = files.write(std::path::Path::new(path), b"new", WriteIntent::Save);
}
let written: Vec<std::path::PathBuf> = ["/out/b.pdf", "/out/a.pdf", "/out/b.pdf"].map(Into::into).into();
assert_eq!(files.written(), written);
}
/// `Files::exists` reports files already present or written through the service and ignores refused writes:
/// batch writers rely on it to pick a fresh name instead of replacing an existing file.
#[test]
fn exists_reports_present_and_written_files() {
let existing = std::path::Path::new("/batch/notes.pdf");
let missing = std::path::Path::new("/batch/new.pdf");
let refused = std::path::Path::new("/batch/refused.pdf");
let files = ScriptedFiles::new().with_file(existing, b"keep".to_vec()).failing_writes(refused);
assert!(files.exists(existing), "a pre-existing scripted file exists");
assert!(!files.exists(missing), "a path not in the service does not exist");
assert!(files.write(refused, b"no", WriteIntent::SaveAs).is_err());
assert!(!files.exists(refused), "a refused write does not create an entry");
assert_eq!(files.write(missing, b"ok", WriteIntent::SaveAs), Ok(false));
assert!(files.exists(missing), "an accepted write exists afterwards");
#[cfg(not(target_arch = "wasm32"))]
{
let dir = std::env::temp_dir().join(format!("craft-host-exists-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let on_disk = dir.join("present.pdf");
let absent = dir.join("absent.pdf");
let _ = std::fs::remove_file(&on_disk);
let _ = std::fs::remove_file(&absent);
let disk = NoPickFiles::default();
assert!(!disk.exists(&on_disk));
assert!(!disk.exists(&absent));
assert_eq!(disk.write(&on_disk, b"data", WriteIntent::SaveAs), Ok(false));
assert!(disk.exists(&on_disk), "NoPickFiles reports a written file on disk");
assert!(!disk.exists(&absent), "NoPickFiles reports a missing path as absent");
let _ = std::fs::remove_file(&on_disk);
let _ = std::fs::remove_dir(&dir);
}
}
#[cfg(feature = "ui")]
#[test]
fn installed_host_survives_a_memory_reset() {
+41 -12
View File
@@ -16,6 +16,7 @@
//! On wasm32 there are no threads: [`QueueOptions::default_lanes`] is 0 and the owner calls
//! [`JobQueue::run_inline`] once per pass.
use std::cmp::Reverse;
use std::collections::VecDeque;
use std::hash::Hash;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -73,6 +74,22 @@ pub struct QueueOptions {
pub lanes: usize,
/// The name each lane's job is spawned with (a thread name with `ThreadJobs`).
pub name: &'static str,
/// Which of two jobs of equal priority runs first.
pub order: QueueOrder,
}
/// Which job runs first among jobs of equal priority: the one that arrived last or first. Priority
/// always decides first; the order only breaks ties.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum QueueOrder {
/// The newest job runs first: what was asked for last is what the user looks at now (a
/// thumbnail scrolled into view, the latest slider value).
#[default]
NewestFirst,
/// The oldest job runs first: every job is wanted and arrival order is the user's order (files
/// opened one after another).
OldestFirst,
}
impl QueueOptions {
@@ -89,10 +106,10 @@ impl QueueOptions {
}
impl Default for QueueOptions {
/// [`default_lanes`](QueueOptions::default_lanes) lanes named `"craft-queue"`.
/// [`default_lanes`](QueueOptions::default_lanes) lanes named `"craft-queue"`, newest first.
fn default() -> Self {
// new: the default every library queue starts from.
Self { lanes: Self::default_lanes(), name: "craft-queue" }
Self { lanes: Self::default_lanes(), name: "craft-queue", order: QueueOrder::default() }
}
}
@@ -124,7 +141,7 @@ type QueueJob<R> = Box<dyn FnOnce(&Cancel) -> R + Send>;
struct Queued<K, R> {
key: K,
priority: Priority,
/// Submission order: among equal priorities the newest runs first.
/// Submission order: among equal priorities [`QueueOrder`] picks the newest or the oldest.
seq: u64,
job: QueueJob<R>,
}
@@ -157,6 +174,8 @@ struct State<K, R> {
lanes_alive: usize,
seq: u64,
stopped: bool,
/// The tie order of [`best`](Self::best), from the queue's options.
order: QueueOrder,
}
struct Shared<K, R> {
@@ -186,14 +205,15 @@ impl<K, R> State<K, R> {
}
impl<K: Clone + Eq, R> State<K, R> {
/// Index of the best waiting job whose key is not running: highest priority, then newest.
/// Index of the best waiting job whose key is not running: highest priority, then the newest
/// or the oldest as [`QueueOrder`] says.
fn best(&self) -> Option<usize> {
self.queued
.iter()
.enumerate()
.filter(|(_, q)| !self.running.iter().any(|r| r.key == q.key))
.max_by_key(|(_, q)| (q.priority, q.seq))
.map(|(i, _)| i)
let startable = self.queued.iter().enumerate().filter(|(_, q)| !self.running.iter().any(|r| r.key == q.key));
match self.order {
QueueOrder::NewestFirst => startable.max_by_key(|(_, q)| (q.priority, q.seq)),
QueueOrder::OldestFirst => startable.max_by_key(|(_, q)| (q.priority, Reverse(q.seq))),
}
.map(|(i, _)| i)
}
/// Moves the best startable job to `running` and returns it.
@@ -307,7 +327,8 @@ impl<K: Clone + Eq + Send + 'static, R: Send + 'static> Shared<K, R> {
/// replaces a queued job of the same key, so scrolling or a slider drag never builds a backlog.
/// A key runs one job at a time: a key's next job waits until its running one ends (overlapping
/// renders of one picture are mostly thrown away).
/// - **Order.** Highest [`Priority`] first; among equal priorities the newest first.
/// - **Order.** Highest [`Priority`] first; among equal priorities the newest first, or the oldest
/// with [`QueueOrder::OldestFirst`] ([`QueueOptions::order`]).
/// [`reprioritize`](Self::reprioritize) re-ranks the waiting jobs or drops them; dropping a key
/// whose job runs sets its [`Cancel`] and its result is never delivered.
/// - **Lanes.** At most [`QueueOptions::lanes`] jobs run at once, each started through the
@@ -343,7 +364,15 @@ impl<K: Clone + Eq + Hash + Send + 'static, R: Send + 'static> JobQueue<K, R> {
/// after each finished job. No lane starts before the first [`submit`](Self::submit).
pub fn new(jobs: Arc<dyn Jobs>, wake: Wake, options: QueueOptions) -> Self {
// new: lanes are spawned on demand by `submit` and by a lane that ends with work waiting.
let state = State { queued: Vec::new(), running: Vec::new(), finished: VecDeque::new(), lanes_alive: 0, seq: 0, stopped: false };
let state = State {
queued: Vec::new(),
running: Vec::new(),
finished: VecDeque::new(),
lanes_alive: 0,
seq: 0,
stopped: false,
order: options.order,
};
Self { shared: Arc::new(Shared { state: Mutex::new(state), ended: Condvar::new(), jobs, wake, options }) }
}
+49 -3
View File
@@ -5,7 +5,7 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::queue::{Cancel, Finished, JobQueue, Priority, QueueOptions};
use crate::queue::{Cancel, Finished, JobQueue, Priority, QueueOptions, QueueOrder};
use crate::{ManualJobs, Wake};
fn queue(lanes: usize) -> (JobQueue<&'static str, &'static str>, Arc<ManualJobs>, Arc<AtomicUsize>) {
@@ -15,10 +15,24 @@ fn queue(lanes: usize) -> (JobQueue<&'static str, &'static str>, Arc<ManualJobs>
let wake = Wake::new(move || {
counter.fetch_add(1, Ordering::Relaxed);
});
let queue = JobQueue::new(jobs.clone(), wake, QueueOptions { lanes, name: "test" });
let queue = JobQueue::new(jobs.clone(), wake, QueueOptions { lanes, name: "test", ..QueueOptions::default() });
(queue, jobs, wakes)
}
/// A queue without lanes in `order`: jobs run one at a time through `run_inline`.
fn inline_queue(order: QueueOrder) -> JobQueue<&'static str, &'static str> {
JobQueue::new(Arc::new(ManualJobs::new()), Wake::new(|| {}), QueueOptions { lanes: 0, name: "test", order })
}
/// Runs the waiting jobs one `run_inline(1)` at a time and returns their results in run order.
fn run_one_by_one(queue: &JobQueue<&'static str, &'static str>) -> Vec<&'static str> {
let mut ran = Vec::new();
while queue.run_inline(1) == 1 {
ran.extend(drain(queue));
}
ran
}
fn drain(queue: &JobQueue<&'static str, &'static str>) -> Vec<&'static str> {
std::iter::from_fn(|| queue.try_recv()).map(|Finished { result, .. }| result).collect()
}
@@ -88,7 +102,11 @@ fn queue_gives_back_a_lane_the_host_dropped() {
}
}
let jobs = Arc::new(Refusing(AtomicUsize::new(0), ManualJobs::new()));
let queue = JobQueue::<&'static str, &'static str>::new(jobs.clone(), Wake::new(|| {}), QueueOptions { lanes: 1, name: "test" });
let queue = JobQueue::<&'static str, &'static str>::new(
jobs.clone(),
Wake::new(|| {}),
QueueOptions { lanes: 1, name: "test", ..QueueOptions::default() },
);
queue.submit("a", Priority::VISIBLE, |_| "a");
jobs.0.store(1, Ordering::Relaxed);
queue.submit("b", Priority::VISIBLE, |_| "b");
@@ -113,3 +131,31 @@ fn queue_finish_runs_the_waiting_jobs_inline() {
done.sort_unstable();
assert_eq!(done, ["a", "b"], "each job ran once");
}
// Among equal priorities `OldestFirst` runs jobs in arrival order and the default runs the newest first; a tie rule
// flipped or ignored would reorder an app's file opens or its thumbnails.
#[test]
fn a_queue_ordered_oldest_first_runs_equal_priorities_in_arrival_order() {
let oldest = inline_queue(QueueOrder::OldestFirst);
let newest = inline_queue(QueueOrder::default());
for queue in [&oldest, &newest] {
queue.submit("one", Priority::NEAR, |_| "one");
queue.submit("two", Priority::NEAR, |_| "two");
queue.submit("three", Priority::NEAR, |_| "three");
}
assert_eq!(run_one_by_one(&oldest), ["one", "two", "three"]);
assert_eq!(run_one_by_one(&newest), ["three", "two", "one"]);
}
// Priority decides before arrival in both orders: background work submitted first never runs before visible work
// submitted later, nor does newer background work outrank older visible work.
#[test]
fn a_higher_priority_runs_before_a_lower_one_in_either_order() {
for order in [QueueOrder::NewestFirst, QueueOrder::OldestFirst] {
let queue = inline_queue(order);
queue.submit("background", Priority::BACKGROUND, |_| "background");
queue.submit("visible", Priority::VISIBLE, |_| "visible");
queue.submit("near", Priority::NEAR, |_| "near");
assert_eq!(run_one_by_one(&queue), ["visible", "near", "background"], "{order:?}");
}
}
+38 -8
View File
@@ -250,6 +250,9 @@ pub enum NameLength {
Narrow,
/// `Sat`, `Oct`.
Abbreviated,
/// `Sa`: a weekday's two-letter name, calendar column heads where there is room for two letters. A month takes
/// its abbreviation.
Short,
/// `Saturday`, `October`.
Wide,
}
@@ -274,6 +277,8 @@ pub struct DateFormat {
hour_cycle: Option<crate::HourCycle>,
/// Write `0`–`9` whatever the locale's digits are.
latin_digits: bool,
/// The day a week starts on when the app sets one apart from the locale.
week_start: Option<Weekday>,
/// Formatters and names, built on first use and shared by clones.
cache: Arc<Cache>,
/// Unique per format built; a clone keeps it (`generation`).
@@ -314,12 +319,12 @@ impl Formatter {
}
}
/// Standalone month and weekday names, indexed by [`NameLength`] (narrow, abbreviated, wide)
/// Standalone month and weekday names, indexed by [`NameLength`] (narrow, abbreviated, short, wide)
/// and then by month (January first) or weekday (Monday first).
#[derive(Debug)]
struct Names {
months: [[String; 12]; 3],
weekdays: [[String; 7]; 3],
months: [[String; 12]; 4],
weekdays: [[String; 7]; 4],
}
/// Which field comes first, second and third in a numeric date.
@@ -380,6 +385,7 @@ impl DateFormat {
locale: region.time.clone(),
hour_cycle: region.hour_cycle,
latin_digits: false,
week_start: None,
cache: Arc::default(),
generation: crate::words::next_generation(),
}
@@ -397,6 +403,12 @@ impl DateFormat {
self.generation
}
/// This format with weeks starting on `day` in place of the region's. It lays weeks out
/// differently, so it is a new [`generation`](Self::generation).
pub fn with_first_weekday(self, day: Weekday) -> DateFormat {
DateFormat { week_start: Some(day), generation: crate::words::next_generation(), ..self }
}
/// The format for a locale tag (`de-CH`), with the locale's clock.
pub fn from_tag(tag: &str) -> DateFormat {
Self::new(&Region::from_tag(tag))
@@ -516,13 +528,13 @@ impl DateFormat {
let formatted = names.load_for_pattern(&provider, &pattern).ok()?.format(&at);
Some(formatted.try_write_to_string().map_or_else(|(_, text)| text.into_owned(), |text| text.into_owned()))
};
let months = ["LLLLL", "LLL", "LLLL"].map(|pattern| {
let months = ["LLLLL", "LLL", "LLL", "LLLL"].map(|pattern| {
std::array::from_fn(|i| name(pattern, CalendarDate { year: 2026, month: i as u8 + 1, day: 1 }).unwrap_or_default())
});
// 2026-10-26 is a Monday.
let weekdays = ["ccccc", "ccc", "cccc"].map(|pattern| {
std::array::from_fn(|i| name(pattern, CalendarDate { year: 2026, month: 10, day: 26 + i as u8 }).unwrap_or_default())
});
// 2026-10-26 is a Monday; the week runs on into November (October has 31 days).
let monday = CalendarDate { year: 2026, month: 10, day: 26 };
let weekdays = ["ccccc", "ccc", "cccccc", "cccc"]
.map(|pattern| std::array::from_fn(|i| name(pattern, monday.add_days(i as i64)).unwrap_or_default()));
Some(Names { months, weekdays })
})
.as_ref()
@@ -573,6 +585,9 @@ impl DateFormat {
/// The day a week starts on in the region: Sunday in the United States, Monday in most of
/// Europe, Saturday in parts of the Middle East.
pub fn first_weekday(&self) -> Weekday {
if let Some(day) = self.week_start {
return day;
}
let first = self.cache.first_weekday.get_or_init(|| {
let provider = data::dates_provider()?;
let locale = self.icu_locale(false);
@@ -781,4 +796,19 @@ mod tests {
assert_eq!(jan31.add_months(-2), CalendarDate::new(2027, 11, 30).unwrap());
assert_eq!(saturday.add_days(1), CalendarDate::new(2026, 11, 1).unwrap());
}
// Sunday's name was blank (the table asked for 2026-10-32): every weekday has a name at every length, and the short
// length is two letters in English.
#[test]
fn every_weekday_has_a_name_at_every_length() {
let dates = DateFormat::from_tag("en-US");
for day in Weekday::ALL {
for length in [NameLength::Narrow, NameLength::Abbreviated, NameLength::Short, NameLength::Wide] {
assert!(!dates.weekday_name(day, length).is_empty(), "{day:?} {length:?}");
}
}
assert_eq!(dates.weekday_name(Weekday::Sunday, NameLength::Short), "Su");
assert_eq!(dates.weekday_name(Weekday::Monday, NameLength::Short), "Mo");
assert_eq!(dates.month_name(11, NameLength::Short), "Nov");
}
}
+14 -1
View File
@@ -24,11 +24,14 @@ use icu_normalizer::DecomposingNormalizerBorrowed;
use icu_properties::props::{GraphemeExtend, HangulSyllableType};
use icu_properties::{CodePointMapData, CodePointSetData};
use crate::scripts::{Direction, direction};
/// Folds text for one locale. Cheap to build and copy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Folder {
turkic: bool,
accents: bool,
rtl: bool,
}
impl Folder {
@@ -36,7 +39,11 @@ impl Folder {
/// or `zh-hant` (any case, `-` or `_`).
pub fn new(locale: &str) -> Folder {
let language = locale.split(['-', '_', '.', '@']).next().unwrap_or_default();
Folder { turkic: language.eq_ignore_ascii_case("tr") || language.eq_ignore_ascii_case("az"), accents: false }
Folder {
turkic: language.eq_ignore_ascii_case("tr") || language.eq_ignore_ascii_case("az"),
accents: false,
rtl: direction(locale) == Direction::Rtl,
}
}
/// Accents count: `é` no longer matches `e`, and a match can't end on a letter whose accent it
@@ -50,6 +57,12 @@ impl Folder {
self.turkic
}
/// Whether the locale writes right to left, by its main script ([`direction`]); a locale with no script data is
/// left to right.
pub(crate) fn rtl(&self) -> bool {
self.rtl
}
/// `s` folded, with the map back to `s`.
pub fn fold(&self, s: &str) -> Folded {
let nfkd = DecomposingNormalizerBorrowed::new_nfkd();
+32 -5
View File
@@ -5,7 +5,7 @@ use crate::fold::{Folded, Folder};
use std::ops::Range;
/// How well a text matches, best first: the derived order puts `Whole` before `Prefix` before `WordStart` before
/// `Contains`.
/// `Contains` before `AllWords`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Rank {
@@ -17,6 +17,8 @@ pub enum Rank {
WordStart,
/// The query occurs inside a word.
Contains,
/// Every word of a multi-word query occurs in the text, in any order (right-to-left locales only).
AllWords,
}
/// A text that matches the query.
@@ -25,7 +27,8 @@ pub enum Rank {
pub struct Match {
/// How well it matches.
pub rank: Rank,
/// Every occurrence of the query, as byte ranges of the text, in order.
/// Every occurrence of the query, as byte ranges of the text, in order; for `AllWords`, the first occurrence of
/// each word, sorted by start.
pub ranges: Vec<Range<usize>>,
}
@@ -34,12 +37,22 @@ pub struct Match {
pub struct Matcher {
folder: Folder,
query: Folded,
/// The folded words of a query of two or more words in a right-to-left locale, where a line typed or pasted
/// across directions often holds its words in another order; empty otherwise, so a left-to-right ranking is
/// the whole-run one.
words: Vec<Folded>,
}
impl Matcher {
/// A matcher for `query` with surrounding space ignored. An empty query matches every text.
pub fn new(folder: &Folder, query: &str) -> Matcher {
Matcher { folder: *folder, query: folder.fold(query.trim()) }
let query = query.trim();
let words: Vec<Folded> = if folder.rtl() {
query.split_whitespace().map(|word| folder.fold(word)).filter(|word| !word.as_str().is_empty()).collect()
} else {
Vec::new()
};
Matcher { folder: *folder, query: folder.fold(query), words: if words.len() > 1 { words } else { Vec::new() } }
}
/// Whether the query is empty.
@@ -52,8 +65,11 @@ impl Matcher {
if self.is_empty() {
return Some(Match { rank: Rank::Whole, ranges: Vec::new() });
}
let ranges: Vec<Range<usize>> = self.folder.fold(text).matches(&self.query).collect();
let first = ranges.first()?;
let folded = self.folder.fold(text);
let ranges: Vec<Range<usize>> = folded.matches(&self.query).collect();
let Some(first) = ranges.first().cloned() else {
return self.all_words(&folded);
};
let rank = if first.start == 0 && first.end == text.len() {
Rank::Whole
} else if first.start == 0 {
@@ -65,4 +81,15 @@ impl Matcher {
};
Some(Match { rank, ranges })
}
/// `AllWords` when every word of the query occurs in `folded`, with each word's first occurrence as source ranges.
fn all_words(&self, folded: &Folded) -> Option<Match> {
if self.words.is_empty() {
return None;
}
let mut ranges: Vec<Range<usize>> = self.words.iter().map(|word| folded.matches(word).next()).collect::<Option<_>>()?;
ranges.sort_by_key(|range| range.start);
ranges.dedup();
Some(Match { rank: Rank::AllWords, ranges })
}
}
+39
View File
@@ -388,3 +388,42 @@ fn read_system() -> Region {
fn read_system() -> Region {
Region::from_tag(&sys_locale::get_locale().unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))]
#[test]
fn each_locale_category_decides_its_own_part_and_lc_all_all_of_them() {
let env =
|pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned());
fn none() -> Option<String> {
None
}
// `LC_ALL` decides every part, `C` included.
let all = from_posix(env(&[("LC_ALL", "de_DE.UTF-8"), ("LC_PAPER", "en_US"), ("LC_TIME", "en_US"), ("LANG", "en_US")]), none);
assert_eq!(all, Region::from_tag("de_DE.UTF-8"));
assert_eq!(from_posix(env(&[("LC_ALL", "C"), ("LANG", "de_DE")]), none), Region::from_tag("C"));
// An empty `LC_ALL` is unset: each category decides its own part.
let split = from_posix(
env(&[
("LC_ALL", ""),
("LC_NUMERIC", "pl_PL"),
("LC_TIME", "en_GB"),
("LC_MEASUREMENT", "en_US"),
("LC_PAPER", "en_US"),
("LANG", "de_DE"),
]),
none,
);
assert_eq!((split.numbers.as_str(), split.time.as_str(), split.measurement, split.paper), ("pl-PL", "en-GB", Measurement::Us, Paper::Letter));
// `LANG` fills every category not set.
let lang = from_posix(env(&[("LC_PAPER", "en_US"), ("LANG", "de_DE")]), none);
assert_eq!((lang.numbers.as_str(), lang.time.as_str(), lang.measurement, lang.paper), ("de-DE", "de-DE", Measurement::Metric, Paper::Letter));
// `LANG` set to `C`, or unset, gives way to the platform's locale.
let platform = from_posix(env(&[("LANG", "C.UTF-8")]), || Some("en-CA".to_owned()));
assert_eq!((platform.numbers.as_str(), platform.measurement, platform.paper), ("en-CA", Measurement::Metric, Paper::Letter));
assert_eq!(from_posix(env(&[]), none), Region::default());
}
}
+97
View File
@@ -1,6 +1,7 @@
//! Tests for the i18n facade.
use super::*;
use crate::matcher::{Matcher, Rank};
use unicode_bidi::{BidiClass, bidi_class};
impl I18n {
@@ -219,3 +220,99 @@ fn lookup_parses_only_what_it_reaches() {
assert_eq!(i.t(Lang::PSEUDO, "Undo"), "⟦Undo⟧");
assert_eq!(i.parsed(), ["pt", "pt-br"]);
}
#[test]
fn words_in_any_order_match_after_a_whole_run() {
// "Delete page" in Arabic and Hebrew, queried with its two words the other way round.
for (locale, text, reversed, missing) in [("ar", "حذف صفحة", "صفحة حذف", "صفحة نسخ"), ("he", "מחק עמוד", "עמוד מחק", "עמוד העתק")]
{
let folder = Folder::new(locale);
let matcher = Matcher::new(&folder, reversed);
let found = matcher.score(text).map(|found| (found.rank, found.ranges));
assert_eq!(found, Some((Rank::AllWords, vec![0..6, 7..15])), "{locale}: each word's first occurrence, in text order");
let whole = matcher.score(reversed).map(|found| found.rank);
assert_eq!(whole, Some(Rank::Whole), "{locale}");
assert!(
Matcher::new(&folder, text).score(&format!("x {text}")).is_some_and(|run| run.rank < Rank::AllWords),
"{locale}: a whole run ranks first"
);
assert_eq!(Matcher::new(&folder, missing).score(text), None, "{locale}: every word must occur");
assert_eq!(Matcher::new(&Folder::new("en"), reversed).score(text), None, "{locale}: a left-to-right folder keeps the whole run");
}
}
#[test]
fn lookups_fall_back_to_the_english_row_then_the_source_by_context_and_id() {
let i = all(E).0;
let fr = lang(&i, "fr");
// The app's row comes before the shared one.
assert_eq!(i.t(fr, "Save"), "Sauvegarder");
assert_eq!(i.tc(fr, "menu", "Open"), "Ouvrir le menu");
assert_eq!(i.tc(fr, "no such context", "Open"), "Ouvrir", "a context with no row takes the plain row");
assert_eq!(i.get(fr, "no such context", "Open"), None, "get takes no other row");
assert_eq!(i.tid(fr, "file.save", "Save"), "Enregistrer le fichier");
assert_eq!(i.tid(fr, "no.such.id", "Open"), "Ouvrir", "an id with no row takes the row of its English label");
assert_eq!(i.tid(fr, "no.such.id", "No such label"), "No such label");
assert_eq!(i.t(fr, "no such label"), "no such label");
// A regional locale falls back to its language, and only then to the source.
let pt_br = lang(&i, "pt-br");
assert_eq!(i.t(pt_br, "Save"), "Salvar");
assert_eq!(i.t(pt_br, "Undo"), "Desfazer");
assert_eq!(i.t(pt_br, "Open"), "Open");
assert_eq!(i.t(Lang::EN, "Save"), "Save");
}
#[test]
fn catalog_problems_are_reported_and_escapes_kept() {
static C: &Embedded = &[(
"ja",
"# c\r\n\tLine\\nTab\\tPath\\\\\tOther\\nTab\\tPath\\\\\r\nweight\tLight\tThin\r\ntheme\tLight\tPale\r\nno tabs here\n\tonly\n\ta\tb\tc\textra\n\t\tempty source\n\tOpen…\tOpen\n\tok\tはい\n\tok\tまた\n\tBad\\q\tx\n",
"",
)];
let (i, problems) = all(C);
assert!(problems.is_empty(), "rows are checked when the locale is first read: {problems:?}");
let ja = lang(&i, "ja");
assert_eq!(i.t(ja, "Line\nTab\tPath\\"), "Other\nTab\tPath\\");
assert_eq!(i.tc(ja, "weight", "Light"), "Thin");
assert_eq!(i.tc(ja, "theme", "Light"), "Pale");
assert_eq!(i.t(ja, "ok"), "はい", "of a row defined twice, the first is kept");
assert_eq!(i.t(ja, "Open…"), "Open…", "a row that drops the ellipsis is skipped");
let found = i.check_all();
let lines: Vec<&str> = found.iter().filter_map(|p| p.strip_prefix("ja/common: line ")).filter_map(|p| p.split(':').next()).collect();
assert_eq!(lines, ["5", "6", "7", "8", "9", "11", "12"], "{found:?}");
}
#[test]
fn plural_forms_follow_cldr_for_every_offered_language() {
static C: &Embedded = &[
("fr", "@plural\t{n} file|{n} files\tun {n}|autre {n}\n", ""),
("ru", "@plural\t{n} file|{n} files\tone {n}|few {n}|many {n}\n", ""),
("ja", "@plural\t{n} file|{n} files\tother {n}\n", ""),
("ar", "@plural\t{n} file|{n} files\tzero {n}|one {n}|two {n}|few {n}|many {n}|other {n}\n", ""),
("pl", "@plural\t{n} file|{n} files\tone {n}|few {n}|many {n}\n", ""),
("pt", "@plural\t{n} file|{n} files\tum {n}|outro {n}\n", ""),
("pt-br", "@plural\t{n} file|{n} files\tum {n}|outro {n}\n", ""),
("de", "@plural\t{n} file|{n} files\teins {n}|zwei {n}|drei {n}\n", ""),
];
let i = all(C).0;
let counted = |code: &str, n: u64| i.trn_plain(lang(&i, code), n, "{n} file", "{n} files");
for (code, expected) in [
("fr", &[(0, "un 0"), (1, "un 1"), (2, "autre 2"), (1_000_000, "autre 1000000")][..]),
("ru", &[(1, "one 1"), (2, "few 2"), (5, "many 5"), (11, "many 11"), (21, "one 21"), (22, "few 22"), (112, "many 112")]),
("ja", &[(1, "other 1"), (2, "other 2")]),
("ar", &[(0, "zero 0"), (1, "one 1"), (2, "two 2"), (3, "few 3"), (11, "many 11"), (100, "other 100"), (103, "few 103")]),
("pl", &[(1, "one 1"), (2, "few 2"), (5, "many 5"), (12, "many 12"), (22, "few 22")]),
// CLDR's `pt` is Brazilian, where 0 is singular; Portugal's is not.
("pt", &[(0, "outro 0"), (1, "um 1"), (2, "outro 2")]),
("pt-br", &[(0, "um 0"), (1, "um 1"), (2, "outro 2")]),
// German has two forms: the three-form row is skipped and the English shows.
("de", &[(1, "1 file"), (2, "2 files")]),
] {
for &(n, want) in expected {
assert_eq!(counted(code, n), want, "{code}: {n}");
}
}
let found = i.check_all();
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].starts_with("de/common: line 1: expected 2"), "{found:?}");
}
+37 -11
View File
@@ -128,6 +128,22 @@ pub struct PreviewMesh {
}
impl PreviewMesh {
/// Clips to a quadrilateral in normalized source texture coordinates.
#[must_use]
pub fn clipped_to_source(self, quad: [Point; 4], extent: [f32; 2]) -> PreviewMesh {
if !extent.iter().all(|v| v.is_finite() && *v > 0.0) {
return PreviewMesh::default();
}
let quad = quad.map(|p| Point::new(p.x * f64::from(extent[0]), p.y * f64::from(extent[1])));
clip_quad(self, quad, true)
}
/// Clips the preview to a convex quadrilateral in document space.
#[must_use]
pub fn clipped_to_quad(self, quad: [Point; 4]) -> PreviewMesh {
clip_to_quad(self, quad)
}
/// The mesh clipped to a document of `canvas` pixels: triangles past its edges are cut in
/// document space, also under a turned view.
#[must_use]
@@ -325,10 +341,25 @@ pub(super) fn front_vertices(h: &Homography, n: usize) -> Vec<bool> {
/// `mesh` with every triangle cut to the document `canvas` (0, 0)–(width, height) in document
/// space, so the cut follows a turned view.
pub(super) fn clip_to_canvas(mesh: PreviewMesh, canvas: [u32; 2]) -> PreviewMesh {
// pc: crates/ui-egui/src/tools/transform_tool/draw.rs:395 (`clip_to_canvas`).
let size = (f64::from(canvas[0]), f64::from(canvas[1]));
let inside = |p: &Point| p.x >= 0.0 && p.y >= 0.0 && p.x <= size.0 && p.y <= size.1;
if mesh.points.iter().all(inside) {
let (w, h) = (f64::from(canvas[0]), f64::from(canvas[1]));
clip_to_quad(mesh, [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)])
}
fn clip_to_quad(mesh: PreviewMesh, quad: [Point; 4]) -> PreviewMesh {
clip_quad(mesh, quad, false)
}
fn clip_quad(mesh: PreviewMesh, quad: [Point; 4], source: bool) -> PreviewMesh {
let cross = |a: Point, b: Point, p: Point| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
let area: f64 = (0..4).map(|i| quad[i].x * quad[(i + 1) % 4].y - quad[(i + 1) % 4].x * quad[i].y).sum();
if !area.is_finite() || area.abs() < 1e-12 || (0..4).any(|i| cross(quad[i], quad[(i + 1) % 4], quad[(i + 2) % 4]) * area < 0.0) {
return PreviewMesh::default();
}
let distance = |edge: usize, p: Point| cross(quad[edge], quad[(edge + 1) % 4], p) * area.signum();
let inside = |p: &Point| (0..4).all(|edge| distance(edge, *p) >= 0.0);
let entirely_inside =
if source { mesh.uv.iter().all(|uv| inside(&Point::new(f64::from(uv[0]), f64::from(uv[1])))) } else { mesh.points.iter().all(inside) };
if entirely_inside {
return mesh;
}
#[derive(Clone, Copy)]
@@ -344,14 +375,9 @@ pub(super) fn clip_to_canvas(mesh: PreviewMesh, canvas: [u32; 2]) -> PreviewMesh
let mut out = PreviewMesh::default();
for tri in mesh.indices.as_chunks::<3>().0 {
let Some(mut poly) = tri.iter().map(|&k| vertex(k)).collect::<Option<Vec<_>>>() else { continue };
// Sutherland–Hodgman against the four canvas edges (`dist` >= 0 is the canvas side).
// Clip each triangle against the four edges, interpolating its texture coordinates.
for edge in 0..4 {
let dist = |v: &Vertex| match edge {
0 => v.point.x,
1 => size.0 - v.point.x,
2 => v.point.y,
_ => size.1 - v.point.y,
};
let dist = |v: &Vertex| distance(edge, if source { Point::new(f64::from(v.uv[0]), f64::from(v.uv[1])) } else { v.point });
let mut next = Vec::with_capacity(poly.len() + 2);
for (k, a) in poly.iter().enumerate() {
let Some(b) = poly.get((k + 1) % poly.len()) else { continue };
+31 -5
View File
@@ -117,6 +117,14 @@ pub struct TransformPreview<'a> {
/// The document's size in pixels: nothing is drawn past its edges.
#[prop]
clip: Option<[u32; 2]>,
/// A convex quadrilateral in document space limiting the visible preview.
#[prop]
clip_quad: Option<[Point; 4]>,
/// A convex quadrilateral in normalized source coordinates, clipped before transformation.
/// With a source clip the plain mesh is shown, since the styled composite includes effects
/// outside the source and cannot be clipped in source space after compositing.
#[prop]
source_clip: Option<[Point; 4]>,
/// The monitor conversion of the displayed upload; the mip levels stay raw.
#[prop]
display: Option<&'a PreviewDisplay>,
@@ -143,6 +151,8 @@ impl<'a> TransformPreview<'a> {
opacity: 1.0,
nearest: false,
clip: None,
clip_quad: None,
source_clip: None,
display: None,
styled: None,
dragging: false,
@@ -193,8 +203,8 @@ impl Component for TransformPreview<'_> {
let scale = map.source_scale(self.textures.size());
let tint = Color32::from_white_alpha((self.opacity.clamp(0.0, 1.0) * 255.0).round() as u8);
let styled = match (&self.styled, &map, self.clip) {
(Some((preview, source)), PreviewMap::Quad(quad), Some(canvas)) => {
let styled = match (&self.styled, &map, self.clip, self.source_clip) {
(Some((preview, source)), PreviewMap::Quad(quad), Some(canvas), None) => {
let mut frame = StyledFrame::new(self.textures, *quad, canvas, zoom);
frame.quad_scale = scale;
frame.nearest = self.nearest;
@@ -212,12 +222,16 @@ impl Component for TransformPreview<'_> {
uv: corners.iter().map(|c| [c.2, c.3]).collect(),
indices: vec![0, 1, 2, 0, 2, 3],
};
add_mesh(&painter, mesh, texture, Color32::from_gray(u8::MAX), self.clip, &view);
add_mesh(&painter, mesh, texture, Color32::from_gray(u8::MAX), self.clip, self.clip_quad, &view);
} else {
let choice = PreviewTextures::choose(zoom, scale, self.nearest);
let Some((texture, uv)) = self.textures.pick(&ctx, choice, self.display) else { return };
let mesh = map.build(view.zoom * f64::from(device), uv);
add_mesh(&painter, mesh, texture, tint, self.clip, &view);
let mesh = match self.source_clip {
Some(clip) => mesh.clipped_to_source(clip, uv),
None => mesh,
};
add_mesh(&painter, mesh, texture, tint, self.clip, self.clip_quad, &view);
}
if let Some(first) = first {
space.paint_picture(&ctx, first.take_after(&ctx));
@@ -234,11 +248,23 @@ impl Component for TransformPreview<'_> {
}
/// `mesh` clipped to the canvas in document space, mapped through `view` and added to the painter.
fn add_mesh(painter: &ContentPainterCx<'_>, mesh: PreviewMesh, texture: TextureId, tint: Color32, canvas: Option<[u32; 2]>, view: &CanvasView) {
fn add_mesh(
painter: &ContentPainterCx<'_>,
mesh: PreviewMesh,
texture: TextureId,
tint: Color32,
canvas: Option<[u32; 2]>,
quad: Option<[Point; 4]>,
view: &CanvasView,
) {
let mesh = match canvas {
Some(canvas) => clip_to_canvas(mesh, canvas),
None => mesh,
};
let mesh = match quad {
Some(quad) => mesh.clipped_to_quad(quad),
None => mesh,
};
let mut out = Mesh::with_texture(texture);
out.vertices =
mesh.points.iter().zip(&mesh.uv).map(|(p, uv)| Vertex { pos: view.to_screen(*p), uv: egui::pos2(uv[0], uv[1]), color: tint }).collect();
@@ -67,6 +67,32 @@ fn unit_quad() -> [Point; 4] {
[pt(0.0, 0.0), pt(100.0, 0.0), pt(100.0, 100.0), pt(0.0, 100.0)]
}
#[trial]
fn source_clip_moves_with_the_preview_and_preserves_texture_coordinates() {
let clip = [pt(0.0, 0.0), pt(1.0, 0.0), pt(1.0, 0.5), pt(0.0, 0.5)];
let moved = [pt(20.0, 40.0), pt(120.0, 40.0), pt(120.0, 140.0), pt(20.0, 140.0)];
let mesh = PreviewMap::quad(moved).build(1.0, [0.8, 0.6]).clipped_to_source(clip, [0.8, 0.6]);
assert!(!mesh.indices.is_empty());
for &index in &mesh.indices {
let p = mesh.points[index as usize];
let uv = mesh.uv[index as usize];
assert!(p.y <= 90.001, "{p:?}");
assert!((f64::from(uv[1]) / 0.6 - (p.y - 40.0) / 100.0).abs() < 1e-5);
}
}
/// A clipped preview retains texture coordinates where its frame cuts the image.
#[trial]
fn a_preview_clipped_to_a_frame_keeps_its_texture_coordinates() {
let quad = [pt(25.0, 20.0), pt(75.0, 20.0), pt(75.0, 80.0), pt(25.0, 80.0)];
let mesh = PreviewMap::quad(unit_quad()).build(1.0, [1.0, 1.0]).clipped_to_quad(quad);
assert!(!mesh.indices.is_empty());
for (p, uv) in mesh.points.iter().zip(&mesh.uv) {
assert!(p.x >= 24.999 && p.x <= 75.001 && p.y >= 19.999 && p.y <= 80.001, "{p:?}");
assert!((f64::from(uv[0]) - p.x / 100.0).abs() < 1e-5 && (f64::from(uv[1]) - p.y / 100.0).abs() < 1e-5);
}
}
// A Distort dragged past the horizon leaves the cells with a corner on the far side out of the mesh; the cells in
// front stay.
#[trial]
+2 -2
View File
@@ -9,7 +9,7 @@ pub(in crate::ui::panel) use map::start_rename;
pub(in crate::ui::panel) use rows::{LayerRows, ToggleSweeps, reveal_plan, thumb_click_replaces_select};
use rows::{RevealPlan, list_selection};
use craft_behavior::{ColumnWidth, IconId};
use craft_behavior::{ColumnWidth, CopyKeys, IconId};
use craft_keymap::Mods;
use craft_ui::contract::{
Bind, CollectionEvent, ColumnSpec, DropAt, DropKind, DropPlace, ListDrag, PendingDrop, Props as _, ReorderRule, ShowCollection as _, ToggleColumn,
@@ -70,7 +70,7 @@ pub(super) fn show_body<T: LayerTree>(
let mut list = List::new(cx.words.list.clone())
.id(cx.list)
.tree(true)
.reorder(ReorderRule::new().into_groups().copy_with_alt())
.reorder(ReorderRule::new().into_groups().copy_with(CopyKeys::Alt))
.allow_empty(true)
.deletable(cx.deletable)
.rename(true)
+21 -2
View File
@@ -82,6 +82,8 @@ pub struct MenuBarUi<'a> {
preferred: &'a [(&'a str, char)],
keyboard: Option<bool>,
help_search: bool,
icons: bool,
compact: bool,
}
/// Every input of the bar's view.
@@ -93,12 +95,14 @@ struct BarProps<'a> {
keyboard: bool,
help: Option<usize>,
label: Label,
icons: bool,
compact: bool,
}
impl<'a> MenuBarUi<'a> {
/// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]).
pub fn new(bar: &'a Tracked<MenuBar>) -> MenuBarUi<'a> {
MenuBarUi { bar, target: None, preferred: &[], keyboard: None, help_search: false }
MenuBarUi { bar, target: None, preferred: &[], keyboard: None, help_search: false, icons: true, compact: false }
}
}
@@ -133,6 +137,19 @@ impl<'a> MenuBarUi<'a> {
self
}
/// Whether the rows show their commands' icons (on by default). Off, the menus are text only and their rows a
/// line shorter, as a classic menu bar's.
pub fn icons(mut self, on: bool) -> MenuBarUi<'a> {
self.icons = on;
self
}
/// Whether the rows are a line of text tall instead of a control's height (off by default): a dense classic menu.
pub fn compact(mut self, on: bool) -> MenuBarUi<'a> {
self.compact = on;
self
}
/// Draws the bar and its open menu. Disabled rows never run. A chosen item is a fired command in the frame's
/// output; [`Builtin::Quit`] and [`Builtin::Minimize`] act on
/// the root window instead.
@@ -147,6 +164,8 @@ impl<'a> MenuBarUi<'a> {
keyboard: self.keyboard.unwrap_or(target != Target::Mac),
help,
label: env.words::<BarWords>().label.clone(),
icons: self.icons,
compact: self.compact,
};
MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, opened: false })
}
@@ -154,7 +173,7 @@ impl<'a> MenuBarUi<'a> {
/// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows.
fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput {
let rows = Rows::new(props.target).preferred(props.preferred);
let rows = Rows::new(props.target).preferred(props.preferred).icons(props.icons).compact(props.compact);
let env = Env::of(ui);
let os = env.view().shell().os;
// The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it.
+1
View File
@@ -17,6 +17,7 @@ fn build() -> MenuBar {
vec![
item("file.new", "New").into(),
Node::submenu("Open Recent", vec![item("file.recent.a", "notes.txt").into()]),
Node::submenu("Export", vec![item("file.export.pdf", "PDF").into()]).enabled(false),
Node::Separator,
item("file.revert", "Revert").enabled(false).into(),
],
+19 -5
View File
@@ -60,11 +60,25 @@ pub(crate) struct BarLabels {
pub(crate) struct Rows<'a> {
target: Target,
preferred: &'a [(&'a str, char)],
/// Whether rows show their command's icon.
icons: bool,
/// Whether rows are a text line tall.
compact: bool,
}
impl<'a> Rows<'a> {
pub(crate) fn new(target: Target) -> Self {
Rows { target, preferred: &[] }
Rows { target, preferred: &[], icons: true, compact: false }
}
pub(crate) fn icons(mut self, on: bool) -> Self {
self.icons = on;
self
}
pub(crate) fn compact(mut self, on: bool) -> Self {
self.compact = on;
self
}
pub(crate) fn preferred(mut self, preferred: &'a [(&'a str, char)]) -> Self {
@@ -165,8 +179,8 @@ impl<'a> Rows<'a> {
Node::Separator => {
Divider::horizontal().show(ui);
}
Node::Submenu { children, .. } => {
if is_dead(children) {
Node::Submenu { children, enabled, .. } => {
if !enabled || is_dead(children) {
MenuItem::submenu(label).enabled(false).show(ui);
} else {
Menu::submenu_row(ui, label, |ui, _| self.show(ui, children, &text.children));
@@ -193,7 +207,7 @@ impl<'a> Rows<'a> {
}
}
_ => {
command_row(ui, item, label, shortcut).show(ui);
command_row(ui, item, label, shortcut).no_icon(!self.icons).compact(self.compact).show(ui);
}
}
}
@@ -258,7 +272,7 @@ fn checked(ui: &Ui, command: &CommandRef) -> Option<bool> {
fn is_dead(nodes: &[Node]) -> bool {
!nodes.iter().any(|node| match node {
Node::Item(item) => item.enabled,
Node::Submenu { children, .. } => !is_dead(children),
Node::Submenu { children, enabled, .. } => *enabled && !is_dead(children),
Node::Separator | Node::Heading(_) | Node::Standard { .. } => false,
})
}
+8 -7
View File
@@ -367,8 +367,8 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option
it.english = Some("Preferences…".to_owned());
Node::Item(it)
}
Node::Submenu { children, role, platforms, .. } => {
Node::Submenu { label: options.text("Preferences"), english: Some("Preferences".to_owned()), children, role, platforms }
Node::Submenu { children, role, platforms, enabled, .. } => {
Node::Submenu { label: options.text("Preferences"), english: Some("Preferences".to_owned()), children, role, platforms, enabled }
}
other => other,
};
@@ -396,12 +396,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar {
let shown = nodes.iter().filter_map(|n| match n {
Node::Item(it) if !it.platforms.contains(on) => None,
Node::Submenu { platforms, .. } if !platforms.contains(on) => None,
Node::Submenu { label, english, children, role, platforms } => Some(Node::Submenu {
Node::Submenu { label, english, children, role, platforms, enabled } => Some(Node::Submenu {
label: label.clone(),
english: english.clone(),
children: keep(children, on, appkit),
role: *role,
platforms: *platforms,
enabled: *enabled,
}),
Node::Standard { .. } if !appkit => None,
other => Some(other.clone()),
@@ -471,11 +472,11 @@ fn settings_node(node: Node, comma_taken: Option<CommandRef>, options: &LayoutOp
give(&mut it);
Node::Item(it)
}
Node::Submenu { mut children, role, platforms, .. } => {
Node::Submenu { mut children, role, platforms, enabled, .. } => {
if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) {
give(first);
}
Node::Submenu { label: options.text("Settings"), english: Some("Settings".to_owned()), children, role, platforms }
Node::Submenu { label: options.text("Settings"), english: Some("Settings".to_owned()), children, role, platforms, enabled }
}
other => other,
}
@@ -491,12 +492,12 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec<Node> {
items.push(it);
}
match submenu {
Some(Node::Submenu { mut children, role, platforms, .. }) => {
Some(Node::Submenu { mut children, role, platforms, enabled, .. }) => {
if !items.is_empty() {
children.push(Node::Separator);
children.extend(items);
}
vec![Node::Submenu { label: options.text("Appearance"), english: Some("Appearance".to_owned()), children, role, platforms }]
vec![Node::Submenu { label: options.text("Appearance"), english: Some("Appearance".to_owned()), children, role, platforms, enabled }]
}
_ => items,
}
+3 -2
View File
@@ -174,8 +174,9 @@ fn lower_nodes(nodes: &[Node], targets: &mut HashMap<String, Target>, headings:
.iter()
.map(|n| match n {
Node::Separator => native::Node::Separator,
Node::Submenu { label, children, .. } => {
native::Node::Submenu { label: label.clone(), children: lower_nodes(children, targets, headings) }
// A native submenu is disabled while it has no children: a disabled one goes over empty.
Node::Submenu { label, children, enabled, .. } => {
native::Node::Submenu { label: label.clone(), children: if *enabled { lower_nodes(children, targets, headings) } else { Vec::new() } }
}
// A disabled item with no target: it shows the caption and nothing reports it. It has no command for
// `native_id` to key on, so its id is its place among the bar's headings.
+20 -4
View File
@@ -159,6 +159,9 @@ pub enum Node {
role: Option<ItemRole>,
/// The platforms it is shown on.
platforms: Platforms,
/// Whether it can be opened. A disabled submenu shows its row greyed and never opens
/// (Open Recent with nothing to list); one whose rows are all disabled is greyed too.
enabled: bool,
},
/// A caption over the rows that follow it. Never a command.
Heading(String),
@@ -439,9 +442,9 @@ impl Node {
Node::Standard { kind, label: label.into() }
}
/// A submenu shown on every platform.
/// An enabled submenu shown on every platform.
pub fn submenu(label: impl Into<String>, children: Vec<Node>) -> Node {
Node::Submenu { label: label.into(), english: None, children, role: None, platforms: Platforms::ALL }
Node::Submenu { label: label.into(), english: None, children, role: None, platforms: Platforms::ALL, enabled: true }
}
/// Set the English name of an item's label or a submenu's title.
@@ -459,6 +462,17 @@ impl Node {
Node::Heading(label.into())
}
/// Set whether an item can be chosen or a submenu opened:
/// `Node::submenu("Open Recent", rows).enabled(!recent.is_empty())`.
pub fn enabled(mut self, on: bool) -> Node {
match &mut self {
Node::Item(it) => it.enabled = on,
Node::Submenu { enabled, .. } => *enabled = on,
Node::Separator | Node::Heading(_) | Node::Standard { .. } => {}
}
self
}
/// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`.
pub fn role(mut self, role: ItemRole) -> Node {
match &mut self {
@@ -824,8 +838,10 @@ fn hash_nodes(nodes: &[Node], h: &mut DefaultHasher) {
it.alternate.as_ref().map(|a| (a.command.key(), a.mods)).hash(h);
}
Node::Separator => '-'.hash(h),
Node::Submenu { label, children, role, .. } => {
('[', label, role).hash(h);
// A native submenu is enabled only through its children (see `mac::lower_nodes`), so its
// enabled state is structure.
Node::Submenu { label, children, role, enabled, .. } => {
('[', label, role, enabled).hash(h);
hash_nodes(children, h);
']'.hash(h);
}
+9
View File
@@ -547,6 +547,11 @@ impl<'a> ShortcutsDialog<'a> {
}
}
/// The width a read-only shortcuts dialog opens at, in points.
const READ_ONLY_WIDTH: f32 = 560.0;
/// The height a read-only shortcuts dialog opens at, in points.
const READ_ONLY_HEIGHT: f32 = 480.0;
/// What a footer button does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
@@ -610,9 +615,13 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu
let enter = env.options.enter_is_ok && !state.modal() && !state.is_recording();
let title = env.title();
let mut open = true;
// A read-only reference opens at a fixed, moderate height (production's key list scrolls inside it), not at the
// window's; the user's own resize is still remembered.
let reference = !env.options.editable;
let session = RefCell::new(Session { env, state });
let shown = Dialog::new(title)
.resizable(true)
.overlay(|overlay| if reference { overlay.size(egui::vec2(READ_ONLY_WIDTH, READ_ONLY_HEIGHT)) } else { overlay })
.remember(SaveKey::new("craft_menu.shortcuts"))
.outer_gesture(true)
.collection_body()
+32
View File
@@ -0,0 +1,32 @@
//! The in-window bar's own rules over the model.
use craft_menu::{Item, Menu, MenuBar, MenuBarUi, Node};
use craft_ui::contract::Tracked;
use craft_ui::testing::{Fixture, trial};
/// A submenu the app disables stays greyed and never opens, though its rows could be chosen
/// (Open Recent with a placeholder row while the app keeps no recent files).
#[trial]
fn a_disabled_submenu_is_greyed_and_does_not_open() {
let bar = Tracked::new(MenuBar::new(vec![Menu::new(
"File",
vec![
Node::submenu("Open Recent", vec![Item::new("file.recent.a", "notes.txt").into()]).enabled(false),
Node::submenu("Export", vec![Item::new("file.export.pdf", "PDF").into()]),
],
)]));
let mut fixture = Fixture::new(move |ui| {
MenuBarUi::new(&bar).show(ui);
});
fixture.settle();
let Some(file) = fixture.by_label("File") else { panic!("the bar shows File") };
fixture.click(&file).settle();
let Some(recent) = fixture.by_label("Open Recent") else { panic!("File shows Open Recent") };
let Some(export) = fixture.by_label("Export") else { panic!("File shows Export") };
assert!(fixture.tree().is_disabled_key(recent.node), "the disabled submenu is greyed");
assert!(!fixture.tree().is_disabled_key(export.node), "its enabled sibling is not");
fixture.click(&recent).settle();
assert!(fixture.by_label("notes.txt").is_none(), "a click does not open it");
fixture.click(&export).settle();
assert!(fixture.by_label("PDF").is_some(), "the enabled one opens");
}
+1
View File
@@ -2,6 +2,7 @@
#[cfg(target_os = "macos")]
mod appkit;
pub(crate) mod bar;
pub(crate) mod from_items;
pub(crate) mod heading;
pub(crate) mod keytips;
+14
View File
@@ -8,3 +8,17 @@ pub(crate) mod review;
pub(crate) mod rows;
pub(crate) mod sets;
pub(crate) mod tabs;
use craft_keymap::Platform;
use craft_ui::testing::trial;
use fixture::Rig;
/// A read-only shortcuts reference does not stretch to the window's height: it opens at a moderate, fixed height and
/// scrolls inside it.
#[trial]
fn a_read_only_dialog_opens_at_a_moderate_height() {
let rig = Rig::tuned(Platform::Windows, |options| options.editable = false);
let close = rig.fixture.by_label("Close").expect("the close button");
assert!(close.rect.bottom() < 560.0, "the dialog's footer sits within a moderate height, not the 700-point window: {:?}", close.rect);
}
+5 -1
View File
@@ -20,7 +20,7 @@ workspace = true
suite = ["screen-testing", "craft-ui/suite"]
default = []
# The page widgets (`craft_pages::ui`), on craft-ui.
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:craft-theme", "dep:egui", "craft-text/ui"]
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:craft-theme", "dep:egui", "dep:serde_json", "craft-text/ui"]
# The stories and the integration tests (`tests/it`).
screen-testing = ["ui", "craft-ui/testing"]
@@ -29,7 +29,10 @@ screen-testing = ["ui", "craft-ui/testing"]
craft-text = { path = "../text", default-features = false }
kurbo = { workspace = true }
serde = { workspace = true }
# `ui::range` keeps a page-range row's value as a dialog's JSON field.
serde_json = { workspace = true, optional = true }
craft-behavior = { workspace = true, optional = true }
# The arrows the page view reads come with the modifiers held.
craft-keymap = { workspace = true, optional = true }
craft-ui = { workspace = true, optional = true }
craft-theme = { workspace = true, optional = true }
@@ -39,3 +42,4 @@ egui = { workspace = true, optional = true }
craft-ui = { workspace = true, features = ["suite"] }
egui = { workspace = true }
craft-i18n = { workspace = true }
serde_json = { workspace = true }
Loaded 100 of 768 files, more files were not shown because too many files have changed in this diff. Show more