mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
Merge next into fix/segmented-narrow-room
This commit is contained in:
commit
cc2b8a3c24
269 files changed
+7445
-979
No files matched your search
@@ -122,10 +122,12 @@ jobs:
|
||||
cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}
|
||||
cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }}
|
||||
lint-cache: false
|
||||
# The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them.
|
||||
# The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a
|
||||
# workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them.
|
||||
unreached-rs-allow: |
|
||||
**/fixtures/**
|
||||
vendor/**
|
||||
crates/pdf/read-only-contract/**
|
||||
timeout-minutes: &timeout 120
|
||||
# Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml).
|
||||
tools: &tools cargo-nextest@0.9.150
|
||||
|
||||
Generated
+18
-14
@@ -2040,6 +2040,7 @@ name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
@@ -2272,6 +2273,7 @@ dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
@@ -2410,6 +2412,7 @@ name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
@@ -4155,6 +4158,7 @@ dependencies = [
|
||||
name = "craft-suite-account"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
@@ -5581,7 +5585,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5637,7 +5641,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5672,7 +5676,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5691,7 +5695,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5710,7 +5714,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5730,7 +5734,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5743,7 +5747,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5820,7 +5824,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5893,7 +5897,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5919,7 +5923,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -15251,19 +15255,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
+14
-14
@@ -317,20 +317,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-appkit"
|
||||
description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,11 +8,12 @@ rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
|
||||
# `NSNotificationCenter` with a block.
|
||||
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6.2"
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
|
||||
|
||||
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
|
||||
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS
|
||||
//! only; the crate is empty elsewhere.
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
|
||||
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
|
||||
//!
|
||||
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
|
||||
//! block says why it is sound.
|
||||
@@ -14,6 +14,8 @@ use block2::RcBlock;
|
||||
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
|
||||
use objc2_foundation::{NSNotification, NSNotificationCenter};
|
||||
|
||||
pub mod save_panel;
|
||||
|
||||
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
|
||||
/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once
|
||||
/// for the process; a later call replaces nothing and does nothing.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action.
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::AnyObject;
|
||||
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
|
||||
use objc2_app_kit::{NSPopUpButton, NSSavePanel};
|
||||
use objc2_foundation::{NSObject, NSObjectProtocol};
|
||||
|
||||
/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems
|
||||
/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it.
|
||||
pub fn new_save_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
|
||||
// SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as
|
||||
// `Option`, so nil is `None`.
|
||||
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
|
||||
if panel.is_some() {
|
||||
return panel;
|
||||
}
|
||||
// SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`.
|
||||
unsafe { msg_send![NSSavePanel::class(), savePanel] }
|
||||
}
|
||||
|
||||
/// The closure a [`PopUpChoice`] calls.
|
||||
pub struct Ivars {
|
||||
on_choose: Box<dyn Fn(usize)>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`.
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = Ivars]
|
||||
#[name = "CraftPopUpChoice"]
|
||||
/// The target of a pop-up menu's action; see [`on_choose`].
|
||||
pub struct PopUpChoice;
|
||||
|
||||
// SAFETY: NSObjectProtocol has no additional requirements.
|
||||
unsafe impl NSObjectProtocol for PopUpChoice {}
|
||||
|
||||
impl PopUpChoice {
|
||||
// SAFETY: NSControl's target-action sends the pop-up button as the one object argument.
|
||||
#[unsafe(method(choose:))]
|
||||
fn choose(&self, sender: &NSPopUpButton) {
|
||||
if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) {
|
||||
(self.ivars().on_choose)(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target,
|
||||
/// so the caller keeps the returned object for as long as `popup` can send its action.
|
||||
pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained<PopUpChoice> {
|
||||
let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) });
|
||||
// SAFETY: NSObject's designated initializer, called once on the allocated subclass.
|
||||
let target: Retained<PopUpChoice> = unsafe { msg_send![super(this), init] };
|
||||
let object: &AnyObject = ⌖
|
||||
// SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps
|
||||
// `target` alive while `popup` can send it (the documentation above).
|
||||
unsafe {
|
||||
popup.setTarget(Some(object));
|
||||
popup.setAction(Some(sel!(choose:)));
|
||||
}
|
||||
target
|
||||
}
|
||||
@@ -16,7 +16,7 @@ use crate::security;
|
||||
use crate::server::{self, Listening};
|
||||
|
||||
/// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so
|
||||
/// freeing a taken port is enough.
|
||||
/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`].
|
||||
pub const RETRY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence
|
||||
@@ -123,6 +123,10 @@ pub struct AgentLink {
|
||||
applied: Option<Option<AgentSettings>>,
|
||||
retry_at: Option<Instant>,
|
||||
retry: Duration,
|
||||
/// The token a failed start already read and checked, for its retries with the same settings;
|
||||
/// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms
|
||||
/// on the UI thread, which every retry of a taken port would otherwise pay again.
|
||||
checked_token: Option<String>,
|
||||
status: AgentLinkStatus,
|
||||
}
|
||||
|
||||
@@ -144,6 +148,7 @@ impl AgentLink {
|
||||
applied: None,
|
||||
retry_at: None,
|
||||
retry: RETRY,
|
||||
checked_token: None,
|
||||
status: AgentLinkStatus::default(),
|
||||
}
|
||||
}
|
||||
@@ -166,7 +171,12 @@ impl AgentLink {
|
||||
|
||||
/// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it
|
||||
/// on another port, stop it, or keep it while other settings change. Does nothing while `want`
|
||||
/// equals the last call's and no retry of a failed start is due.
|
||||
/// equals the last call's and no retry of a failed start is due. A token file refused as it is
|
||||
/// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still
|
||||
/// can't be used (a folder in its place, a folder that can't be written) schedules no retry:
|
||||
/// that lasts until someone changes it, and on Windows each check blocks the UI thread for
|
||||
/// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`]
|
||||
/// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again.
|
||||
pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate {
|
||||
let mut update = LinkUpdate::default();
|
||||
if self.launch.is_some() {
|
||||
@@ -174,9 +184,15 @@ impl AgentLink {
|
||||
}
|
||||
let now = motion::now();
|
||||
let retry_due = self.retry_at.is_some_and(|at| now >= at);
|
||||
if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due {
|
||||
let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want);
|
||||
if unchanged && !retry_due {
|
||||
return update;
|
||||
}
|
||||
// Only a retry with the same settings reuses the token its failed start checked: after a
|
||||
// change (agents off and on again, another port) the file may hold another token by now.
|
||||
if !unchanged {
|
||||
self.checked_token = None;
|
||||
}
|
||||
let before = (self.status.clone(), self.applied.clone().flatten());
|
||||
self.applied = Some(want.cloned());
|
||||
self.retry_at = None;
|
||||
@@ -218,6 +234,10 @@ impl AgentLink {
|
||||
update.requests = Some(requests);
|
||||
Ok(())
|
||||
}
|
||||
Err(problem @ LinkProblem::TokenFile(_)) => {
|
||||
log::warn!("{problem}");
|
||||
Err(problem)
|
||||
}
|
||||
Err(problem) => {
|
||||
log::warn!("{problem}");
|
||||
self.retry_at = Some(motion::now() + self.retry);
|
||||
@@ -229,13 +249,21 @@ impl AgentLink {
|
||||
|
||||
/// The token from the settings folder (created `0600` when missing), the server, then the
|
||||
/// connection file. Any failure leaves nothing running.
|
||||
fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
|
||||
/// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]).
|
||||
/// The token file is the link's own, so one refused as it is gets a new token (see
|
||||
/// [`fresh_token`]).
|
||||
fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?;
|
||||
let token = match self.checked_token.clone() {
|
||||
Some(token) => token,
|
||||
None => fresh_token(&token_file)?,
|
||||
};
|
||||
self.checked_token = Some(token.clone());
|
||||
let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?;
|
||||
let running = Running { server, dir: dir.to_path_buf(), port_pref };
|
||||
let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone());
|
||||
write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?;
|
||||
self.checked_token = None;
|
||||
Ok((running, requests))
|
||||
}
|
||||
|
||||
@@ -250,3 +278,22 @@ impl AgentLink {
|
||||
self.status.problem = Some(problem);
|
||||
}
|
||||
}
|
||||
|
||||
/// The token in `token_file`, created when missing. A regular file the check refuses (one an
|
||||
/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged
|
||||
/// token) is replaced with a new token, once: the token is only this link's secret, and a client
|
||||
/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted
|
||||
/// the file. Anything else in the way (a folder, a link) is reported, not removed.
|
||||
fn fresh_token(token_file: &Path) -> Result<String, LinkProblem> {
|
||||
let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()));
|
||||
let problem = match read() {
|
||||
Ok(token) => return Ok(token),
|
||||
Err(problem) => problem,
|
||||
};
|
||||
if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) {
|
||||
return Err(problem);
|
||||
}
|
||||
log::warn!("{problem}; writing a new token file");
|
||||
std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?;
|
||||
read()
|
||||
}
|
||||
@@ -200,8 +200,16 @@ impl ControlChannel {
|
||||
|
||||
/// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the
|
||||
/// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time);
|
||||
/// `document` the identity a screenshot is attributed to.
|
||||
/// `document` the identity a screenshot is attributed to. A screenshot is admitted at
|
||||
/// [`motion::now`]; [`Self::settle_at`] takes the time instead.
|
||||
pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64) {
|
||||
self.settle_at(req, outcome, document, settle_ms, motion::now());
|
||||
}
|
||||
|
||||
/// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its
|
||||
/// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to
|
||||
/// [`Captures::issue`] and [`Captures::drain`].
|
||||
pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64, now: Instant) {
|
||||
let reply = req.reply;
|
||||
match outcome {
|
||||
Reply::Done(v) => {
|
||||
@@ -212,7 +220,7 @@ impl ControlChannel {
|
||||
Reply::AccessTree => self.tree_waiters.push(reply),
|
||||
Reply::Screenshot { token, path, region, viewport } => {
|
||||
let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms };
|
||||
if let Err((reply, e)) = self.captures.admit(request, motion::now()) {
|
||||
if let Err((reply, e)) = self.captures.admit(request, now) {
|
||||
let _ = reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
//! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept
|
||||
//! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it.
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{BufRead, Write};
|
||||
use std::io::BufRead;
|
||||
#[cfg(not(windows))]
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -319,30 +322,34 @@ fn read_token_file(path: &Path) -> Result<String, AutomationError> {
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one
|
||||
/// that caused it, with the path in its message.
|
||||
fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> {
|
||||
let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display()));
|
||||
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?;
|
||||
}
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
|
||||
// On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token
|
||||
// is written, and a file that cannot be restricted is removed rather than left for the token to go into later.
|
||||
// On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's
|
||||
// access list, and the token is written through the handle that created it.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) {
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display())));
|
||||
owner_only::current_user_sid()
|
||||
.and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes()))
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display())))
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| at(path, e))?;
|
||||
writeln!(file, "{token}").map_err(|e| at(path, e))
|
||||
}
|
||||
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// The server's token, lower-cased. Both given is
|
||||
@@ -355,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// file can be reached by others: <why>; restrict it to its owner`), and its trimmed content is
|
||||
/// validated. A missing one is created with a generated token (parent directories created,
|
||||
/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a
|
||||
/// newline); losing that create race to another process reads the winner's file instead.
|
||||
/// newline); losing that create race to another process reads the winner's file instead. On
|
||||
/// Windows a create that does not finish in time fails (`I/O: <path>: cannot create the control
|
||||
/// token file for its owner only: <why>`), and a file it left at the path is not read as a winner's.
|
||||
pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result<String, AutomationError> {
|
||||
server_token_with(supplied, token_file, create_token_file)
|
||||
}
|
||||
|
||||
/// [`server_token`], with `create` making a missing token file.
|
||||
fn server_token_with(
|
||||
supplied: Option<&str>,
|
||||
token_file: Option<&Path>,
|
||||
create: impl FnOnce(&Path, &str) -> std::io::Result<()>,
|
||||
) -> Result<String, AutomationError> {
|
||||
if supplied.is_some() && token_file.is_some() {
|
||||
return Err(token_conflict());
|
||||
}
|
||||
@@ -370,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result
|
||||
};
|
||||
match read_token_file(path) {
|
||||
Ok(existing) => Ok(existing.to_ascii_lowercase()),
|
||||
Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) {
|
||||
Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) {
|
||||
Ok(()) => Ok(token),
|
||||
// Another process won the create-new race.
|
||||
Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
|
||||
Err(e) => Err(e),
|
||||
// Another process won the create-new race. A file left by a create that ran out of time is this one's.
|
||||
Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
|
||||
Err(e) => Err(AutomationError::Io(e.to_string())),
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
|
||||
@@ -141,6 +141,12 @@ fn server_token_sources_and_validation() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
let sddl = owner_only::sddl_of(&file).unwrap();
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
|
||||
}
|
||||
assert_eq!(server_token(None, Some(&file)).unwrap(), created);
|
||||
|
||||
// An existing file's content is trimmed and lower-cased.
|
||||
@@ -163,3 +169,25 @@ fn server_token_sources_and_validation() {
|
||||
"bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE"
|
||||
);
|
||||
}
|
||||
|
||||
// A token file create that runs out of time fails with its own error, even when it left a file at
|
||||
// the path: that file is not read as another process's. A create that another process beat to the
|
||||
// path reads that process's token.
|
||||
#[trial]
|
||||
fn a_token_file_create_that_runs_out_of_time_is_an_error() {
|
||||
let dir = scratch_dir("token-limit");
|
||||
let file = dir.join("token");
|
||||
let late = |p: &Path, _: &str| {
|
||||
std::fs::write(p, "partial").unwrap();
|
||||
Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display())))
|
||||
};
|
||||
let err = server_token_with(None, Some(&file), late).unwrap_err().to_string();
|
||||
assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}");
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
let beaten = |p: &Path, _: &str| {
|
||||
create_token_file(p, TOKEN).unwrap();
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"))
|
||||
};
|
||||
assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -308,6 +308,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() {
|
||||
TcpListener::bind(("127.0.0.1", port)).expect("the port was let go");
|
||||
}
|
||||
|
||||
/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the
|
||||
/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every
|
||||
/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again.
|
||||
#[trial]
|
||||
fn a_refused_token_file_is_not_retried_until_the_settings_change() {
|
||||
let dir = temp_dir("link-token-no-retry");
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let wanted = free_port();
|
||||
assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
|
||||
// The file is fixed, but the same settings don't look at it again.
|
||||
std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
let same = link.sync(Some(&on(u32::from(wanted))), &host);
|
||||
assert!(same.requests.is_none() && !same.changed, "no retry with the same settings");
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
|
||||
let changed = link.sync(Some(&on(0)), &host);
|
||||
assert!(changed.requests.is_some(), "a settings change tries again");
|
||||
assert_eq!(link.status().problem, None);
|
||||
}
|
||||
|
||||
/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its
|
||||
/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can
|
||||
/// connect instead of staying out until someone deletes the file (photocraft#17006).
|
||||
#[trial]
|
||||
fn a_refused_token_file_is_replaced_with_a_new_token() {
|
||||
let dir = temp_dir("link-token-refresh");
|
||||
let file = dir.path().join(TOKEN_FILE);
|
||||
std::fs::write(&file, "not a token\n").unwrap();
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
|
||||
assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status());
|
||||
assert_eq!(link.status().problem, None);
|
||||
let token = std::fs::read_to_string(&file).unwrap();
|
||||
assert_ne!(token.trim(), "not a token");
|
||||
assert_eq!(token.trim().len(), 64, "a new token: {token:?}");
|
||||
assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening"));
|
||||
}
|
||||
|
||||
/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows
|
||||
/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time.
|
||||
#[trial]
|
||||
fn a_taken_port_retry_reuses_the_checked_token() {
|
||||
let dir = temp_dir("link-token-reuse");
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = u32::from(taken.local_addr().unwrap().port());
|
||||
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
|
||||
|
||||
// Reading the file now fails, so a retry that read it would report a token file problem.
|
||||
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
drop(taken);
|
||||
let retried = link.sync(Some(&on(port)), &host);
|
||||
assert!(retried.requests.is_some(), "{:?}", link.status());
|
||||
assert_eq!(link.status().problem, None);
|
||||
|
||||
// Once a start succeeded, the next one reads the file again.
|
||||
let moved = link.sync(Some(&on(0)), &host);
|
||||
assert!(moved.requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
}
|
||||
|
||||
/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token
|
||||
/// file again, so a server never listens with a token the file no longer holds.
|
||||
#[trial]
|
||||
fn a_settings_change_reads_the_token_file_again() {
|
||||
let dir = temp_dir("link-token-settings");
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = u32::from(taken.local_addr().unwrap().port());
|
||||
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
|
||||
|
||||
assert!(!link.sync(None, &host).stopped, "nothing was running");
|
||||
// While agents are off the token file changes; here it can't be read at all, which the next start must report.
|
||||
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
drop(taken);
|
||||
let back = link.sync(Some(&on(port)), &host);
|
||||
assert!(back.requests.is_none(), "started with the token the file no longer holds");
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
}
|
||||
|
||||
/// Dropping the link stops its server and removes its connection file.
|
||||
#[trial]
|
||||
fn dropping_the_link_removes_its_connection_file() {
|
||||
|
||||
@@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app
|
||||
/// also passes to `issue` and `drain`, not from the wall clock.
|
||||
#[trial]
|
||||
fn a_screenshot_settled_at_a_time_counts_from_that_time() {
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
|
||||
use craft_automation::screenshot::ScreenshotParams;
|
||||
use serde_json::json;
|
||||
|
||||
let ctx = Context::default();
|
||||
// An app clock ahead of the wall clock.
|
||||
let arrived = motion::now() + Duration::from_secs(60);
|
||||
let (_transport, requests) = channel();
|
||||
let mut control = ControlChannel::new(requests);
|
||||
control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0));
|
||||
let (request, rx) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
let params = ScreenshotParams::from_params(&json!({})).expect("no params");
|
||||
control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived);
|
||||
assert!(rx.try_recv().is_err(), "the reply waits for the capture");
|
||||
|
||||
let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None);
|
||||
assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::<Vec<_>>());
|
||||
assert!(callbacks.is_empty(), "not issued inside its settle delay");
|
||||
assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline");
|
||||
let finished = control.captures.drain(arrived + DEADLINE, None);
|
||||
assert_eq!(finished.len(), 1);
|
||||
assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0]));
|
||||
}
|
||||
|
||||
/// Cancelling releases the budget at once; an image that arrives afterwards is dropped.
|
||||
#[trial]
|
||||
fn cancellation_releases_the_budget_and_drops_a_late_image() {
|
||||
|
||||
@@ -41,8 +41,8 @@ pub struct Workspace<P> {
|
||||
/// goes back.
|
||||
#[serde(default)]
|
||||
hidden: Vec<(P, Location<P>)>,
|
||||
/// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the
|
||||
/// workspace.
|
||||
/// Floating panels with the docked location each one left, so Dock Panel can return it; a closed panel that
|
||||
/// floats records the place it would reopen at. Saved with the workspace.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
floated: Vec<(P, Location<P>)>,
|
||||
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
|
||||
@@ -264,6 +264,16 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?,
|
||||
_ => false,
|
||||
};
|
||||
// Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel
|
||||
// that would reopen in a floating window has no docked place.
|
||||
let hidden_place = match &action {
|
||||
Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed
|
||||
.restored(panel, &policy)
|
||||
.filter(|restored| !floats(&restored.layout, panel))
|
||||
.and_then(|restored| restored.layout.location(panel).ok())
|
||||
.map(|location| (panel.clone(), location)),
|
||||
_ => None,
|
||||
};
|
||||
if !reopened {
|
||||
// SetNative records where the window system has a floating window, so a lock
|
||||
// does not refuse it.
|
||||
@@ -278,6 +288,12 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
proposed.hidden.push((panel, location));
|
||||
}
|
||||
proposed.track_floated(&before);
|
||||
if let Some((panel, location)) = hidden_place
|
||||
&& floats(&proposed.layout, &panel)
|
||||
&& !proposed.floated.iter().any(|(p, _)| p == &panel)
|
||||
{
|
||||
proposed.floated.push((panel, location));
|
||||
}
|
||||
all_closed.extend(closed);
|
||||
}
|
||||
let visible: HashSet<P> = proposed.layout.panels().into_iter().cloned().collect();
|
||||
|
||||
@@ -85,15 +85,12 @@ pub struct GridCursor {
|
||||
impl GridCursor {
|
||||
/// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A
|
||||
/// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share
|
||||
/// does not go below it.
|
||||
/// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns.
|
||||
pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self {
|
||||
let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0);
|
||||
let content: Vec<f32> = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect();
|
||||
let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width })
|
||||
.collect();
|
||||
let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x);
|
||||
keep_fill_least(columns, &mut widths, least);
|
||||
let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect();
|
||||
GridCursor {
|
||||
flow,
|
||||
@@ -266,6 +263,44 @@ impl GridCursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a
|
||||
/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight.
|
||||
/// The fill columns together take more than their room only when their least widths do not fit in it.
|
||||
fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) {
|
||||
let fills: Vec<(usize, f32)> = columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None })
|
||||
.collect();
|
||||
let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum();
|
||||
if !room.is_finite() {
|
||||
// Room with no bound leaves every share above its least.
|
||||
for (i, _) in &fills {
|
||||
widths[*i] = widths[*i].max(least(*i));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut raised = vec![false; columns.len()];
|
||||
loop {
|
||||
let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::<f32>();
|
||||
let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum();
|
||||
let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 };
|
||||
let mut more = false;
|
||||
for (i, weight) in &fills {
|
||||
if !raised[*i] && share(*weight) < least(*i) {
|
||||
raised[*i] = true;
|
||||
more = true;
|
||||
}
|
||||
}
|
||||
if !more {
|
||||
for (i, weight) in &fills {
|
||||
widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) };
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `columns` with each `Fill` column as a `Content` column.
|
||||
fn as_content(columns: &[ColumnWidth]) -> Vec<ColumnWidth> {
|
||||
columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect()
|
||||
@@ -288,4 +323,43 @@ mod tests {
|
||||
cursor.cell(Vec2::new(150.0, 100.0));
|
||||
assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds");
|
||||
}
|
||||
|
||||
/// The widths of one row of `columns` placed by `last`, read from the cells.
|
||||
fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec<f32> {
|
||||
let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last);
|
||||
columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
|
||||
let shares = row_widths(&columns, &fitting);
|
||||
let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0]));
|
||||
assert!(shares[0] < 120.0, "the first column's share is below its least");
|
||||
assert!(raised[0] >= 120.0, "the first column keeps its least");
|
||||
assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow");
|
||||
assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights");
|
||||
assert_eq!(raised[3], shares[3], "the content column keeps its width");
|
||||
assert_eq!(raised.iter().sum::<f32>(), 300.0, "the row fills the grid and no more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]);
|
||||
let widths = row_widths(&columns, &last);
|
||||
assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least");
|
||||
assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room");
|
||||
assert_eq!(widths.iter().sum::<f32>(), 330.0, "the row is as wide as the least widths and no wider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
|
||||
let shares = row_widths(&columns, &last);
|
||||
let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0]));
|
||||
assert_eq!(kept, shares);
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool {
|
||||
}
|
||||
|
||||
/// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can
|
||||
/// tell it from a number or an operator.
|
||||
/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch).
|
||||
pub fn is_unit_spelling(spelling: &str) -> bool {
|
||||
!spelling.is_empty() && spelling.chars().all(is_unit_char)
|
||||
let letters = spelling.strip_prefix('/').unwrap_or(spelling);
|
||||
!letters.is_empty() && letters.chars().all(is_unit_char)
|
||||
}
|
||||
|
||||
/// A unit spelling and the factor that turns its quantity into the base unit.
|
||||
@@ -41,7 +42,9 @@ struct Unit {
|
||||
/// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it
|
||||
/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest
|
||||
/// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a
|
||||
/// quantity when `px` is registered. A group separator counts only before exactly three digits.
|
||||
/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after
|
||||
/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before
|
||||
/// exactly three digits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Reader {
|
||||
decimal: char,
|
||||
@@ -213,8 +216,9 @@ impl Parse<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no
|
||||
/// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it.
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a
|
||||
/// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them,
|
||||
/// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide.
|
||||
fn quantity(&mut self, scaled: bool) -> Result<f64, NotAValue> {
|
||||
let number = self.number()?;
|
||||
self.tag = None;
|
||||
@@ -223,8 +227,11 @@ impl Parse<'_> {
|
||||
return Ok(number / 100.0);
|
||||
}
|
||||
let reader = self.reader;
|
||||
let run: Vec<char> = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect();
|
||||
let unit = (1..=run.len()).rev().find_map(|len| {
|
||||
let after = &self.chars[self.at..];
|
||||
let slash = usize::from(after.first() == Some(&'/'));
|
||||
let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count();
|
||||
let run = &after[..slash + letters];
|
||||
let unit = (1 + slash..=run.len()).rev().find_map(|len| {
|
||||
let lowered = run[..len].iter().collect::<String>().to_lowercase();
|
||||
reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit))
|
||||
});
|
||||
@@ -326,6 +333,20 @@ mod tests {
|
||||
near(&percent, "2%", 14.0);
|
||||
assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share");
|
||||
|
||||
let per_inch = Reader::new().unit_tagged("/in", 1.0, 0);
|
||||
assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in"));
|
||||
for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] {
|
||||
near(&per_inch, text, 40.0);
|
||||
}
|
||||
assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit");
|
||||
assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product");
|
||||
assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value");
|
||||
for bad in ["", "/in", "40/inch", "40/"] {
|
||||
assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value");
|
||||
}
|
||||
near(&lengths, "144/2in", 1.0);
|
||||
assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number");
|
||||
|
||||
let german = Reader::new().decimal(',').group('.');
|
||||
near(&german, "1.234,5", 1234.5);
|
||||
near(&german, "1.234.567", 1_234_567.0);
|
||||
|
||||
@@ -241,6 +241,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() {
|
||||
assert!(workspace.floated().is_empty(), "closing drops the record");
|
||||
}
|
||||
|
||||
/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old
|
||||
/// group keeps its front tab; docking it then returns it to that group at its old index.
|
||||
#[test]
|
||||
fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() {
|
||||
let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0));
|
||||
let mut opened = Workspace::new(docked());
|
||||
opened.apply(Action::close(2), false, allow).unwrap();
|
||||
opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap();
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(2), false, allow).unwrap();
|
||||
workspace.apply(float, false, allow).unwrap();
|
||||
let layout = workspace.layout();
|
||||
assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. })));
|
||||
assert_eq!(group_members(layout, 3), [3]);
|
||||
assert_eq!(front(layout, 3), 3, "the old group keeps its front tab");
|
||||
assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives");
|
||||
|
||||
let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) };
|
||||
let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone());
|
||||
workspace.apply(back, false, allow).unwrap();
|
||||
assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index");
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(6), false, allow).unwrap();
|
||||
workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place");
|
||||
}
|
||||
|
||||
/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6].
|
||||
fn columns() -> Layout<u32> {
|
||||
let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]);
|
||||
|
||||
@@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
Variation::WarmCool => (&words.cool, &words.warm),
|
||||
Variation::VividMuted => (&words.muted, &words.vivid),
|
||||
};
|
||||
Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Text::new(left.clone()).show(ui);
|
||||
Text::new(right.clone()).show(ui);
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::{Button, PopupMark};
|
||||
use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring};
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band};
|
||||
use craft_ui::contract::{
|
||||
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi,
|
||||
Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
|
||||
@@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra
|
||||
if style.ring {
|
||||
let ground =
|
||||
ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) });
|
||||
ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground);
|
||||
ui.draw().surface_styled(well.shrink(ring_band(well)), &ground);
|
||||
} else {
|
||||
ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge);
|
||||
}
|
||||
|
||||
@@ -448,7 +448,7 @@ pub struct ColorPanel<'a> {
|
||||
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: &'a [Srgba],
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
@@ -471,7 +471,7 @@ struct Inputs<'a> {
|
||||
wells: Option<&'a [PairWell; 2]>,
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: &'a [Srgba],
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> {
|
||||
wells: None,
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: &[],
|
||||
recent: None,
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags.
|
||||
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row
|
||||
/// for a host that gives them, an empty list included; without them it shows no row.
|
||||
pub fn recent(mut self, colors: &'a [Srgba]) -> Self {
|
||||
self.recent = colors;
|
||||
self.recent = Some(colors);
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{Swatch, SwatchSpacing};
|
||||
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::text::{HexField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
@@ -131,8 +132,8 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and
|
||||
/// picks nothing; a Shift click moves to the next mode.
|
||||
/// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end
|
||||
/// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode.
|
||||
fn spectrum(&mut self, ui: &mut Ui) {
|
||||
let mode = self.shown_mode();
|
||||
let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum };
|
||||
@@ -145,6 +146,7 @@ impl Body<'_> {
|
||||
.gamut(gamut)
|
||||
.gamut_revision(revision)
|
||||
.web_safe(self.now.web_safe_ramp)
|
||||
.square_boxes(true)
|
||||
.sizing(Sizing::Fill)
|
||||
.show(ui);
|
||||
self.ramp_events(ramp.edit.events);
|
||||
@@ -154,14 +156,19 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Recent Colors as a spaced palette; a pick sets the colour.
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
|
||||
/// is empty, where the first applied color will go.
|
||||
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
|
||||
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
|
||||
fn recent(&mut self, ui: &mut Ui) {
|
||||
if self.inputs.recent.is_empty() {
|
||||
let Some(recent) = self.inputs.recent else {
|
||||
return;
|
||||
};
|
||||
Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
if recent.is_empty() {
|
||||
return;
|
||||
}
|
||||
let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let mut current = self.color();
|
||||
let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced);
|
||||
if let Some(setup) = self.inputs.recent_setup {
|
||||
|
||||
@@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
use craft_ui::canvas::context_click;
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx,
|
||||
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi,
|
||||
PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{Marker, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
@@ -240,6 +240,11 @@ pub struct ColorRamp<'a> {
|
||||
/// Whether the white and black boxes follow the bar; on by default.
|
||||
#[prop]
|
||||
boxes: bool,
|
||||
/// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a
|
||||
/// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by
|
||||
/// its content and in a short one.
|
||||
#[prop]
|
||||
square_boxes: bool,
|
||||
/// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value.
|
||||
#[prop(into)]
|
||||
kind_name: Option<Label>,
|
||||
@@ -265,6 +270,7 @@ impl<'a> ColorRamp<'a> {
|
||||
web_safe: false,
|
||||
recolor_clicks: false,
|
||||
boxes: true,
|
||||
square_boxes: false,
|
||||
kind_name: None,
|
||||
colors: Arc::default(),
|
||||
shown_ends: ends,
|
||||
@@ -416,6 +422,12 @@ impl Component for ColorRamp<'_> {
|
||||
Some(Axis::X)
|
||||
}
|
||||
|
||||
/// With [`square_boxes`](ColorRamp::square_boxes), as tall as its two end boxes stacked, each as tall as it is wide;
|
||||
/// else the style's least, a color band.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
if self.square_boxes { Vec2::new(0.0, cx.style.boxes * 2.0) } else { Vec2::ZERO }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
@@ -136,11 +136,19 @@ pub(super) fn group_rename(groups: &[SwatchGroup], index: usize, text: &str) ->
|
||||
(!name.is_empty() && !groups.iter().enumerate().any(|(i, g)| i != index && g.name == name)).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header, then its swatches.
|
||||
/// Whether the browser shows a header row for `group`: every group but the one with an empty name, which holds the
|
||||
/// swatches outside every group.
|
||||
fn has_header(group: &SwatchGroup) -> bool {
|
||||
!group.name.is_empty()
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header (none for the swatches outside every group), then its swatches.
|
||||
fn flat<'a>(groups: impl IntoIterator<Item = &'a SwatchGroup>) -> Vec<SwatchKey> {
|
||||
let mut rows = Vec::new();
|
||||
for group in groups {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
if has_header(group) {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
}
|
||||
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
|
||||
}
|
||||
rows
|
||||
@@ -167,10 +175,21 @@ fn resolve_move(groups: &[SwatchGroup], names: &[&str], to: usize, parent: Optio
|
||||
(group < groups.len()).then_some((group, slot))
|
||||
}
|
||||
|
||||
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay.
|
||||
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay: each staying group
|
||||
/// whose first row (its header, or its first swatch when it has none) is above `to`. Groups never land above the
|
||||
/// swatches outside every group when those come first.
|
||||
fn group_slot(groups: &[SwatchGroup], names: &[&str], to: usize) -> usize {
|
||||
let remaining = flat(groups.iter().filter(|g| !names.contains(&g.name.as_str())));
|
||||
remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count()
|
||||
let mut row = 0;
|
||||
let mut slot = 0;
|
||||
let mut staying = groups.iter().filter(|g| !names.contains(&g.name.as_str())).peekable();
|
||||
let floor = usize::from(staying.peek().is_some_and(|g| !has_header(g)));
|
||||
for group in staying {
|
||||
if row < to {
|
||||
slot += 1;
|
||||
}
|
||||
row += usize::from(has_header(group)) + group.entries.len();
|
||||
}
|
||||
slot.max(floor)
|
||||
}
|
||||
|
||||
/// The `at` of each edit that moves `moved` (in library order) one by one within `order`, so that they end up together
|
||||
@@ -352,8 +371,8 @@ impl SwatchLibrary {
|
||||
}
|
||||
|
||||
/// Applies a reorder of the browser: swatches go into a group at a place, or groups to a place among the
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches) that remain once the moved ones are
|
||||
/// taken out. Anything else leaves the library as it is.
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches; no header for the group with an empty
|
||||
/// name) that remain once the moved ones are taken out. Anything else leaves the library as it is.
|
||||
pub fn apply_reorder(&mut self, mv: &ReorderMove<SwatchKey>) -> bool {
|
||||
if mv.copy {
|
||||
return false;
|
||||
@@ -641,17 +660,24 @@ fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>
|
||||
}
|
||||
|
||||
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
|
||||
/// colour value (the name alone for a swatch without a colour).
|
||||
/// colour value (the name alone for a swatch without a colour). A group with an empty name holds the swatches outside
|
||||
/// every group: its swatches show at the top level, with no header.
|
||||
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
|
||||
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
|
||||
for group in groups {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
let header = has_header(group);
|
||||
let depth = usize::from(header);
|
||||
if header {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
}
|
||||
for entry in &group.entries {
|
||||
let named = match entry.color() {
|
||||
Some(color) => format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())),
|
||||
None => entry.name.clone(),
|
||||
};
|
||||
rows.push(PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named));
|
||||
rows.push(
|
||||
PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), depth).tooltip(named.clone()).accessible_name(named),
|
||||
);
|
||||
}
|
||||
}
|
||||
rows
|
||||
@@ -676,6 +702,27 @@ pub(crate) mod tests {
|
||||
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
|
||||
}
|
||||
|
||||
/// The swatches outside every group (the group with an empty name) have no header row, so a place below them
|
||||
/// counts them as rows: a group dropped there lands after them, and a swatch dropped there joins them. A group
|
||||
/// dropped above them lands after them too.
|
||||
#[trial]
|
||||
fn drops_below_the_ungrouped_swatches_land_after_them() {
|
||||
let library = SwatchLibrary::new(vec![group("", &["A", "B"]), group("G", &["C"]), group("H", &["D"])]);
|
||||
let rows: Vec<_> = swatch_rows(&library.groups, &SwatchesWords::default()).into_iter().map(|row| row.key).collect();
|
||||
assert_eq!(rows, flat(&library.groups), "the reorder counts the rows the browser shows");
|
||||
|
||||
for to in [0, 2] {
|
||||
let mut moved = library.clone();
|
||||
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Group("H".to_owned()), vec![SwatchKey::Group("H".to_owned())], to, false)));
|
||||
let order: Vec<_> = moved.groups.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(order, ["", "H", "G"], "H dropped at row {to} lands below the ungrouped swatches, above G");
|
||||
}
|
||||
|
||||
let mut moved = library.clone();
|
||||
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Swatch("C".to_owned()), vec![SwatchKey::Swatch("C".to_owned())], 2, false)));
|
||||
assert_eq!(moved.find("C"), Some(SwatchAt::new(0, 2)), "C joins the ungrouped swatches, after B");
|
||||
}
|
||||
|
||||
/// Edits that move several items down or up give the order the browser's own reorder gives.
|
||||
#[trial]
|
||||
fn multi_item_moves_apply_as_the_reorder_does() {
|
||||
|
||||
@@ -18,7 +18,7 @@ use craft_ui::patterns::presets::{
|
||||
};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use egui::{Response, Ui};
|
||||
use egui::{AsIdSalt, IdSalt, Response, Ui};
|
||||
|
||||
use super::library::{HostThumb, find_swatch, has, panel_source};
|
||||
use super::menu::event_edits;
|
||||
@@ -77,6 +77,8 @@ type PayloadAdder<'a> = Box<dyn for<'b> Fn(PresetBrowser<'b, SwatchKey>) -> Pres
|
||||
/// [`search`](SwatchesPanel::search), [`row_icons`](SwatchesPanel::row_icons), [`takes_drop`](SwatchesPanel::takes_drop)
|
||||
/// and [`row_items`](SwatchesPanel::row_items) pass through; the events they cause come out in
|
||||
/// [`SwatchesPanelOutput::events`].
|
||||
/// - [`document`](SwatchesPanel::document) keeps the browser's own state (an open rename field, the scroll position)
|
||||
/// per document, so a host that shows one panel for several documents does not carry it from one to another.
|
||||
/// - It fills the room it is given, and its browser scrolls the swatches: show it outside a body that scrolls.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
@@ -96,6 +98,7 @@ pub struct SwatchesPanel<'a> {
|
||||
takes_drop: Option<DropMaker<'a>>,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
document: Option<IdSalt>,
|
||||
}
|
||||
|
||||
/// What the body decided; `show` stores the state and reports the rest after the real run.
|
||||
@@ -126,6 +129,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
takes_drop: None,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
document: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +220,14 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll
|
||||
/// position) for each document, so a rename left open in one document does not open on another document's
|
||||
/// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in.
|
||||
pub fn document(mut self, document: impl AsIdSalt) -> Self {
|
||||
self.document = Some(IdSalt::new(document));
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws the panel and returns the user's actions this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
|
||||
let SwatchesPanel {
|
||||
@@ -234,12 +246,15 @@ impl<'a> SwatchesPanel<'a> {
|
||||
takes_drop,
|
||||
payloads,
|
||||
row_items,
|
||||
document,
|
||||
} = self;
|
||||
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
let words = Env::of(ui).words::<SwatchesWords>();
|
||||
let mut held_state = Held::new(state);
|
||||
let ctx = ui.ctx().clone();
|
||||
let browser_id = ui.scope_id();
|
||||
// A document's browser has an id of its own; otherwise the browser takes the scope id of the `Ui` it is shown in.
|
||||
let document_id = document.map(|document| ui.scope_id().with(document));
|
||||
let browser_id = document_id.unwrap_or_else(|| ui.scope_id());
|
||||
let icons: BTreeMap<&str, Vec<(IconSpec<'static>, String)>> = match &row_icons {
|
||||
Some(icons) => {
|
||||
groups.iter().flat_map(|g| g.entries.iter()).map(|e| (e.name.as_str(), icons(&SwatchKey::Swatch(e.name.clone())))).collect()
|
||||
@@ -267,6 +282,9 @@ impl<'a> SwatchesPanel<'a> {
|
||||
.select(select)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.selection(Bind::bound(&mut st.selection));
|
||||
if let Some(id) = document_id {
|
||||
browser = browser.browser_id(id);
|
||||
}
|
||||
if let Some(options) = footer_options {
|
||||
browser = browser.footer(options);
|
||||
}
|
||||
|
||||
@@ -202,6 +202,50 @@ impl WheelRig {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names focus takes from the hue ring of a wheel shown in an arena (a split area's body) between two buttons,
|
||||
/// one per Tab in `keys` (with its modifiers).
|
||||
fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>> {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = craft_ui::buttons::Button::new("Before").show(ui);
|
||||
let limits = |_: &usize| craft_ui::contract::SizeLimits::default();
|
||||
let rules = craft_ui::docking::tree::FrameRules::new(&limits);
|
||||
let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0));
|
||||
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| {
|
||||
let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui);
|
||||
});
|
||||
let _ = craft_ui::buttons::Button::new("After").show(ui);
|
||||
});
|
||||
fixture.room(vec2(420.0, 420.0));
|
||||
fixture.settle();
|
||||
let hue = fixture.by_label("Hue").expect("the ring");
|
||||
fixture.access(AccessActionKind::Focus, &hue);
|
||||
fixture.idle(2);
|
||||
let focused = |fixture: &Fixture| {
|
||||
let tree = fixture.tree();
|
||||
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
|
||||
};
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("Hue"), "{inner:?}: the ring takes focus");
|
||||
keys.iter()
|
||||
.map(|mods| {
|
||||
fixture.key(Key::Tab, *mods);
|
||||
fixture.idle(2);
|
||||
focused(&fixture)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// In an arena, as in a docked panel, Tab from the hue ring lands on the saturation and brightness control, also when a
|
||||
/// square shows it through its own folded picker, then goes on past the wheel; Shift-Tab comes back the same way.
|
||||
#[trial]
|
||||
fn in_an_arena_tab_from_the_ring_reaches_the_saturation_and_brightness_control() {
|
||||
let (on, back) = (Modifiers::NONE, Modifiers::SHIFT);
|
||||
for inner in [WheelInner::Triangle, WheelInner::Square] {
|
||||
let walk = arena_tab_walk(inner, &[on, on, back, back]);
|
||||
let expected = ["Saturation and brightness", "After", "Saturation and brightness", "Hue"].map(|name| Some(name.to_owned()));
|
||||
assert_eq!(walk, expected, "{inner:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A square wheel hands a press between the square and the ring to the square; its named markers speak their colour,
|
||||
/// pick on a click, and a press held on one still drags the ring; Shift snaps a ring drag to 45 degrees, in both
|
||||
/// variants.
|
||||
|
||||
@@ -1,13 +1,49 @@
|
||||
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, and its swatch size.
|
||||
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, its swatch size and its ring.
|
||||
|
||||
use craft_color_ui::ui::{Paint, PaintChip, PaintChipSize};
|
||||
use craft_color_ui::ui::{GradientPreview, Paint, PaintChip, PaintChipSize};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::PopupMark;
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, Shape};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Every shape of the frame, groups opened.
|
||||
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
|
||||
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
|
||||
}
|
||||
|
||||
/// A ring chip wider than it is high keeps an open middle: the hole inside the band is at least a third of the chip's
|
||||
/// height, and the band is as thick at the sides as at the top and bottom. Checked for a solid paint, drawn as a band
|
||||
/// of the colour, and for a gradient, whose middle is covered by the surface the chip sits on.
|
||||
#[trial]
|
||||
fn a_wide_ring_chip_keeps_an_open_middle() {
|
||||
let gradient = GradientPreview::new(vec![(0.0, Srgba::rgb(0.2, 0.4, 0.8)), (1.0, Srgba::WHITE)]);
|
||||
for paint in [Paint::Solid(Srgba::rgb(0.2, 0.4, 0.8)), Paint::Gradient(gradient)] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut paint = paint.clone();
|
||||
let _ = PaintChip::new("Stroke", Bind::bound(&mut paint), Srgba::BLACK).ring(true).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let well = fixture.by_role(Role::COLOR_WELL).first().copied().expect("the chip is a colour well").rect;
|
||||
assert!(well.width() > well.height(), "the chip is wider than it is high");
|
||||
// The hole is the smallest rect drawn round the well's centre.
|
||||
let hole = flat(fixture.frame_shapes())
|
||||
.into_iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::Rect(rect) => Some(rect.rect),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|rect: &Rect| rect.center().distance(well.center()) < 0.5 && rect.width() < well.width() - 2.0)
|
||||
.min_by(|a, b| a.area().total_cmp(&b.area()))
|
||||
.expect("a hole inside the band");
|
||||
assert!(hole.height() >= well.height() / 3.0, "the hole is {:?} in a {:?} well", hole.size(), well.size());
|
||||
let (side, top) = (hole.left() - well.left(), hole.top() - well.top());
|
||||
assert!((side - top).abs() < 0.5, "the band is {side} at the sides and {top} at the top");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the menu mark, past the well, opens the chip's popover, as a click on the well does.
|
||||
#[trial]
|
||||
fn a_click_on_the_menu_mark_opens_the_popover() {
|
||||
|
||||
@@ -7,15 +7,17 @@ use std::rc::Rc;
|
||||
use craft_behavior::{EditEvent, Mixed, Selection};
|
||||
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
|
||||
use craft_color_ui::ui::{
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey,
|
||||
SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows,
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
|
||||
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
SwatchesWords, swatch_rows,
|
||||
};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::{ColorModel as _, HsbModel, Srgba};
|
||||
use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::{Label, Scale};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
@@ -254,6 +256,36 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
|
||||
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
|
||||
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
|
||||
#[trial]
|
||||
fn a_fill_stroke_spectrum_keeps_its_end_boxes_square_in_a_content_sized_host() {
|
||||
for (room, content_sized) in [(COLOR_ROOM, true), (Vec2::new(280.0, 96.0), false)] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let show = |ui: &mut egui::Ui, state: &mut ColorPanelState| {
|
||||
let _ = ColorPanel::new(Bind::bound(state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke).show(ui);
|
||||
};
|
||||
if content_sized {
|
||||
let _ = Stack::new().show(ui, |ui, _| show(ui, &mut state));
|
||||
} else {
|
||||
show(ui, &mut state);
|
||||
}
|
||||
});
|
||||
fixture.room(room).settle();
|
||||
let bar = fixture.by_label("Color Ramp").expect("the spectrum").rect;
|
||||
let ends: Vec<_> = fixture
|
||||
.by_role(Role::BUTTON)
|
||||
.into_iter()
|
||||
.filter(|button| button.rect.left() >= bar.right() - 0.5 && button.rect.y_range().intersects(bar.y_range()))
|
||||
.collect();
|
||||
assert_eq!(ends.len(), 2, "{room:?}: the white and black boxes beside the bar ({bar:?})");
|
||||
for end in ends {
|
||||
assert!(end.rect.height() >= end.rect.width() - 0.5, "{room:?}: an end box at least square ({:?} beside {bar:?})", end.rect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SWATCHES: [(&str, [f32; 3]); 6] = [
|
||||
("Red", [0.90, 0.28, 0.30]),
|
||||
("Orange", [0.97, 0.42, 0.08]),
|
||||
@@ -408,6 +440,28 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
|
||||
}
|
||||
|
||||
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
|
||||
/// it; a host that gives no recent colors gets no row.
|
||||
#[trial]
|
||||
fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() {
|
||||
let caption = |recent: Option<&'static [Srgba]>| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
|
||||
let _ = match recent {
|
||||
Some(colors) => panel.recent(colors),
|
||||
None => panel,
|
||||
}
|
||||
.show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
fixture.texts().iter().any(|run| run.text == "Recent Colors")
|
||||
};
|
||||
assert!(caption(Some(&[])), "an empty list shows the row's caption");
|
||||
assert!(caption(Some(&RECENT)), "a list with a color shows it");
|
||||
assert!(!caption(None), "a host with no recent colors shows no row");
|
||||
}
|
||||
|
||||
/// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first;
|
||||
/// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`.
|
||||
#[trial]
|
||||
@@ -541,6 +595,30 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
|
||||
}
|
||||
|
||||
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
|
||||
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
|
||||
#[trial]
|
||||
fn swatches_outside_every_group_show_without_a_header() {
|
||||
let entry = |name: &str, rgb: [f32; 3]| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(rgb));
|
||||
let groups = vec![
|
||||
SwatchGroup { name: String::new(), entries: vec![entry("Red", [1.0, 0.0, 0.0]), entry("Blue", [0.0, 0.0, 1.0])] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Green", [0.0, 1.0, 0.0])] },
|
||||
];
|
||||
let (fixture, _) = swatches_rig(groups, SwatchesState::default());
|
||||
let tree = fixture.tree();
|
||||
let unnamed: Vec<_> = tree
|
||||
.keys()
|
||||
.into_iter()
|
||||
.filter(|&key| matches!(tree.role_of(key), Some(Role::HEADING | Role::BUTTON)))
|
||||
.filter(|&key| tree.name_of(key).is_none_or(|name| name.is_empty() || name.starts_with(',')))
|
||||
.map(|key| (tree.role_of(key), tree.name_of(key), tree.bounds_of(key)))
|
||||
.collect();
|
||||
assert!(unnamed.is_empty(), "every heading and button is named, starting with a label: {unnamed:?}");
|
||||
assert!(fixture.by_label("Red, #ff0000").is_some(), "the ungrouped swatches show");
|
||||
let headings: Vec<_> = tree.with_role(Role::HEADING).into_iter().filter_map(|key| tree.name_of(key)).collect();
|
||||
assert!(headings.iter().any(|name| name.starts_with("Other")), "a named group keeps its header: {headings:?}");
|
||||
}
|
||||
|
||||
/// Tb-8 (5): a click uses any swatch, as production applied every one: a colour swatch reports its colour, and a
|
||||
/// gradient, pattern or None swatch reports where it is with no colour, for the host to apply its paint. The panel
|
||||
/// reported only colour swatches.
|
||||
@@ -628,6 +706,34 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
|
||||
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
|
||||
/// swatch of the same name opens no field, and Enter there renames nothing.
|
||||
#[trial]
|
||||
fn a_rename_left_open_stays_with_its_document() {
|
||||
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
|
||||
let groups = vec![SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] }];
|
||||
let document = Rc::new(Cell::new(1_u32));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let (shown, seen) = (Rc::clone(&document), Rc::clone(&edits));
|
||||
let mut state = SwatchesState::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED).document(shown.get()).show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
});
|
||||
fixture.room(Vec2::new(320.0, 400.0)).settle();
|
||||
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
|
||||
fixture.click(&red).key(Key::F2, Modifiers::NONE).type_text("X").settle();
|
||||
let typed = |fixture: &Fixture, text: &str| {
|
||||
let tree = fixture.tree();
|
||||
tree.keys().into_iter().any(|key| tree.value_of(key) == Some(text))
|
||||
};
|
||||
assert!(typed(&fixture, "X"), "the rename field is open in the first document");
|
||||
document.set(2);
|
||||
fixture.settle();
|
||||
fixture.type_text("Y").key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
|
||||
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
|
||||
}
|
||||
@@ -768,3 +874,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() {
|
||||
fixture.click(&marker).idle(1);
|
||||
assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker");
|
||||
}
|
||||
|
||||
/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its
|
||||
/// right edge.
|
||||
#[trial]
|
||||
fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
|
||||
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let grid = fixture.by_label("Variations").expect("the variations grid").rect;
|
||||
let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted"));
|
||||
let (shades, tints) = (run("Shades"), run("Tints"));
|
||||
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
|
||||
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
|
||||
}
|
||||
@@ -32,6 +32,10 @@ craft-flags = { workspace = true, optional = true }
|
||||
dirs = { version = "7", optional = true }
|
||||
log = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours).
|
||||
craft-platform = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
+268
-119
@@ -101,7 +101,7 @@ impl App {
|
||||
/// Record `port` as the running app's, readable only by the user like the token files.
|
||||
pub fn write_current_port(&self, port: u16) -> Result<PathBuf> {
|
||||
let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;
|
||||
self.write_token_file(&path, &port.to_string())?;
|
||||
self.write_private(&path, &port.to_string(), true)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -141,16 +141,27 @@ impl App {
|
||||
}
|
||||
|
||||
/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`
|
||||
/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one
|
||||
/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file
|
||||
/// is removed and no token is written. A file left by an earlier launch is replaced. The process
|
||||
/// file beside it ([`pid_path`]) records this process, best effort.
|
||||
/// and the file `0600` on Unix; on Windows the file is created with an access list of the user
|
||||
/// and SYSTEM only and the token is written through the handle that created it
|
||||
/// (`create_for_user`), so the file never has its folder's access list. A file left by an
|
||||
/// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process,
|
||||
/// best effort.
|
||||
pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> {
|
||||
self.write_private(path, token, false)
|
||||
}
|
||||
|
||||
/// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while
|
||||
/// this one was being created is replaced (the discovery file, which names the latest launch);
|
||||
/// otherwise this write fails and that launch's token stays.
|
||||
fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some());
|
||||
let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace);
|
||||
#[cfg(not(windows))]
|
||||
let restrict = |_: &Path| Ok(());
|
||||
write_token_file_with(path, token, restrict)
|
||||
let create = {
|
||||
let _ = replace;
|
||||
create_new_file
|
||||
};
|
||||
write_token_file_with(path, token, create)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows).
|
||||
fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
|
||||
/// [`App::write_token_file`], with `create` making the new file with its contents, readable only
|
||||
/// by the user.
|
||||
fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> {
|
||||
let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let _ = std::fs::remove_file(path);
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let opened = opts.open(path)?;
|
||||
// On a refusal the file goes with the closure, so it is closed before it is removed.
|
||||
let mut f = match restrict(path).map(|()| opened) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
f.write_all(token.as_bytes())?;
|
||||
f.write_all(b"\n")?;
|
||||
f.sync_all()?;
|
||||
create(path, format!("{token}\n").as_bytes())?;
|
||||
let pid = std::process::id();
|
||||
let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));
|
||||
let _ = std::fs::write(pid_path(path), line);
|
||||
@@ -369,74 +367,148 @@ fn held_by_another(path: &Path, token: &str) -> bool {
|
||||
read_token(path).is_some_and(|held| !tokens_match(&held, token.trim()))
|
||||
}
|
||||
|
||||
/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process
|
||||
/// is left suspended (security software holding it), and waiting on it without a limit froze
|
||||
/// the app.
|
||||
#[cfg(windows)]
|
||||
const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// How a run of `icacls` ended.
|
||||
#[cfg(any(windows, test))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum IcaclsEnd {
|
||||
Succeeded,
|
||||
Failed,
|
||||
/// It didn't finish within [`ICACLS_LIMIT`] and was ended.
|
||||
TimedOut,
|
||||
/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a
|
||||
/// file created this way has its folder's access list; the token file there is made by
|
||||
/// `create_for_user`.
|
||||
fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let mut f = opts.open(path)?;
|
||||
f.write_all(contents)?;
|
||||
f.sync_all()
|
||||
}
|
||||
|
||||
/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is
|
||||
/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder,
|
||||
/// the user's own local app data, which other users can't read by default; nothing is known about
|
||||
/// the permissions of any other folder.
|
||||
/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell;
|
||||
/// on some computers a new process is left suspended (security software holding it), and waiting
|
||||
/// on it without a limit froze the app.
|
||||
#[cfg(windows)]
|
||||
const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Windows: create `path` with the current user as owner and an access list of that user and
|
||||
/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written
|
||||
/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`.
|
||||
/// Another account never gets a moment in which the file has its folder's access list and could be
|
||||
/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names;
|
||||
/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and
|
||||
/// what `replace` changes.
|
||||
#[cfg(windows)]
|
||||
fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> {
|
||||
use craft_platform::owner_only;
|
||||
/// How many creates that were not waited for are still running.
|
||||
static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c));
|
||||
create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0
|
||||
}
|
||||
|
||||
/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names
|
||||
/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that
|
||||
/// folder's permissions; in the default folder, the user's own local app data, which other users
|
||||
/// can't read by default, `path` created with that folder's access list ([`create_new_file`]).
|
||||
#[cfg(any(windows, test))]
|
||||
fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> {
|
||||
match end {
|
||||
IcaclsEnd::Succeeded => Ok(()),
|
||||
IcaclsEnd::TimedOut if !custom_folder => Ok(()),
|
||||
IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))),
|
||||
IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))),
|
||||
fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> {
|
||||
if custom_folder {
|
||||
Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display())))
|
||||
} else {
|
||||
create_new_file(path, contents)
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows: drop inherited entries and grant only the current user full access. An `icacls`
|
||||
/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means.
|
||||
#[cfg(windows)]
|
||||
fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?;
|
||||
let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty());
|
||||
let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}"));
|
||||
let child = std::process::Command::new("icacls")
|
||||
.arg(path)
|
||||
.args(["/inheritance:r", "/grant:r", &format!("{who}:F")])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.creation_flags(0x0800_0000)
|
||||
.spawn()?;
|
||||
let end = match wait_within(child, ICACLS_LIMIT)? {
|
||||
Some(status) if status.success() => IcaclsEnd::Succeeded,
|
||||
Some(_) => IcaclsEnd::Failed,
|
||||
None => IcaclsEnd::TimedOut,
|
||||
/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its
|
||||
/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path`
|
||||
/// (`.<name>.<process id>.<count>.tmp`), and the file takes the name `path` only once `private`
|
||||
/// has finished, so `path` never holds a file that is still being written: with `replace` by a
|
||||
/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`],
|
||||
/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool
|
||||
/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result.
|
||||
/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its
|
||||
/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any
|
||||
/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that
|
||||
/// leaves new processes suspended holds at most the threads that were started together. The
|
||||
/// thread's handle is returned for tests.
|
||||
#[cfg(any(windows, test))]
|
||||
fn create_within(
|
||||
path: &Path,
|
||||
contents: &[u8],
|
||||
custom_folder: bool,
|
||||
replace: bool,
|
||||
limit: std::time::Duration,
|
||||
stuck: &'static std::sync::atomic::AtomicUsize,
|
||||
private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static,
|
||||
) -> (Result<()>, Option<std::thread::JoinHandle<()>>) {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{RecvTimeoutError, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
/// Numbers the thread's files within this process.
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
if stuck.load(Ordering::Acquire) > 0 {
|
||||
return (not_waited_for(path, contents, custom_folder), None);
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
|
||||
let (sender, receiver) = channel();
|
||||
// Set under the lock when the caller stops waiting; the thread reads it under the same lock
|
||||
// before it reports, so its result is either received or its file is removed.
|
||||
let abandoned = Arc::new(Mutex::new(false));
|
||||
let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned));
|
||||
let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || {
|
||||
let made = private(&own_file, &owned_contents);
|
||||
let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if *abandoned {
|
||||
let _ = std::fs::remove_file(&own_file);
|
||||
stuck.fetch_sub(1, Ordering::AcqRel);
|
||||
} else {
|
||||
let _ = sender.send(made);
|
||||
}
|
||||
});
|
||||
let handle = match spawned {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => return (Err(e), None),
|
||||
};
|
||||
restriction_result(end, custom_folder, path)
|
||||
let made = match receiver.recv_timeout(limit) {
|
||||
Ok(made) => made,
|
||||
Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))),
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match receiver.try_recv() {
|
||||
Ok(made) => made,
|
||||
Err(_) => {
|
||||
*abandoned = true;
|
||||
stuck.fetch_add(1, Ordering::AcqRel);
|
||||
drop(abandoned);
|
||||
return (not_waited_for(path, contents, custom_folder), Some(handle));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let placed = match made {
|
||||
// `owner_only` ended a tool that ran out of its own time: the same as not waiting.
|
||||
Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder),
|
||||
made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }),
|
||||
};
|
||||
let _ = std::fs::remove_file(&staged);
|
||||
(placed, Some(handle))
|
||||
}
|
||||
|
||||
/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it
|
||||
/// hasn't finished by then.
|
||||
/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch
|
||||
/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a
|
||||
/// `create_new` there would, instead of replacing the first one's token. The new name is a hard
|
||||
/// link. On a volume without hard links the file is renamed once `path` is found free; there a
|
||||
/// launch that puts its file at `path` between that check and the rename has it replaced, as std
|
||||
/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the
|
||||
/// caller to remove.
|
||||
#[cfg(any(windows, test))]
|
||||
fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result<Option<std::process::ExitStatus>> {
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
fn place_new(staged: &Path, path: &Path) -> Result<()> {
|
||||
match std::fs::hard_link(staged, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => {
|
||||
Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display())))
|
||||
}
|
||||
if start.elapsed() >= limit {
|
||||
// Not waited for afterwards: a suspended process may not end at once.
|
||||
let _ = child.kill();
|
||||
return Ok(None);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
Err(_) => std::fs::rename(staged, path),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,50 +528,127 @@ mod tests {
|
||||
/// An app with no data folder and no environment, whose times read `t<seconds>`.
|
||||
const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 };
|
||||
|
||||
/// #6145: a child that doesn't finish in time is given up on, not waited for forever.
|
||||
#[cfg(unix)]
|
||||
/// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder
|
||||
/// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created
|
||||
/// anyway and holds the token. Either way the file the late create makes is removed when it
|
||||
/// finishes and never takes the token file's name, even when a later write has put a file
|
||||
/// there. While it runs, the next create starts no thread of its own. A create that finishes in
|
||||
/// time puts its file in place unless a file already has the name, and one that fails leaves
|
||||
/// nothing. A create that fails as timed out by itself is taken as one not waited for.
|
||||
#[test]
|
||||
fn a_slow_child_is_waited_for_only_so_long() {
|
||||
use std::time::{Duration, Instant};
|
||||
let start = Instant::now();
|
||||
let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap();
|
||||
assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none());
|
||||
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
let quick = std::process::Command::new("true").spawn().unwrap();
|
||||
assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success()));
|
||||
let failing = std::process::Command::new("false").spawn().unwrap();
|
||||
assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success()));
|
||||
}
|
||||
|
||||
/// #6145's freeze fix stays in the default folder, the user's own; a folder picked with
|
||||
/// the app's `CONTROL_DIR` gets no token unless the file was really restricted.
|
||||
#[test]
|
||||
fn only_the_default_folder_accepts_an_icacls_that_timed_out() {
|
||||
let path = Path::new("control/7878.token");
|
||||
for custom in [false, true] {
|
||||
assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok());
|
||||
assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err());
|
||||
fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::Duration;
|
||||
static STUCK: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let names = || {
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
};
|
||||
for custom in [true, false] {
|
||||
let path = dir.join("7878.port");
|
||||
let (go, wait) = channel::<()>();
|
||||
let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| {
|
||||
wait.recv().map_err(Error::other)?;
|
||||
create_new_file(p, c)
|
||||
});
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 1);
|
||||
if custom {
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
assert!(!path.exists());
|
||||
let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") };
|
||||
let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused);
|
||||
assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
assert!(none.is_none());
|
||||
// A later write of the same contents, as a retry of the same port would make.
|
||||
create_new_file(&path, b"7878\n").unwrap();
|
||||
} else {
|
||||
made.unwrap();
|
||||
}
|
||||
go.send(()).unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 0);
|
||||
assert_eq!(names(), ["7878.port"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("7878"));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok());
|
||||
let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::TimedOut);
|
||||
assert!(e.to_string().contains("7878.token"), "{e}");
|
||||
let path = dir.join("quick.token");
|
||||
let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("quick"));
|
||||
// Another launch's file at the name is kept, as `create_new` keeps it.
|
||||
let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists);
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("quick"));
|
||||
// With `replace` (the discovery file) the later launch's file takes the name.
|
||||
let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("later"));
|
||||
let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) };
|
||||
let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused);
|
||||
assert!(made.is_err());
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
// A create whose tool was ended after its own limit, within this one, is taken as one
|
||||
// that was not waited for.
|
||||
let ended =
|
||||
|_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) };
|
||||
let path = dir.join("ended.token");
|
||||
let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended);
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["ended.token", "quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("ended"));
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A file that couldn't be restricted is removed, empty and with no process file beside it, and
|
||||
/// the error goes to the caller. A restricted one gets its token.
|
||||
/// A file that couldn't be created leaves no process file beside it, and the error goes to the
|
||||
/// caller. A created one gets the token and a newline.
|
||||
#[test]
|
||||
fn a_token_file_that_could_not_be_restricted_is_removed() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id()));
|
||||
fn a_token_file_that_could_not_be_created_leaves_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id()));
|
||||
let path = dir.join("7879.token");
|
||||
let e = write_token_file_with(&path, "secret-token", |p| {
|
||||
assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in");
|
||||
restriction_result(IcaclsEnd::TimedOut, true, p)
|
||||
})
|
||||
.unwrap_err();
|
||||
let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::TimedOut);
|
||||
assert!(!path.exists() && !pid_path(&path).exists());
|
||||
write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap();
|
||||
write_token_file_with(&path, "secret-token", create_new_file).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n");
|
||||
assert!(pid_path(&path).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// On Windows the token file is its user's alone from the moment it exists: in a folder that
|
||||
/// lets Users read what is created in it, the file has no entry for Users and no other
|
||||
/// account's access.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_token_file_is_private_from_the_start_on_windows() {
|
||||
use craft_platform::owner_only;
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
|
||||
let path = dir.join("7880.token");
|
||||
TEST.write_token_file(&path, "secret-token").unwrap();
|
||||
let sddl = owner_only::sddl_of(&path).unwrap();
|
||||
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
|
||||
assert_eq!(read_token(&path).as_deref(), Some("secret-token"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -942,6 +942,7 @@ ui-system_fonts = ["ui", "craft-ui/system_fonts"]
|
||||
ui-testing = ["ui", "craft-ui/testing"]
|
||||
|
||||
update = ["dep:craft-update"] # native only: downloads and installs through getrandom without wasm support
|
||||
update-local-mirror = ["update", "craft-update/local-mirror"]
|
||||
update-oci_migration = ["update", "craft-update/oci_migration"]
|
||||
|
||||
usd = ["dep:craft-usd"]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
|
||||
pub const GIT: &str = "https://github.com/storytold/egui.git";
|
||||
/// The commit of [`GIT`].
|
||||
pub const REV: &str = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec";
|
||||
pub const REV: &str = "b9770908e0f304896f9658d239a7b29cf8af1564";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
/// Crates the facade leaves out, by directory, with the reason. Everything else under `crates/` is a member.
|
||||
pub const NOT_IN_FACADE: &[(&str, &str)] = &[
|
||||
("appkit", "the `unsafe` AppKit observers behind a safe API, used by craft-window"),
|
||||
("appkit", "the `unsafe` AppKit calls behind a safe API, used by craft-window and craft-dialogs"),
|
||||
("design-lint", "a lint template and checker for apps' clippy.toml, run from xtask"),
|
||||
("feature-root", "a build tool: the dependency set tools/cl resolves every local build's features with; never built"),
|
||||
("fonts-build", "a build-script helper; apps call it from build.rs"),
|
||||
|
||||
@@ -31,13 +31,14 @@ serde_json = { workspace = true, optional = true }
|
||||
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] }
|
||||
|
||||
# The file-dialog probe asks the session bus whether the desktop portal offers a file chooser.
|
||||
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`). rfd and winit already
|
||||
# use these.
|
||||
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`), and the Save sheet with a
|
||||
# Format menu (`beginSheetModalForWindow:completionHandler:`). rfd and winit already use these.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6.2"
|
||||
craft-appkit = { workspace = true }
|
||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSApplication", "NSOpenPanel", "NSPanel", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSString", "NSURL"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSAccessibilityProtocols", "NSApplication", "NSButton", "NSControl", "NSOpenPanel", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSText", "NSTextField", "NSView", "NSWindow", "objc2-core-foundation"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSString", "NSURL", "objc2-core-foundation"] }
|
||||
|
||||
# The Linux and BSD Save panel asks the desktop portal itself, which reports the file type picked.
|
||||
# The versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the
|
||||
|
||||
@@ -44,7 +44,7 @@ pub type Override = Box<dyn FnMut(&Request) -> Answer>;
|
||||
|
||||
pub enum Kind { Open { multiple: bool }, Folder, Save }
|
||||
pub struct FileDialog { pub kind: Kind, pub title: Option<String>, pub filters: Vec<Filter>,
|
||||
pub directory: Option<PathBuf>, pub file_name: Option<String> }
|
||||
pub directory: Option<PathBuf>, pub file_name: Option<String>, pub format_label: Option<String> }
|
||||
pub struct Filter { pub name: String, pub extensions: Vec<String> }
|
||||
pub struct Message { pub level: MessageLevel, pub title: String, pub description: String,
|
||||
pub buttons: MessageButtons }
|
||||
@@ -66,7 +66,7 @@ impl<T> Dialogs<T> {
|
||||
```
|
||||
|
||||
`FileDialog` has builders: `FileDialog::open().title("Place").filter("Images", &["png", "jpg"])`,
|
||||
and `open_many`, `folder`, `save`, `directory`, `file_name`.
|
||||
and `open_many`, `folder`, `save`, `directory`, `file_name`, `format_label`.
|
||||
|
||||
In an eframe app:
|
||||
|
||||
@@ -127,6 +127,12 @@ they start only with a parent in a running app, and answer `Unavailable` otherwi
|
||||
before the event loop starts or after it ends (startup and crash messages) stay blocking `rfd`
|
||||
calls in the app.
|
||||
|
||||
A Save that offers two or more file types is a sheet the crate makes itself, with a Format menu
|
||||
that lists each type by name, the suggested name's type chosen. Choosing a type changes the
|
||||
extension in the name field, and the answer is `Saved` with the chosen type's index in `filter`.
|
||||
The menu's label is `FileDialog::format_label`, set from `FilePanels::set_format_label` (English
|
||||
"Format:" when unset). A Save with one type is rfd's sheet, which has no menu.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- Linux portal Save (`org.freedesktop.portal.FileChooser.SaveFile`), so the file type the user
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The Format menu of a macOS Save panel with two or more file types: which types it lists, which one is chosen
|
||||
//! when the panel opens, the name a choice gives the file and the extensions the panel then allows. Plain rules on
|
||||
//! names and filters, so they are tested on every platform; `macos.rs` shows the menu.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::Filter;
|
||||
use crate::service::normal;
|
||||
|
||||
/// The indices into `filters` of the file types the menu lists, in order: types with an extension other than `*`.
|
||||
/// Empty when fewer than two remain: the panel then has no menu.
|
||||
pub(crate) fn entries(filters: &[Filter]) -> Vec<usize> {
|
||||
let listed: Vec<usize> = filters
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| f.extensions.iter().any(|e| !normal(e).is_empty()) && !f.extensions.iter().any(|e| normal(e) == "*"))
|
||||
.map(|(at, _)| at)
|
||||
.collect();
|
||||
if listed.len() < 2 { Vec::new() } else { listed }
|
||||
}
|
||||
|
||||
/// The menu's item titles for `entries`, one per entry and all different: a pop-up menu keeps one item per title, so
|
||||
/// a name that repeats gets its extensions after it (`Document (docx)`), and a title that still matches an earlier
|
||||
/// title or another type's name gets a number after it.
|
||||
pub(crate) fn titles(filters: &[Filter], entries: &[usize]) -> Vec<String> {
|
||||
let names: Vec<&str> = entries.iter().map(|&at| filters.get(at).map_or("", |f| f.name.as_str())).collect();
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for (&at, name) in entries.iter().zip(&names) {
|
||||
let mut base = (*name).to_owned();
|
||||
if names.iter().filter(|n| *n == name).count() > 1 {
|
||||
let extensions: Vec<String> = filters.get(at).map(|f| f.extensions.iter().map(|e| normal(e)).collect()).unwrap_or_default();
|
||||
base = format!("{name} ({})", extensions.join(", "));
|
||||
}
|
||||
let taken = |title: &str| out.iter().any(|t| t == title) || (title != *name && names.contains(&title));
|
||||
let mut title = base.clone();
|
||||
let mut number = 2;
|
||||
while taken(&title) {
|
||||
title = format!("{base} {number}");
|
||||
number += 1;
|
||||
}
|
||||
out.push(title);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The file type a Save answer reports, as an index into `filters`: the one chosen in the menu (menu position
|
||||
/// `chosen`), unless the name the panel returned ends in an extension that only another listed type has: the user
|
||||
/// typed it, and the file is saved in that type. `kept` is the name the field still showed when the last choice could
|
||||
/// not rename it. A returned name equal to it that still has the extension of the name the panel opened with
|
||||
/// (`opened_with`) keeps the chosen type: the save flow gives a name with the opened extension the chosen type's
|
||||
/// extension (`with_chosen_type`). Any other extension stays on the name, so the type reported is the one the name has.
|
||||
pub(crate) fn answered_type(
|
||||
returned: &str,
|
||||
kept: Option<&str>,
|
||||
opened_with: Option<&str>,
|
||||
filters: &[Filter],
|
||||
entries: &[usize],
|
||||
chosen: usize,
|
||||
) -> Option<usize> {
|
||||
let chosen = entries.get(chosen).copied()?;
|
||||
let Some(ext) = extension(returned) else { return Some(chosen) };
|
||||
let kept_opened = kept == Some(returned) && opened_with.and_then(extension).as_ref() == Some(&ext);
|
||||
if filters.get(chosen).is_some_and(|f| lists(f, &ext)) || kept_opened {
|
||||
return Some(chosen);
|
||||
}
|
||||
Some(entries.iter().copied().find(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(chosen))
|
||||
}
|
||||
|
||||
/// The menu position chosen when the panel opens: the type whose extensions include `name`'s, else the first.
|
||||
pub(crate) fn initial(name: &str, filters: &[Filter], entries: &[usize]) -> usize {
|
||||
let Some(ext) = extension(name) else { return 0 };
|
||||
entries.iter().position(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The name the panel shows once `chosen` is picked: an extension `chosen` lists stays; one that another of
|
||||
/// `filters` lists becomes `chosen`'s first; any other is part of the name (`art.v2`), and `chosen`'s first extension
|
||||
/// is added after it. An empty name stays empty.
|
||||
pub(crate) fn renamed(name: &str, chosen: &Filter, filters: &[Filter]) -> String {
|
||||
let Some(first) = chosen.extensions.iter().map(|e| normal(e)).find(|e| !e.is_empty()) else { return name.to_owned() };
|
||||
if name.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
match extension(name) {
|
||||
Some(ext) if lists(chosen, &ext) => name.to_owned(),
|
||||
Some(ext) if filters.iter().any(|f| lists(f, &ext)) => Path::new(name).with_extension(first).to_string_lossy().into_owned(),
|
||||
_ => format!("{name}.{first}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The extensions the panel allows with menu position `selected` chosen: that type's first, so that AppKit adds it
|
||||
/// to a name typed without one, then the other listed types', so that a name typed with one of theirs is kept.
|
||||
pub(crate) fn allowed(filters: &[Filter], entries: &[usize], selected: usize) -> Vec<String> {
|
||||
let chosen = entries.get(selected).copied();
|
||||
let order = chosen.into_iter().chain(entries.iter().copied().filter(|&at| Some(at) != chosen));
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for ext in order.filter_map(|at| filters.get(at)).flat_map(|f| f.extensions.iter().map(|e| normal(e))) {
|
||||
if !ext.is_empty() && !out.contains(&ext) {
|
||||
out.push(ext);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `name`'s extension as compared, if it has one.
|
||||
fn extension(name: &str) -> Option<String> {
|
||||
Path::new(name).extension().and_then(|e| e.to_str()).map(normal)
|
||||
}
|
||||
|
||||
/// Whether `filter` lists `ext` (already [`normal`]).
|
||||
fn lists(filter: &Filter, ext: &str) -> bool {
|
||||
filter.extensions.iter().any(|e| normal(e) == ext)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -0,0 +1,110 @@
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
fn filters() -> Vec<Filter> {
|
||||
vec![Filter::new("Document", &["doc"]), Filter::new("Drawing", &["ai"]), Filter::new("Picture", &["jpg", "jpeg"])]
|
||||
}
|
||||
|
||||
/// The menu lists the types with an extension; "every file" types and ones without an extension stay out, and a
|
||||
/// panel left with one type gets no menu.
|
||||
#[trial]
|
||||
fn the_menu_lists_types_with_extensions_and_needs_two() {
|
||||
assert_eq!(entries(&filters()), [0, 1, 2]);
|
||||
let mixed = [Filter::new("Document", &["doc"]), Filter::new("All files", &["*"]), Filter::new("Any", &[]), Filter::new("Drawing", &[".ai"])];
|
||||
assert_eq!(entries(&mixed), [0, 3], "the dot is not part of the extension");
|
||||
assert!(entries(&[Filter::new("Document", &["doc"]), Filter::new("All files", &["*"])]).is_empty());
|
||||
assert!(entries(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// Two types with one name both stay in the menu, under different titles; other titles are the names.
|
||||
#[trial]
|
||||
fn types_that_share_a_name_get_different_titles() {
|
||||
let twice = [Filter::new("Document", &["doc"]), Filter::new("Document", &["docx"]), Filter::new("Drawing", &["ai"])];
|
||||
let listed = entries(&twice);
|
||||
assert_eq!(listed, [0, 1, 2]);
|
||||
let shown = titles(&twice, &listed);
|
||||
assert_eq!(shown.len(), listed.len());
|
||||
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
|
||||
assert_eq!(shown[2], "Drawing");
|
||||
for set in [
|
||||
vec![Filter::new("Document", &["doc"]), Filter::new("Document", &["doc"])],
|
||||
vec![Filter::new("X (x) 2", &["a"]), Filter::new("X", &["x"]), Filter::new("X", &["x"])],
|
||||
vec![Filter::new("X", &["x"]), Filter::new("X", &["x"]), Filter::new("X (x) 2", &["a"]), Filter::new("X (x)", &["b"])],
|
||||
] {
|
||||
let shown = titles(&set, &entries(&set));
|
||||
assert_eq!(shown.len(), set.len());
|
||||
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer reports the chosen type, unless the user typed another listed type's extension; a name the panel kept
|
||||
/// when a choice could not rename it keeps the chosen type.
|
||||
#[trial]
|
||||
fn a_typed_extension_of_another_type_is_the_type_saved() {
|
||||
let all = filters();
|
||||
let listed = entries(&all);
|
||||
let (kept, opened) = (Some("Untitled-1.doc"), Some("Untitled-1.doc"));
|
||||
let answer = |returned, kept| answered_type(returned, kept, opened, &all, &listed, 1);
|
||||
assert_eq!(answer("Untitled-1.ai", None), Some(1));
|
||||
assert_eq!(answer("Untitled-1.doc", kept), Some(1), "the panel kept the opened name");
|
||||
assert_eq!(answer("Other.doc", kept), Some(0), "the user typed a new name after that");
|
||||
assert_eq!(answer("Untitled-1.doc", None), Some(0), "the user typed the first type's extension back");
|
||||
assert_eq!(answer("photo.JPEG", kept), Some(2), "the user typed another type's extension");
|
||||
assert_eq!(answer("Other.doc", Some("Other.doc")), Some(1), "a kept name with the opened extension");
|
||||
assert_eq!(answer("Other.jpg", Some("Other.jpg")), Some(2), "a kept name with another type's extension keeps that type");
|
||||
assert_eq!(answer("notes.v2", None), Some(1));
|
||||
assert_eq!(answer("art", None), Some(1));
|
||||
assert_eq!(answered_type("art.ai", None, opened, &all, &listed, 9), None, "a position the menu doesn't have");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_suggested_name_chooses_its_type_and_any_other_the_first() {
|
||||
let all = filters();
|
||||
let listed = entries(&all);
|
||||
for (name, at) in [("Untitled-1.doc", 0), ("art.AI", 1), ("photo.jpeg", 2), ("Untitled-1", 0), ("notes.v2", 0), ("", 0)] {
|
||||
assert_eq!(initial(name, &all, &listed), at, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Choosing a type replaces the extension of another listed type, keeps one of its own and adds its own after any
|
||||
/// other dot in the name.
|
||||
#[trial]
|
||||
fn choosing_a_type_gives_the_name_its_extension() {
|
||||
let all = filters();
|
||||
let drawing = &all[1];
|
||||
for (name, expected) in [
|
||||
("Untitled-1.doc", "Untitled-1.ai"),
|
||||
("Plan 1.DOC", "Plan 1.ai"),
|
||||
("photo.jpeg", "photo.ai"),
|
||||
("art.ai", "art.ai"),
|
||||
("art.AI", "art.AI"),
|
||||
("art", "art.ai"),
|
||||
("art.v2", "art.v2.ai"),
|
||||
("", ""),
|
||||
] {
|
||||
assert_eq!(renamed(name, drawing, &all), expected, "{name}");
|
||||
}
|
||||
assert_eq!(renamed("photo.jpeg", &all[2], &all), "photo.jpeg", "a second extension of the chosen type stays");
|
||||
}
|
||||
|
||||
/// A sequence of choices (A to B to C) ends with C's extension, and back to A gives A's.
|
||||
#[trial]
|
||||
fn each_choice_follows_the_previous_one() {
|
||||
let all = filters();
|
||||
let mut name = "Untitled-1.doc".to_owned();
|
||||
for (at, ext) in [(1, "ai"), (2, "jpg"), (0, "doc")] {
|
||||
name = renamed(&name, &all[at], &all);
|
||||
assert_eq!(Path::new(&name).extension().and_then(|e| e.to_str()), Some(ext));
|
||||
assert_eq!(Path::new(&name).file_stem().and_then(|e| e.to_str()), Some("Untitled-1"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen type's extension comes first, so AppKit adds it to a bare name; the others stay allowed.
|
||||
#[trial]
|
||||
fn the_chosen_type_is_allowed_first() {
|
||||
let all = filters();
|
||||
let listed = entries(&all);
|
||||
assert_eq!(allowed(&all, &listed, 0), ["doc", "ai", "jpg", "jpeg"]);
|
||||
assert_eq!(allowed(&all, &listed, 1), ["ai", "doc", "jpg", "jpeg"]);
|
||||
assert_eq!(allowed(&all, &listed, 2), ["jpg", "jpeg", "doc", "ai"]);
|
||||
}
|
||||
@@ -20,6 +20,8 @@
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod filter;
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod format_menu;
|
||||
mod native;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
pub(crate) mod portal;
|
||||
@@ -92,12 +94,18 @@ pub struct FileDialog {
|
||||
pub directory: Option<PathBuf>,
|
||||
/// The file name a Save dialog suggests.
|
||||
pub file_name: Option<String>,
|
||||
/// The label of the file type menu a macOS Save panel with two or more file types shows; `None` shows
|
||||
/// [`FORMAT_LABEL`]. Other platforms' dialogs label their menu themselves.
|
||||
pub format_label: Option<String>,
|
||||
}
|
||||
|
||||
/// The English label of the macOS Save panel's file type menu.
|
||||
pub const FORMAT_LABEL: &str = "Format:";
|
||||
|
||||
impl FileDialog {
|
||||
/// A dialog of `kind` with nothing else set.
|
||||
pub fn new(kind: Kind) -> Self {
|
||||
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None }
|
||||
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None, format_label: None }
|
||||
}
|
||||
|
||||
/// Choose one existing file.
|
||||
@@ -143,6 +151,12 @@ impl FileDialog {
|
||||
self.file_name = Some(file_name.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the label of the macOS Save panel's file type menu, in the app's language.
|
||||
pub fn format_label(mut self, label: impl Into<String>) -> Self {
|
||||
self.format_label = Some(label.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The icon a message box shows.
|
||||
@@ -223,7 +237,7 @@ pub enum Answer {
|
||||
/// The chosen files or folder.
|
||||
Paths(Vec<PathBuf>),
|
||||
/// A Save panel's answer: the name as typed and the file type picked, when the panel reports it (the portal's
|
||||
/// current filter; rfd reports `None`).
|
||||
/// current filter, or the macOS panel's Format menu; rfd reports `None`).
|
||||
Saved {
|
||||
/// The name as typed.
|
||||
path: PathBuf,
|
||||
|
||||
+142
-8
@@ -6,22 +6,29 @@
|
||||
//! rfd can't show this panel: its async dialogs always begin a sheet, on the main or first window
|
||||
//! when no parent is given (rfd 0.17.2 `backend/macos/modal_future.rs:71-102`).
|
||||
//!
|
||||
//! Save and message boxes are sheets on the parent window through rfd, as native apps show them.
|
||||
//! rfd falls back to the blocking `runModal` when the app isn't running or has no window
|
||||
//! (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
|
||||
//! Save and message boxes are sheets on the parent window, as native apps show them. A Save that
|
||||
//! offers two or more file types is a sheet made here ([`show_save_sheet`]), with a Format menu:
|
||||
//! rfd's Save panel lists the extensions of every type and has no menu to choose one
|
||||
//! (rfd 0.17.2 `backend/macos/file_dialog/panel_ffi.rs:107-120`). Other Saves and message boxes
|
||||
//! are rfd's sheets. rfd falls back to the blocking `runModal` when the app isn't running or has no
|
||||
//! window (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
|
||||
//! running app.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::ffi::c_void;
|
||||
use std::rc::Rc;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2::rc::Retained;
|
||||
use objc2_app_kit::{NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSView};
|
||||
use objc2_foundation::{NSArray, NSString, NSURL};
|
||||
use objc2::MainThreadOnly;
|
||||
use objc2::rc::{Retained, Weak};
|
||||
use objc2_app_kit::{
|
||||
NSAccessibility, NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSPopUpButton, NSSavePanel, NSTextField, NSView, NSWindow,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
|
||||
use crate::{Answer, FileDialog, Kind, Reply};
|
||||
use crate::{Answer, FORMAT_LABEL, FileDialog, Filter, Kind, Reply, format_menu};
|
||||
|
||||
const NOT_MAIN: &str = "dialogs show from the main thread only";
|
||||
const NOT_RUNNING: &str = "the app isn't running yet, so the dialog can't be shown";
|
||||
@@ -62,6 +69,133 @@ fn contains(root: &NSView, view: *const c_void) -> bool {
|
||||
std::ptr::eq((root as *const NSView).cast(), view) || root.subviews().iter().any(|child| contains(&child, view))
|
||||
}
|
||||
|
||||
/// The app's window that `parent`'s view is in.
|
||||
fn window_of<W: HasWindowHandle>(mtm: MainThreadMarker, parent: &W) -> Option<Retained<NSWindow>> {
|
||||
let view = match parent.window_handle().map(|h| h.as_raw()) {
|
||||
Ok(RawWindowHandle::AppKit(h)) => h.ns_view.as_ptr().cast_const(),
|
||||
_ => return None,
|
||||
};
|
||||
NSApplication::sharedApplication(mtm).windows().iter().find(|window| window.contentView().is_some_and(|content| contains(&content, view)))
|
||||
}
|
||||
|
||||
/// The Format menu's height and the room around and between its label and menu, in points.
|
||||
const ACCESSORY_HEIGHT: f64 = 38.0;
|
||||
const MARGIN: f64 = 12.0;
|
||||
const GAP: f64 = 8.0;
|
||||
/// The Format menu's size, in points.
|
||||
const MENU: NSSize = NSSize::new(260.0, 26.0);
|
||||
|
||||
/// Shows a Save sheet with a Format menu on `parent` (a [`sheet_parent`]) when `d` offers two or more file types
|
||||
/// ([`format_menu::entries`]), and answers through `reply` with the type chosen in the menu. Choosing a type puts the
|
||||
/// type's extensions first in the allowed types, which AppKit adds to a name typed without one, and sets the name
|
||||
/// field to [`format_menu::renamed`]. The SDK's `NSSavePanel.h` says the name field can only be set while the panel is
|
||||
/// configured; macOS 27.2 shows the new name. Where a system keeps the suggested name, the answer's `filter` still names the chosen
|
||||
/// type, so the save flow settles the extension (`ExtensionPolicy::picked_type`, or the app's own rule) and asks
|
||||
/// before replacing a file the panel did not ask about; a kept name with another extension reports that extension's
|
||||
/// type ([`format_menu::answered_type`]). Gives `reply` back when `d` offers fewer types, for rfd's panel.
|
||||
///
|
||||
/// The menu is the panel's accessory view, set before `beginSheetModalForWindow:completionHandler:` shows the sheet:
|
||||
/// an accessory set after the sheet began made macOS dismiss the sheet at once (storytold/vectorcraft#1800). The
|
||||
/// completion handler holds the panel, the menu and the menu's target until the sheet closes; the target holds the
|
||||
/// panel weakly.
|
||||
pub(crate) fn show_save_sheet<W: HasWindowHandle>(d: &FileDialog, parent: &W, reply: Reply) -> Result<(), Reply> {
|
||||
let entries = format_menu::entries(&d.filters);
|
||||
if entries.is_empty() {
|
||||
return Err(reply);
|
||||
}
|
||||
let Some(mtm) = MainThreadMarker::new() else { return Err(reply) };
|
||||
let Some(window) = window_of(mtm, parent) else { return Err(reply) };
|
||||
let Some(panel) = craft_appkit::save_panel::new_save_panel(mtm) else {
|
||||
reply.send(Answer::Unavailable("macOS returned no Save panel".into()));
|
||||
return Ok(());
|
||||
};
|
||||
let name = d.file_name.clone().unwrap_or_default();
|
||||
let selected = format_menu::initial(&name, &d.filters, &entries);
|
||||
set_allowed_types(&panel, &d.filters, &entries, selected);
|
||||
if let Some(title) = &d.title {
|
||||
panel.setMessage(Some(&NSString::from_str(title)));
|
||||
}
|
||||
if let Some(directory) = d.directory.as_deref().and_then(NSURL::from_directory_path) {
|
||||
panel.setDirectoryURL(Some(&directory));
|
||||
}
|
||||
panel.setExtensionHidden(false);
|
||||
if !name.is_empty() {
|
||||
panel.setNameFieldStringValue(&NSString::from_str(&name));
|
||||
}
|
||||
let label = d.format_label.as_deref().unwrap_or(FORMAT_LABEL);
|
||||
let (accessory, popup) = accessory(mtm, label, &d.filters, &entries, selected);
|
||||
panel.setAccessoryView(Some(&accessory));
|
||||
|
||||
// The name the field kept when the last choice could not rename it.
|
||||
let kept: Rc<RefCell<Option<String>>> = Rc::default();
|
||||
let (filters, listed, weak, kept_by_choice) = (d.filters.clone(), entries.clone(), Weak::new(&*panel), kept.clone());
|
||||
let choice = craft_appkit::save_panel::on_choose(mtm, &popup, move |at| {
|
||||
let (Some(panel), Some(chosen)) = (weak.load(), listed.get(at).and_then(|&i| filters.get(i))) else { return };
|
||||
set_allowed_types(&panel, &filters, &listed, at);
|
||||
let name = panel.nameFieldStringValue().to_string();
|
||||
let new_name = format_menu::renamed(&name, chosen, &filters);
|
||||
panel.setNameFieldStringValue(&NSString::from_str(&new_name));
|
||||
let shown = panel.nameFieldStringValue().to_string();
|
||||
*kept_by_choice.borrow_mut() = (shown != new_name).then_some(shown);
|
||||
});
|
||||
let reply = Cell::new(Some(reply));
|
||||
let answered = panel.clone();
|
||||
let (filters, opened_with) = (d.filters.clone(), d.file_name.clone());
|
||||
let handler = RcBlock::new(move |response: NSModalResponse| {
|
||||
// The menu sends its action to `choice` while the sheet is open; the handler keeps it until then.
|
||||
let _target = &choice;
|
||||
let Some(reply) = reply.take() else { return };
|
||||
if response != NSModalResponseOK {
|
||||
return reply.send(Answer::Cancelled);
|
||||
}
|
||||
let Some(path) = answered.URL().and_then(|url| url.to_file_path()) else { return reply.send(Answer::Cancelled) };
|
||||
let returned = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let filter = usize::try_from(popup.indexOfSelectedItem())
|
||||
.ok()
|
||||
.and_then(|at| format_menu::answered_type(&returned, kept.borrow().as_deref(), opened_with.as_deref(), &filters, &entries, at));
|
||||
reply.send(Answer::Saved { path, filter });
|
||||
});
|
||||
panel.beginSheetModalForWindow_completionHandler(&window, &handler);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets `panel`'s allowed file types to [`format_menu::allowed`].
|
||||
fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], entries: &[usize], selected: usize) {
|
||||
let types: Vec<Retained<NSString>> = format_menu::allowed(filters, entries, selected).iter().map(|e| NSString::from_str(e)).collect();
|
||||
// As rfd does, and as `show_panel` does for Open.
|
||||
#[allow(deprecated)]
|
||||
panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types)));
|
||||
}
|
||||
|
||||
/// The label and the Format menu of `filters`' `entries`, `selected` chosen, in a view for the panel's accessory.
|
||||
fn accessory(
|
||||
mtm: MainThreadMarker,
|
||||
text: &str,
|
||||
filters: &[Filter],
|
||||
entries: &[usize],
|
||||
selected: usize,
|
||||
) -> (Retained<NSView>, Retained<NSPopUpButton>) {
|
||||
let label = NSTextField::labelWithString(&NSString::from_str(text), mtm);
|
||||
label.sizeToFit();
|
||||
let size = label.frame().size;
|
||||
label.setFrameOrigin(NSPoint::new(MARGIN, (ACCESSORY_HEIGHT - size.height) / 2.0));
|
||||
let x = MARGIN + size.width + GAP;
|
||||
let frame = NSRect::new(NSPoint::new(x, (ACCESSORY_HEIGHT - MENU.height) / 2.0), MENU);
|
||||
let popup = NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), frame, false);
|
||||
// The label beside the menu is not tied to it for VoiceOver, so the menu carries the label's words as its name.
|
||||
popup.setAccessibilityLabel(Some(&NSString::from_str(text.trim_end_matches([':', ':']))));
|
||||
for title in format_menu::titles(filters, entries) {
|
||||
popup.addItemWithTitle(&NSString::from_str(&title));
|
||||
}
|
||||
if let Ok(index) = isize::try_from(selected) {
|
||||
popup.selectItemAtIndex(index);
|
||||
}
|
||||
let view = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, NSSize::new(x + MENU.width + MARGIN, ACCESSORY_HEIGHT)));
|
||||
view.addSubview(&label);
|
||||
view.addSubview(&popup);
|
||||
(view, popup)
|
||||
}
|
||||
|
||||
/// Shows an Open or Folder panel that doesn't block the window and answers through `reply` when
|
||||
/// it closes. AppKit calls the completion handler on the main thread.
|
||||
pub(crate) fn show_panel(d: &FileDialog, reply: Reply) -> Option<Panel> {
|
||||
|
||||
@@ -63,10 +63,13 @@ pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, pare
|
||||
|
||||
fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Option<&W>, reply: Reply) -> Shown {
|
||||
#[cfg(target_os = "macos")]
|
||||
let parent = match d.kind {
|
||||
let (parent, reply) = match d.kind {
|
||||
Kind::Open { .. } | Kind::Folder => return Shown { panel: crate::macos::show_panel(&d, reply) },
|
||||
Kind::Save => match crate::macos::sheet_parent(parent) {
|
||||
Ok(parent) => Some(parent),
|
||||
Ok(parent) => match crate::macos::show_save_sheet(&d, parent, reply) {
|
||||
Ok(()) => return Shown::default(),
|
||||
Err(reply) => (Some(parent), reply),
|
||||
},
|
||||
Err(why) => {
|
||||
reply.send(Answer::Unavailable(why));
|
||||
return Shown::default();
|
||||
|
||||
@@ -276,6 +276,8 @@ pub struct FilePanels {
|
||||
extension_policy: ExtensionPolicy,
|
||||
replace_guard: ReplaceGuard,
|
||||
replace_words: ReplaceWords,
|
||||
/// The label of the macOS Save panel's file type menu; `None` shows [`crate::FORMAT_LABEL`].
|
||||
format_label: Option<String>,
|
||||
/// Why no file dialog can open on this system, when the probe knows.
|
||||
backend_problem: fn() -> Option<String>,
|
||||
/// The replace questions [`pump_with`](FilePanels::pump_with) put on the app's dialog host.
|
||||
@@ -325,6 +327,7 @@ impl FileService {
|
||||
extension_policy: ExtensionPolicy::default(),
|
||||
replace_guard: ReplaceGuard::default(),
|
||||
replace_words: ReplaceWords::default(),
|
||||
format_label: None,
|
||||
backend_problem: probe::known_problem,
|
||||
#[cfg(feature = "ui")]
|
||||
prompts: Vec::new(),
|
||||
@@ -393,6 +396,12 @@ impl FilePanels {
|
||||
self.replace_words = words;
|
||||
}
|
||||
|
||||
/// The label of the file type menu on a macOS Save panel that offers two or more types ("Format:" in English);
|
||||
/// the app sets it again when the language changes.
|
||||
pub fn set_format_label(&mut self, label: impl Into<String>) {
|
||||
self.format_label = Some(label.into());
|
||||
}
|
||||
|
||||
/// [`extension_policy`](FilePanels::extension_policy) on panels the app already keeps, for a
|
||||
/// preference that changes while the app runs.
|
||||
pub fn set_extension_policy(&mut self, policy: ExtensionPolicy) {
|
||||
@@ -647,6 +656,7 @@ impl FilePanels {
|
||||
if request.kind == PickKind::Save {
|
||||
let adds_extension = cfg!(windows) && !request.filters.is_empty();
|
||||
dialog.file_name = request.file_name.as_deref().and_then(|name| dialog_file_name(name, adds_extension));
|
||||
dialog.format_label = self.format_label.clone();
|
||||
}
|
||||
dialog
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use craft_behavior::CanvasView;
|
||||
use egui::Pos2;
|
||||
use kurbo::{Affine, CubicBez, ParamCurveNearest as _, Point};
|
||||
|
||||
use super::model::SelectedAnchors;
|
||||
use super::{BezierHit, BezierOverlay, EditPath, HandleSide, HandlesShown, KnotRef, MAX_ANCHORS, PathSelection};
|
||||
|
||||
/// A shown direction handle: its path's index, its knot, side and screen end.
|
||||
@@ -46,15 +47,34 @@ impl BezierOverlay<'_> {
|
||||
reach: f32,
|
||||
) -> Option<BezierHit> {
|
||||
// pc: crates/vector/src/edit.rs:337 `hit` (handles, anchors, segments; nearest per kind).
|
||||
let shown = shown_handles(paths, selection, handles, view);
|
||||
let shown = shown_handles(paths, selection, &SelectedAnchors::of(selection), handles, view);
|
||||
let anchors = paths.iter().map(EditPath::anchor_count).sum::<usize>() <= MAX_ANCHORS;
|
||||
hit_in(paths, &shown, anchors, view, at, reach)
|
||||
}
|
||||
}
|
||||
|
||||
/// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection
|
||||
/// does not show.
|
||||
pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
|
||||
/// does not show. `anchors` holds the anchors `sel` selects.
|
||||
pub(super) fn shown_handles(
|
||||
paths: &[EditPath],
|
||||
sel: &PathSelection,
|
||||
anchors: &SelectedAnchors,
|
||||
handles: HandlesShown,
|
||||
view: &CanvasView,
|
||||
) -> Vec<Shown> {
|
||||
shown_handles_of(paths, sel, |path, knot| anchors.has_anchor(path, knot), sel.selected_len(), handles, view)
|
||||
}
|
||||
|
||||
/// [`shown_handles`] with `has_anchor` answering whether a knot of a path is a selected anchor, and `selected` as the
|
||||
/// number of selected anchors that `OneAnchor` counts.
|
||||
fn shown_handles_of(
|
||||
paths: &[EditPath],
|
||||
sel: &PathSelection,
|
||||
has_anchor: impl Fn(u64, KnotRef) -> bool,
|
||||
selected: usize,
|
||||
handles: HandlesShown,
|
||||
view: &CanvasView,
|
||||
) -> Vec<Shown> {
|
||||
let mut shown = Vec::new();
|
||||
for (index, path) in paths.iter().enumerate() {
|
||||
let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| {
|
||||
@@ -65,13 +85,13 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
|
||||
let Some(knot) = path.knot(knot_ref) else { continue };
|
||||
for side in [HandleSide::In, HandleSide::Out] {
|
||||
let of_selection = || {
|
||||
sel.has_anchor(path.key, knot_ref)
|
||||
|| next_to_selected_anchor(path, sel, knot_ref, side)
|
||||
has_anchor(path.key, knot_ref)
|
||||
|| next_to_selected_anchor(path, &has_anchor, knot_ref, side)
|
||||
|| segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref))
|
||||
};
|
||||
let wanted = match handles {
|
||||
HandlesShown::All => true,
|
||||
HandlesShown::OneAnchor => sel.selected_len() == 1 && of_selection(),
|
||||
HandlesShown::OneAnchor => selected == 1 && of_selection(),
|
||||
HandlesShown::Selected => of_selection(),
|
||||
};
|
||||
if wanted && !knot.retracted(side) {
|
||||
@@ -85,31 +105,38 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
|
||||
|
||||
/// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not
|
||||
/// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted.
|
||||
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`.
|
||||
pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
|
||||
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per
|
||||
/// path, so it reads the listed anchors and their count from `anchors`, the anchors `sel` selects, and copies none.
|
||||
pub(super) fn other_handles(
|
||||
paths: &[EditPath],
|
||||
at: usize,
|
||||
sel: &PathSelection,
|
||||
anchors: &SelectedAnchors,
|
||||
handles: HandlesShown,
|
||||
view: &CanvasView,
|
||||
) -> Vec<Shown> {
|
||||
let Some(path) = paths.get(at) else { return Vec::new() };
|
||||
let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key));
|
||||
let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() };
|
||||
let mut own = PathSelection::new(Some(path.key), anchors.clone(), None);
|
||||
for (key, rest) in sel.others.iter().filter(|(key, _)| *key != path.key) {
|
||||
own = own.also(*key, rest.clone());
|
||||
if sel.path == Some(path.key) || handles == HandlesShown::All || !anchors.lists(path.key) {
|
||||
return Vec::new();
|
||||
}
|
||||
if let Some(edited) = sel.path.filter(|edited| *edited != path.key) {
|
||||
own = own.also(edited, sel.anchors.clone());
|
||||
}
|
||||
shown_handles(std::slice::from_ref(path), &own, handles, view).into_iter().map(|shown| Shown { path: at, ..shown }).collect()
|
||||
let edited = sel.path.map_or(0, |_| sel.anchors.len());
|
||||
let own = PathSelection::new(Some(path.key), Vec::new(), None);
|
||||
shown_handles_of(std::slice::from_ref(path), &own, |key, knot| anchors.listed_anchor(key, knot), anchors.others_len() + edited, handles, view)
|
||||
.into_iter()
|
||||
.map(|shown| Shown { path: at, ..shown })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out
|
||||
/// handle or the next anchor's in handle, across a closed subpath's seam too.
|
||||
fn next_to_selected_anchor(path: &EditPath, sel: &PathSelection, knot: KnotRef, side: HandleSide) -> bool {
|
||||
fn next_to_selected_anchor(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool {
|
||||
let Some(sub) = path.subpaths.get(knot.subpath) else { return false };
|
||||
let count = sub.knots.len();
|
||||
match side {
|
||||
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, next))),
|
||||
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))),
|
||||
HandleSide::In => {
|
||||
let previous = (knot.knot + count.saturating_sub(1)) % count.max(1);
|
||||
sub.segment_ends(previous).is_some_and(|(previous, _)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
|
||||
sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ use hit_test::{Shown, nearest_on_screen, other_handles, shown_handles};
|
||||
pub(crate) use mark::paint_mark;
|
||||
pub use mark::{AnchorsShown, HitMark, SegmentMark};
|
||||
use mark::{Fill, paint_handle, segment_path, stroke};
|
||||
use model::SelectedAnchors;
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
pub(crate) use model::reads;
|
||||
pub use model::{AnchorDelete, EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit, PathSelection};
|
||||
pub use style::BezierStyle;
|
||||
pub use words::BezierWords;
|
||||
@@ -381,6 +384,8 @@ struct Scene {
|
||||
items: Vec<Item>,
|
||||
/// Over [`MAX_ANCHORS`] or hidden: outlines only.
|
||||
limited: bool,
|
||||
/// The anchors the selection selects (none when `limited`).
|
||||
selected: SelectedAnchors,
|
||||
}
|
||||
|
||||
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
|
||||
@@ -470,10 +475,12 @@ impl<'a> BezierOverlay<'a> {
|
||||
let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::<usize>() > MAX_ANCHORS;
|
||||
let mut items = Vec::new();
|
||||
if limited {
|
||||
return Scene { items, limited };
|
||||
return Scene { items, limited, selected: SelectedAnchors::default() };
|
||||
}
|
||||
let selected = SelectedAnchors::of(self.selection);
|
||||
let near = rect.expand(reach);
|
||||
let shown = if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, self.handles, view) };
|
||||
let shown =
|
||||
if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, &selected, self.handles, view) };
|
||||
let mut handles = shown.iter().peekable();
|
||||
for (at, path) in paths.iter().enumerate() {
|
||||
let count = path.anchor_count();
|
||||
@@ -551,7 +558,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Scene { items, limited }
|
||||
Scene { items, limited, selected }
|
||||
}
|
||||
|
||||
/// Whether the press on `item` is the tool's.
|
||||
@@ -1308,7 +1315,7 @@ impl Component for BezierOverlay<'_> {
|
||||
for item in &scene.items {
|
||||
let press = self.takes(item);
|
||||
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
|
||||
let selected = item.kind == Kind::Anchor && self.selection.has_anchor(item.key, item.knot);
|
||||
let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot);
|
||||
let part = cx.part(item.part(), item.shape.clone()).priority(item.priority());
|
||||
let part = if press { part.sense(PRESS) } else { part };
|
||||
let part = if keyboard {
|
||||
@@ -1416,7 +1423,7 @@ impl Component for BezierOverlay<'_> {
|
||||
draw_end(path, item.knot, item.at, fill);
|
||||
}
|
||||
Kind::Anchor if item.shown => {
|
||||
let fill = if self.selection.draws_selected(path.key, item.knot) {
|
||||
let fill = if scene.selected.draws_selected(path.key, item.knot) {
|
||||
Fill::Path(style.line)
|
||||
} else {
|
||||
Fill::Style(if cx.part_if_declared(item.part()).is_some() {
|
||||
@@ -1433,7 +1440,7 @@ impl Component for BezierOverlay<'_> {
|
||||
// The handles of anchors selected in paths the overlay does not edit: drawn, never parts.
|
||||
if !circles {
|
||||
for (at, path) in paths.iter().enumerate() {
|
||||
for shown in other_handles(paths, at, self.selection, self.handles, &view) {
|
||||
for shown in other_handles(paths, at, self.selection, &scene.selected, self.handles, &view) {
|
||||
draw_end(path, shown.knot, shown.at, Fill::Style(cx.resolve(handle_fill)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! the overlays report. The host converts its own path type to these each frame and applies the
|
||||
//! edits to its own.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use kurbo::{BezPath, CubicBez, Point, Vec2};
|
||||
|
||||
@@ -235,6 +237,8 @@ impl PathSelection {
|
||||
|
||||
/// Whether `knot` of `path` draws selected: a selected anchor of the path being edited, or one listed in `others`.
|
||||
pub fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
reads::add(self.others.iter().map(|(key, anchors)| if *key == path { 1 + anchors.len() } else { 1 }).sum());
|
||||
self.has_anchor(path, knot) || self.others.iter().any(|(key, anchors)| *key == path && anchors.contains(&knot))
|
||||
}
|
||||
|
||||
@@ -245,6 +249,8 @@ impl PathSelection {
|
||||
|
||||
/// Whether `knot` of `path` is a selected anchor.
|
||||
pub fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
reads::add(if self.path == Some(path) { self.anchors.len() } else { 0 });
|
||||
self.path == Some(path) && self.anchors.contains(&knot)
|
||||
}
|
||||
|
||||
@@ -268,6 +274,79 @@ impl PathSelection {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors a [`PathSelection`] selects, gathered into sets once so that the overlay asks about each knot it lays
|
||||
/// out or draws without searching the selection's lists. A path that `others` lists more than once is treated as one
|
||||
/// path holding every anchor listed for it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct SelectedAnchors {
|
||||
path: Option<u64>,
|
||||
anchors: HashSet<KnotRef>,
|
||||
others: HashSet<(u64, KnotRef)>,
|
||||
listed: HashSet<u64>,
|
||||
others_len: usize,
|
||||
}
|
||||
|
||||
impl SelectedAnchors {
|
||||
/// The anchors `sel` selects.
|
||||
pub(super) fn of(sel: &PathSelection) -> Self {
|
||||
let others_len = sel.others.iter().map(|(_, anchors)| anchors.len()).sum();
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
reads::add(sel.anchors.len() + others_len);
|
||||
Self {
|
||||
path: sel.path,
|
||||
anchors: sel.anchors.iter().copied().collect(),
|
||||
others: sel.others.iter().flat_map(|(key, anchors)| anchors.iter().map(|knot| (*key, *knot))).collect(),
|
||||
listed: sel.others.iter().map(|(key, _)| *key).collect(),
|
||||
others_len,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `knot` of `path` is a selected anchor of the path being edited ([`PathSelection::has_anchor`]).
|
||||
pub(super) fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
|
||||
self.path == Some(path) && self.anchors.contains(&knot)
|
||||
}
|
||||
|
||||
/// Whether `knot` of `path` draws selected ([`PathSelection::draws_selected`]).
|
||||
pub(super) fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
|
||||
self.has_anchor(path, knot) || self.others.contains(&(path, knot))
|
||||
}
|
||||
|
||||
/// Whether `knot` is one of the anchors `others` lists for `path`.
|
||||
pub(super) fn listed_anchor(&self, path: u64, knot: KnotRef) -> bool {
|
||||
self.others.contains(&(path, knot))
|
||||
}
|
||||
|
||||
/// Whether `others` lists `path`, with or without anchors.
|
||||
pub(super) fn lists(&self, path: u64) -> bool {
|
||||
self.listed.contains(&path)
|
||||
}
|
||||
|
||||
/// The number of anchors `others` lists over every path.
|
||||
pub(super) fn others_len(&self) -> usize {
|
||||
self.others_len
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work.
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
pub(crate) mod reads {
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static READS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Counts `n` entries read.
|
||||
pub(crate) fn add(n: usize) {
|
||||
READS.with(|reads| reads.set(reads.get() + n));
|
||||
}
|
||||
|
||||
/// The entries read since the last call, and starts the count again.
|
||||
pub(crate) fn take() -> usize {
|
||||
READS.with(|reads| reads.replace(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of a knot's two direction handles.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -6,7 +6,7 @@ use craft_behavior::Value;
|
||||
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
@@ -549,31 +549,34 @@ impl DivideSlicesDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// One axis: its check box, then (while it is on) what the value counts and the value.
|
||||
/// One axis: its check box, then (while it is on) what the value counts and the value. Both axes show the same Divide
|
||||
/// By and value labels, so those rows describe their controls, and each control is named by its label and the axis's
|
||||
/// caption.
|
||||
fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &Label, words: &SliceWords, lengths: LengthUnits) {
|
||||
Field::new(caption.clone()).show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut axis.on)).label(caption.clone()).show(ui);
|
||||
});
|
||||
let in_axis = |control: &Label| Label::from(words.axis_control.fill(&[("control", control.as_str()), ("axis", caption.as_str())]));
|
||||
let unit = if axis.by_size { words.size.clone() } else { words.count.clone() };
|
||||
Field::new(words.divide_by.clone()).enabled(axis.on).show(ui, |ui, _| {
|
||||
RadioGroup::new(words.divide_by.clone(), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
|
||||
let describes = || SideLabel::new().role(FieldLabelRole::Describes);
|
||||
Field::new(words.divide_by.clone()).side(describes()).enabled(axis.on).show(ui, |ui, _| {
|
||||
RadioGroup::new(in_axis(&words.divide_by), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Radio::new(false).label(words.count.clone()).show(ui);
|
||||
Radio::new(true).label(words.size.clone()).show(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
Field::new(unit).enabled(axis.on).show(ui, |ui, _| {
|
||||
let value_name = in_axis(&unit);
|
||||
Field::new(unit).side(describes()).enabled(axis.on).show(ui, |ui, _| {
|
||||
if axis.by_size {
|
||||
let field =
|
||||
NumberField::length(words.divide_value.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
|
||||
let field = NumberField::length(value_name.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
|
||||
if let Some(Some(size)) = field.value().copied() {
|
||||
axis.size = AxisState::size_of(size, axis.size);
|
||||
}
|
||||
} else {
|
||||
let max = f64::from(AxisState::MAX_COUNT);
|
||||
let field =
|
||||
NumberField::new(words.divide_value.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
|
||||
let field = NumberField::new(value_name.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
|
||||
if let Some(Some(count)) = field.value().copied() {
|
||||
axis.count = count.round().clamp(1.0, max) as u32;
|
||||
}
|
||||
|
||||
@@ -72,5 +72,8 @@ craft_ui::words! {
|
||||
count: "slice.count" = "slices, evenly spaced";
|
||||
size: "slice.size" = "per slice";
|
||||
divide_value: "slice.divideValue" = "Value";
|
||||
/// The name a screen reader reads for one axis's Divide By group and value field: `{control}` the row's
|
||||
/// visible label, `{axis}` the axis's caption.
|
||||
axis_control: template "slice.axisControl" = "{control}, {axis}";
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ impl Outcome for StrokeEditorOutput {
|
||||
/// with a line sample drawn at opacity 1; the row matching [`StrokeStyle::line_style`] is selected, none for Custom.
|
||||
/// Picking one applies [`StrokeStyle::with_line_style`].
|
||||
/// - Rows: Alignment (Inside, Center, Outside; enabled only when [`closed`](Self::closed)); Caps (Butt / Flat, Round,
|
||||
/// Square; disabled for a solid closed path); Corners (Miter, Round, Bevel; enabled only with
|
||||
/// Square; disabled for a solid closed path unless [`caps_on_closed`](Self::caps_on_closed)); Corners (Miter, Round, Bevel; enabled only with
|
||||
/// [`corners`](Self::corners)); the app's [`rows`](Self::rows); Miter limit (1–500, `×`; enabled only for Miter
|
||||
/// corners); Opacity ([`StrokeSections::OPACITY`], 0–100 %, stored 0..=1). Choices are selects, or segmented icon
|
||||
/// buttons with [`StrokeSections::ICONS`]. Under the rows of an open path: "Open paths use centered strokes".
|
||||
@@ -96,6 +96,7 @@ pub struct StrokeEditor<'a> {
|
||||
value: Bind<'a, StrokeStyle>,
|
||||
sections: StrokeSections,
|
||||
closed: bool,
|
||||
caps_on_closed: bool,
|
||||
corners: bool,
|
||||
mixed: StrokeMixed,
|
||||
rows: &'a [StrokeChoiceRow<'a>],
|
||||
@@ -109,6 +110,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
value,
|
||||
sections: StrokeSections::default(),
|
||||
closed: true,
|
||||
caps_on_closed: false,
|
||||
corners: true,
|
||||
mixed: StrokeMixed::default(),
|
||||
rows: &[],
|
||||
@@ -121,13 +123,20 @@ impl<'a> StrokeEditor<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the stroked path is closed: alignment applies and caps need dashes.
|
||||
/// True by default.
|
||||
/// Whether the stroked path is closed: alignment applies and caps need dashes, unless
|
||||
/// [`caps_on_closed`](Self::caps_on_closed) is set. True by default.
|
||||
pub fn closed(mut self, closed: bool) -> Self {
|
||||
self.closed = closed;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the Caps row stays enabled on a closed path without dashes. False by default: the row is then disabled
|
||||
/// for a solid closed path and enabled for an open or dashed one.
|
||||
pub fn caps_on_closed(mut self, enabled: bool) -> Self {
|
||||
self.caps_on_closed = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the path has corners for the Corners and Miter limit rows (an ellipse has none). True by default.
|
||||
pub fn corners(mut self, corners: bool) -> Self {
|
||||
self.corners = corners;
|
||||
@@ -148,7 +157,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
|
||||
/// Shows the editor.
|
||||
pub fn show(self, ui: &mut Ui) -> StrokeEditorOutput {
|
||||
let StrokeEditor { label, mut value, sections, closed, corners, mixed, rows } = self;
|
||||
let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<StrokeWords>();
|
||||
let name: Arc<str> = label.as_str().into();
|
||||
@@ -164,7 +173,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
Some((base, draft)) if base == held => draft,
|
||||
_ => held.clone(),
|
||||
};
|
||||
let body = Body { words: &words, style: &style, sections, closed, corners, mixed, rows, name: name.clone() };
|
||||
let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, name: name.clone() };
|
||||
body.show(ui, &mut found);
|
||||
if !found.events.is_empty() {
|
||||
for event in &found.events {
|
||||
@@ -251,6 +260,7 @@ struct Body<'a> {
|
||||
style: &'a StrokeStyle,
|
||||
sections: StrokeSections,
|
||||
closed: bool,
|
||||
caps_on_closed: bool,
|
||||
corners: bool,
|
||||
mixed: StrokeMixed,
|
||||
rows: &'a [StrokeChoiceRow<'a>],
|
||||
@@ -325,7 +335,7 @@ impl Body<'_> {
|
||||
|
||||
fn grid(&self, ui: &mut Ui, found: &mut Found) {
|
||||
let (style, mixed, words) = (self.style, self.mixed, self.words);
|
||||
let solid_closed = self.closed && style.dashes.is_empty() && !mixed.dashes;
|
||||
let solid_closed = self.closed && !self.caps_on_closed && style.dashes.is_empty() && !mixed.dashes;
|
||||
let icons = self.sections.contains(StrokeSections::ICONS);
|
||||
FieldGroup::new(words.title.clone()).show(ui, |ui, _| {
|
||||
let align = [
|
||||
|
||||
@@ -465,6 +465,54 @@ fn one_anchor_shows_handles_only_while_one_anchor_is_selected_over_all_paths() {
|
||||
assert!(!matches!(none, Some(BezierHit::Handle { .. })), "{none:?}");
|
||||
}
|
||||
|
||||
// Under `OneAnchor` the handles of an anchor listed in `others` draw while it is the only selected anchor over all
|
||||
// paths, as `Selected` draws them; with an anchor of a third path listed too, neither path's handles draw.
|
||||
#[trial]
|
||||
fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths() {
|
||||
let painted_with = |selection: PathSelection, handles: HandlesShown| {
|
||||
let mut other = path_b();
|
||||
other.subpaths[0].knots[0] = Knot::smooth(p(60.0, 200.0), p(90.0, 170.0));
|
||||
let third =
|
||||
EditPath::new(3, vec![EditSubpath::new(vec![Knot::smooth(p(300.0, 220.0), p(330.0, 190.0)), Knot::corner(p(360.0, 260.0))], false)]);
|
||||
let mut h = harness(vec![path_a(), other, third]);
|
||||
h.update(|st| (st.selection, st.handles) = (selection, handles));
|
||||
format!("{:?}", h.fixture.frame_shapes())
|
||||
};
|
||||
let one = || sel(1, &[]).also(2, vec![kr(0)]);
|
||||
assert_eq!(painted_with(one(), HandlesShown::OneAnchor), painted_with(one(), HandlesShown::Selected));
|
||||
let two = || sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]);
|
||||
assert_ne!(painted_with(two(), HandlesShown::OneAnchor), painted_with(two(), HandlesShown::Selected));
|
||||
assert_eq!(
|
||||
painted_with(two(), HandlesShown::OneAnchor),
|
||||
painted_with(sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]), HandlesShown::OneAnchor),
|
||||
"painting is the same from frame to frame"
|
||||
);
|
||||
}
|
||||
|
||||
// A frame reads the selection's anchor lists a number of times that grows with the selection, not with its square:
|
||||
// doubling the selected anchors of the edited path and the number of other paths listed at most doubles the entries
|
||||
// read (a search of the lists for each anchor laid out or drawn quadruples them).
|
||||
#[trial]
|
||||
fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
|
||||
let reads_for = |n: usize| {
|
||||
let knot = |i: usize| Knot::smooth(p(20.0 + (i % 40) as f64 * 12.0, 20.0 + (i / 40) as f64 * 12.0), p(26.0 + (i % 40) as f64 * 12.0, 20.0));
|
||||
let edited = EditPath::new(1, vec![EditSubpath::new((0..n).map(knot).collect(), false)]);
|
||||
let others: Vec<EditPath> =
|
||||
(0..n).map(|i| EditPath::new(2 + i as u64, vec![EditSubpath::new((0..4).map(|k| knot(i * 4 + k)).collect(), true)])).collect();
|
||||
let mut selection = PathSelection::new(Some(1), (0..n).map(kr).collect(), None);
|
||||
for other in &others {
|
||||
selection = selection.also(other.key, (0..4).map(kr).collect());
|
||||
}
|
||||
let mut h = harness(std::iter::once(edited).chain(others).collect());
|
||||
craft_draw::ui::pen::bezier::reads::take();
|
||||
h.update(|st| st.selection = selection);
|
||||
craft_draw::ui::pen::bezier::reads::take()
|
||||
};
|
||||
let (small, large) = (reads_for(60), reads_for(120));
|
||||
assert!(small > 0, "the frame reads the selection");
|
||||
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
|
||||
}
|
||||
|
||||
// Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at.
|
||||
|
||||
// `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.
|
||||
|
||||
@@ -4,11 +4,15 @@
|
||||
use craft_behavior::geometry::Constraint;
|
||||
use craft_behavior::kurbo::{Point, Rect};
|
||||
use craft_behavior::{CanvasView, EditEvent};
|
||||
use craft_draw::ui::slice::{SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool, SliceToolSettings};
|
||||
use craft_ui::contract::{CommandSet, Show as _};
|
||||
use craft_draw::ui::slice::{
|
||||
DivideBy, DivideSlices, DivideSlicesDialog, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool,
|
||||
SliceToolSettings,
|
||||
};
|
||||
use craft_ui::contract::{CommandSet, Role, Show as _};
|
||||
use craft_ui::dialog::DialogHost;
|
||||
use craft_ui::runtime::commands::CommandRef;
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::testing::{ToolFixture, trial};
|
||||
use craft_ui::testing::{Fixture, ToolFixture, access, trial};
|
||||
use egui::{Key, Modifiers, Pos2, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -203,3 +207,37 @@ fn delete_takes_the_key_for_the_selected_slice() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a screen reader reads for the nodes of `role` in the shown Divide Slice dialog, in tree order.
|
||||
fn divide_names(divide: DivideSlices, role: Role) -> Vec<String> {
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(Vec2::new(900.0, 700.0));
|
||||
host.borrow_mut().open(DivideSlicesDialog::new(divide));
|
||||
fixture.idle(10);
|
||||
let tree = fixture.tree();
|
||||
fixture.by_role(role).iter().map(|target| access::name(tree, target.node).unwrap_or_default().to_owned()).collect()
|
||||
}
|
||||
|
||||
/// Divide Slice's two axes show the same Divide By choice and value rows; each axis's radio group and value field
|
||||
/// name their axis by its caption after their visible label, so a screen reader tells the rows from the columns.
|
||||
#[trial]
|
||||
fn divide_slice_names_each_axis_control_by_its_axis() {
|
||||
let by_count = DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(3)));
|
||||
let by_size = DivideSlices::new(Some(DivideBy::Size(72.0)), Some(DivideBy::Size(36.0)));
|
||||
let cases = [
|
||||
("the Divide By groups", by_count, Role::RADIO_GROUP, "Divide By"),
|
||||
("the count fields", by_count, Role::SPIN_BUTTON, "slices, evenly spaced"),
|
||||
("the size fields", by_size, Role::SPIN_BUTTON, "per slice"),
|
||||
];
|
||||
for (what, divide, role, label) in cases {
|
||||
let names = divide_names(divide, role);
|
||||
let [rows, columns] = names.as_slice() else { panic!("{what}: one for each axis, got {names:?}") };
|
||||
assert_ne!(rows, columns, "{what} have different names");
|
||||
for (name, axis) in [(rows, "Divide Horizontally Into"), (columns, "Divide Vertically Into")] {
|
||||
assert!(name.starts_with(label), "{what}: {name:?} starts with the visible label {label:?}");
|
||||
assert!(name.contains(axis), "{what}: {name:?} names its axis {axis:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The stroke editor's dash fields: typing in the blank after the pattern adds an entry, clearing a later field ends
|
||||
//! the pattern there, and the first field never clears.
|
||||
//! the pattern there, and the first field never clears. Its Caps row on a solid closed path: disabled by default,
|
||||
//! enabled with `caps_on_closed`.
|
||||
|
||||
use craft_draw::ui::stroke::{StrokeEditor, StrokeSections, StrokeStyle};
|
||||
use craft_draw::ui::stroke::{LineCap, StrokeEditor, StrokeSections, StrokeStyle};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
@@ -34,6 +35,39 @@ fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
|
||||
fixture.idle(3);
|
||||
}
|
||||
|
||||
/// The panel editor over a solid closed path, with `caps_on_closed` as given, and the style it writes through to.
|
||||
fn closed_editor(caps_on_closed: bool) -> (Fixture, Rc<RefCell<StrokeStyle>>) {
|
||||
let style = Rc::new(RefCell::new(StrokeStyle::default()));
|
||||
let shown = Rc::clone(&style);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut style = shown.borrow_mut();
|
||||
let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style))
|
||||
.sections(StrokeSections::PANEL)
|
||||
.closed(true)
|
||||
.caps_on_closed(caps_on_closed)
|
||||
.show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, style)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn caps_on_closed_keeps_the_cap_buttons_enabled_on_a_solid_closed_path() {
|
||||
let (mut fixture, style) = closed_editor(false);
|
||||
let square = fixture.by_label("Square").expect("the editor shows Square");
|
||||
assert!(fixture.tree().is_disabled_key(square.node), "by default Caps is disabled for a solid closed path");
|
||||
fixture.click(&square);
|
||||
fixture.idle(3);
|
||||
assert_ne!(style.borrow().cap, LineCap::Square, "a disabled cap button does not change the cap");
|
||||
|
||||
let (mut fixture, style) = closed_editor(true);
|
||||
let square = fixture.by_label("Square").expect("the editor shows Square");
|
||||
assert!(!fixture.tree().is_disabled_key(square.node), "with caps_on_closed Caps is enabled");
|
||||
fixture.click(&square);
|
||||
fixture.idle(3);
|
||||
assert_eq!(style.borrow().cap, LineCap::Square, "the cap button sets the cap");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() {
|
||||
let (mut fixture, style) = editor(vec![4.0, 2.0]);
|
||||
|
||||
@@ -734,6 +734,7 @@ pub struct FontPicker<'a> {
|
||||
host_picked: Option<String>,
|
||||
/// Whether the font picker uses compact bar sizing (`size.length.field.sm` / `size.length.short`).
|
||||
#[style_key]
|
||||
#[prop]
|
||||
compact: bool,
|
||||
}
|
||||
|
||||
@@ -787,13 +788,6 @@ impl<'a> FontPicker<'a> {
|
||||
.enabled(catalog.is_ready())
|
||||
}
|
||||
|
||||
/// Sets whether the font picker uses compact bar sizing (`size.length.field.sm` / `size.length.short`).
|
||||
#[must_use]
|
||||
pub fn compact(mut self, compact: bool) -> Self {
|
||||
self.compact = compact;
|
||||
self
|
||||
}
|
||||
|
||||
/// 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, arrow: DropdownArrow) -> Vec<Adornment> {
|
||||
|
||||
@@ -868,15 +868,23 @@ fn copy_in(folder: &OsFontFolder, p: &Planned, found: Option<&str>) -> Result<()
|
||||
}
|
||||
let part = aside(&p.path, "part");
|
||||
let _ = std::fs::remove_file(&part);
|
||||
std::fs::copy(&p.source, &part).map_err(io(what()))?;
|
||||
folder.unload(&p.path);
|
||||
let checked = File::open(&part).and_then(|f| f.sync_all()).map_err(io(what())).and_then(|()| {
|
||||
if file_sha256(&part).as_ref() == Some(&p.sha256) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Verify { file: p.store_file.clone(), error: VerifyError::Sha256 })
|
||||
}
|
||||
// One writable handle writes and flushes the copy: Windows flushes only through a handle that can write, and the
|
||||
// copy doesn't take the source's permissions (`std::fs::copy` would), so a read-only store file still copies.
|
||||
let copied = File::open(&p.source).and_then(|mut source| {
|
||||
let mut copy = File::create(&part)?;
|
||||
std::io::copy(&mut source, &mut copy)?;
|
||||
copy.sync_all()
|
||||
});
|
||||
if let Err(e) = copied {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(io(what())(e));
|
||||
}
|
||||
folder.unload(&p.path);
|
||||
let checked = if file_sha256(&part).as_ref() == Some(&p.sha256) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Verify { file: p.store_file.clone(), error: VerifyError::Sha256 })
|
||||
};
|
||||
if let Err(e) = checked.and_then(|()| publish(&part, p, found)) {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(e);
|
||||
|
||||
@@ -904,6 +904,28 @@ mod store {
|
||||
assert_eq!(files[0]["postscript"], json!(["TestSans-Bold"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_store_files_are_made_available() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-read-only");
|
||||
let set_read_only = |read_only: bool| {
|
||||
for name in entries(&dir.join("testsans")) {
|
||||
let path = dir.join("testsans").join(name);
|
||||
let mut permissions = std::fs::metadata(&path).unwrap().permissions();
|
||||
permissions.set_readonly(read_only);
|
||||
std::fs::set_permissions(&path, permissions).unwrap();
|
||||
}
|
||||
};
|
||||
set_read_only(true);
|
||||
let copies = store.make_available(GOOGLE_FONTS, "Test Sans");
|
||||
set_read_only(false);
|
||||
assert_eq!(copies.unwrap().len(), 3, "a read-only store file still copies");
|
||||
assert!(entries(&shared.join("testsans")).iter().all(|name| !name.starts_with('.')), "no copy is left aside");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_made_available_to_all_apps_is_withdrawn_exactly() {
|
||||
let server = Server::start();
|
||||
@@ -1005,6 +1027,7 @@ mod store {
|
||||
}
|
||||
|
||||
/// A catalog of the same system as [`shared_store`]'s, to look at what a scan sees.
|
||||
#[cfg(unix)]
|
||||
fn catalog_of(dir: &Path, root: &Path) -> Catalog {
|
||||
let env = FontEnv {
|
||||
os: Os::Unix,
|
||||
@@ -1187,9 +1210,12 @@ mod store {
|
||||
assert!(with(&[], &flatpak).is_err(), "read only");
|
||||
info("~/.local/share/fonts;");
|
||||
assert!(with(&[], &flatpak).is_ok());
|
||||
assert!(with(&[("HOST_XDG_DATA_HOME", "/elsewhere")], &flatpak).is_err(), "the grant is for another folder");
|
||||
// Absolute on every platform: `/elsewhere` isn't on Windows.
|
||||
let elsewhere = root.join("elsewhere");
|
||||
let host = [("HOST_XDG_DATA_HOME", elsewhere.to_str().unwrap())];
|
||||
assert!(with(&host, &flatpak).is_err(), "the grant is for another folder");
|
||||
info("xdg-data/fonts;");
|
||||
assert_eq!(with(&[("HOST_XDG_DATA_HOME", "/elsewhere")], &flatpak), Ok(PathBuf::from("/elsewhere/fonts/Craft")));
|
||||
assert_eq!(with(&host, &flatpak), Ok(elsewhere.join("fonts/Craft")));
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
@@ -95,13 +95,17 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names (
|
||||
- `embedded_elsewhere(&["Noto Sans Math", …])` names families another table of the app embeds,
|
||||
so `check_text` and the catalog check count their characters as covered.
|
||||
- `dir(path)` and `required(bool)` override the two environment variables.
|
||||
- `tab_face()` also embeds Noto Sans Condensed SemiBold from `fonts/latin-manifest.txt`, with the
|
||||
role `tab`. `scripts` and `filter` do not apply to it. A checkout without that manifest or its
|
||||
row embeds the other faces and prints a warning, even with `CRAFT_FONTS_REQUIRED=1`.
|
||||
|
||||
`write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face
|
||||
is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts,
|
||||
index, bytes, role }` literals; any struct with those fields and that name in scope works too.
|
||||
`role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")`, `Some("signature")` or
|
||||
`None`; craft-ui's font stack leads the Monospace family with the `mono` face and the signature
|
||||
family (`FontRef::signature()`) with the `signature` face. `EmbeddedFace` itself has `name()`,
|
||||
`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace
|
||||
family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature`
|
||||
face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`,
|
||||
`has_script(tag)`, `is_cjk()` and `weight()`.
|
||||
|
||||
## Document fonts
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::io;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::cmap::Cmap;
|
||||
use crate::manifest::{ManifestEntry, ParseError, parse_manifest, script_matches};
|
||||
use crate::manifest::{ManifestEntry, ParseError, TAB_FACE, TAB_ROLE, parse_manifest, script_matches};
|
||||
|
||||
const DIR_VAR: &str = "CRAFT_FONTS_DIR";
|
||||
const REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED";
|
||||
@@ -55,6 +55,35 @@ fn rerun_if_changed(cargo: &mut Vec<String>, path: &Path) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `entry` of `manifest` as a face to embed, once its font file resolves to a file inside the checkout `root` and its
|
||||
/// licence file, if it exists, does too.
|
||||
fn checked_face(manifest: &Path, dir: &Path, root: &Path, entry: ManifestEntry, cut: bool, cargo: &mut Vec<String>) -> Result<Face, Error> {
|
||||
let manifest = manifest.to_path_buf();
|
||||
// A manifest path names a file in the checkout, and is served under the same name.
|
||||
for file in [&entry.file, &entry.licence_file] {
|
||||
if !file.is_empty() && !is_checkout_relative(file) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
|
||||
}
|
||||
}
|
||||
let file = dir.join(&entry.file);
|
||||
// `include_bytes!` resolves relative paths from the including source file.
|
||||
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
|
||||
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
|
||||
// missing licence is only warned about when serving; one that exists must be inside.
|
||||
if !path.starts_with(root) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(root)) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
rerun_if_changed(cargo, &path)?;
|
||||
let (index, sha256) = (entry.index, entry.sha256.clone());
|
||||
Ok(Face { entry, path, index, cut, sha256 })
|
||||
}
|
||||
|
||||
/// Whether the build script is building for wasm32 (web builds usually embed fewer faces).
|
||||
pub fn target_is_wasm() -> bool {
|
||||
std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32")
|
||||
@@ -75,6 +104,7 @@ pub struct Embed {
|
||||
families: Option<Vec<String>>,
|
||||
elsewhere: Vec<String>,
|
||||
serve: Option<Serve>,
|
||||
tab: bool,
|
||||
}
|
||||
|
||||
/// Where [`Embed::serve`] copies the faces, and the URL prefix they are served under.
|
||||
@@ -174,6 +204,18 @@ impl Embed {
|
||||
self
|
||||
}
|
||||
|
||||
/// Also embed the tab-title face, Noto Sans Condensed SemiBold ([`TAB_FACE`]), from the checkout's
|
||||
/// `fonts/latin-manifest.txt`, with the `tab` role ([`TAB_ROLE`]); craft-ui's font stack leads its tab-title family
|
||||
/// with it. [`Embed::scripts`] and [`Embed::filter`] do not apply to it. A checkout without that manifest, or a
|
||||
/// manifest without the face's row, embeds the other faces and prints a `cargo::warning`, required or not. A
|
||||
/// manifest that does not parse, or a row whose file is missing or outside the checkout, is an [`Error`] when
|
||||
/// required and a `cargo::warning` otherwise; the other faces are embedded either way when not required. A
|
||||
/// [`Embed::serve`] table carries no roles, so it leaves the face out and prints a `cargo::warning`.
|
||||
pub fn tab_face(mut self) -> Self {
|
||||
self.tab = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Read this checkout instead of `CRAFT_FONTS_DIR`.
|
||||
pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
|
||||
self.dir = Some(dir.into());
|
||||
@@ -239,7 +281,7 @@ impl Embed {
|
||||
|
||||
let selected = match &dir {
|
||||
None => Err(Error::NotSet),
|
||||
Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
|
||||
Some(dir) => self.select(dir, required, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
|
||||
};
|
||||
let mut selected = selected;
|
||||
if let Ok(faces) = &mut selected {
|
||||
@@ -278,8 +320,39 @@ impl Embed {
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
/// The tab-title face of `fonts/latin-manifest.txt` ([`TAB_FACE`]), with the [`TAB_ROLE`] role. A checkout without
|
||||
/// that manifest, or a manifest without the face's row, gives `None` and a `cargo::warning`.
|
||||
fn select_tab_face(&self, dir: &Path, root: &Path, cargo: &mut Vec<String>) -> Result<Option<Face>, Error> {
|
||||
let manifest = dir.join("fonts/latin-manifest.txt");
|
||||
let text = match read_text_bounded(&manifest, MAX_MANIFEST_BYTES) {
|
||||
Ok(text) => text,
|
||||
Err(source) if source.kind() == io::ErrorKind::NotFound => {
|
||||
// Cargo treats a missing watched file as changed, so the build watches the folder the manifest would be in.
|
||||
rerun_if_changed(cargo, &dir.join("fonts"))?;
|
||||
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} does not exist", manifest.display()));
|
||||
return Ok(None);
|
||||
}
|
||||
Err(source) => return Err(Error::Read { path: manifest, source }),
|
||||
};
|
||||
rerun_if_changed(cargo, &manifest)?;
|
||||
let entries = parse_manifest(&text).map_err(|error| Error::Parse { manifest: manifest.clone(), error })?;
|
||||
let (family, style) = TAB_FACE;
|
||||
let Some(mut entry) = entries.into_iter().find(|entry| entry.family == family && entry.style == style) else {
|
||||
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} has no {family} {style} row", manifest.display()));
|
||||
return Ok(None);
|
||||
};
|
||||
entry.role = Some(TAB_ROLE.to_owned());
|
||||
let file = dir.join(&entry.file);
|
||||
if !file.exists() {
|
||||
// Cargo treats a missing watched file as changed, so the build watches the nearest folder that exists.
|
||||
let folder = file.ancestors().skip(1).find(|folder| folder.is_dir()).unwrap_or(dir);
|
||||
rerun_if_changed(cargo, folder)?;
|
||||
}
|
||||
checked_face(&manifest, dir, root, entry, false, cargo).map(Some)
|
||||
}
|
||||
|
||||
/// The wanted manifest entries with their canonical file paths.
|
||||
fn select(&self, dir: &Path, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
|
||||
fn select(&self, dir: &Path, required: bool, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
let text = read_text_bounded(&manifest, MAX_MANIFEST_BYTES).map_err(|source| Error::Read { path: manifest.clone(), source })?;
|
||||
// Cargo treats a missing watched file as changed, which would rerun the build every time.
|
||||
@@ -325,29 +398,17 @@ impl Embed {
|
||||
uncut.push(format!("{} {}", entry.family, entry.style));
|
||||
continue;
|
||||
}
|
||||
// A manifest path names a file in the checkout, and is served under the same name.
|
||||
for file in [&entry.file, &entry.licence_file] {
|
||||
if !file.is_empty() && !is_checkout_relative(file) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
|
||||
}
|
||||
faces.push(checked_face(&manifest, dir, &root, entry, cut, cargo)?);
|
||||
}
|
||||
if self.tab && self.serve.is_some() {
|
||||
cargo.push("cargo::warning=craft-fonts: not serving the tab-title face: a served table carries no roles".to_owned());
|
||||
} else if self.tab {
|
||||
match self.select_tab_face(dir, &root, cargo) {
|
||||
Ok(Some(face)) => faces.push(face),
|
||||
Ok(None) => {}
|
||||
Err(e) if required => return Err(e),
|
||||
Err(e) => cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {e}")),
|
||||
}
|
||||
let file = dir.join(&entry.file);
|
||||
// `include_bytes!` resolves relative paths from the including source file.
|
||||
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
|
||||
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
|
||||
// missing licence is only warned about when serving; one that exists must be inside.
|
||||
if !path.starts_with(&root) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(&root)) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
rerun_if_changed(cargo, &path)?;
|
||||
let (index, sha256) = (entry.index, entry.sha256.clone());
|
||||
faces.push(Face { entry, path, index, cut, sha256 });
|
||||
}
|
||||
if !uncut.is_empty() {
|
||||
let why = if self.catalogs.is_some() { "Embed::subset_to was given no translation catalogs" } else { "no translation catalogs" };
|
||||
@@ -451,7 +512,8 @@ impl Embed {
|
||||
}
|
||||
|
||||
/// Warn about each catalog's and [`Embed::check_text`] file's characters that neither an
|
||||
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers.
|
||||
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers. The tab-title face, which draws only tab titles,
|
||||
/// covers none of them.
|
||||
fn check_coverage(&self, faces: &[Face], dir: &Path, cargo: &mut Vec<String>) {
|
||||
let files = self.checked_files();
|
||||
if files.is_empty() {
|
||||
@@ -460,6 +522,7 @@ impl Embed {
|
||||
let elsewhere = self.elsewhere(dir, cargo);
|
||||
let fonts: Vec<(&ManifestEntry, u32, Option<Vec<u8>>)> = faces
|
||||
.iter()
|
||||
.filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE))
|
||||
.map(|face| (&face.entry, face.index, read_bounded(&face.path, MAX_FILE_BYTES).ok()))
|
||||
.chain(elsewhere.iter().map(|entry| (entry, entry.index, read_bounded(&dir.join(&entry.file), MAX_FILE_BYTES).ok())))
|
||||
.collect();
|
||||
@@ -496,16 +559,19 @@ impl Embed {
|
||||
}
|
||||
}
|
||||
|
||||
/// `faces` when `fonts/manifest.txt` gave at least one, covering every script of [`Embed::scripts`]; the tab-title
|
||||
/// face, which neither selection applies to, counts for neither.
|
||||
fn check_required(&self, dir: &Path, faces: Vec<Face>) -> Result<Vec<Face>, Error> {
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
if faces.is_empty() {
|
||||
let selected = || faces.iter().filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE));
|
||||
if selected().next().is_none() {
|
||||
return Err(Error::NoFaces { manifest });
|
||||
}
|
||||
let missing: Vec<String> = self
|
||||
.scripts
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|tag| !faces.iter().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
|
||||
.filter(|tag| !selected().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
|
||||
.cloned()
|
||||
.collect();
|
||||
if missing.is_empty() { Ok(faces) } else { Err(Error::MissingScripts { manifest, scripts: missing }) }
|
||||
|
||||
@@ -62,7 +62,7 @@ mod sha256;
|
||||
mod tests;
|
||||
|
||||
pub use embed::{Embed, Error, target_is_wasm};
|
||||
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, UI_ROLE, parse_manifest};
|
||||
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, TAB_FACE, TAB_ROLE, UI_ROLE, parse_manifest};
|
||||
|
||||
/// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`.
|
||||
///
|
||||
@@ -81,8 +81,8 @@ pub struct EmbeddedFace {
|
||||
/// The font file's bytes, from `include_bytes!`.
|
||||
pub bytes: &'static [u8],
|
||||
/// The manifest line's `role`: `Some("ui")` for an interface face ([`UI_ROLE`]), `Some("mono")` for the
|
||||
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a
|
||||
/// line without one.
|
||||
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `Some("tab")`
|
||||
/// for the tab-title face [`Embed::tab_face`] adds ([`TAB_ROLE`]), `None` for a line without one.
|
||||
pub role: Option<&'static str>,
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
//! translation catalogs; `mono` for the monospace face, which leads an app's Monospace family; or
|
||||
//! `signature` for the handwriting face, which leads the signature family.
|
||||
//! Fields after the ninth are ignored, so a manifest that gains a field still embeds.
|
||||
//! `fonts/latin-manifest.txt` has the same format; [`Embed::tab_face`](crate::Embed::tab_face)
|
||||
//! reads one row of it and gives that face the `tab` role.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -37,6 +39,7 @@ pub struct ManifestEntry {
|
||||
pub source: String,
|
||||
/// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the
|
||||
/// monospace face, `Some("signature")` for the signature face, `None` when the line has no role.
|
||||
/// [`Embed::tab_face`](crate::Embed::tab_face) sets `Some("tab")` on the face it adds.
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
@@ -72,6 +75,13 @@ pub const MONO_ROLE: &str = "mono";
|
||||
/// The `role` of a signature face: `FontRef::signature()` selects the embedded faces that have it.
|
||||
pub const SIGNATURE_ROLE: &str = "signature";
|
||||
|
||||
/// The `role` [`Embed::tab_face`](crate::Embed::tab_face) gives the tab-title face it embeds from
|
||||
/// `fonts/latin-manifest.txt`: the tab-title family leads with the embedded face that has it.
|
||||
pub const TAB_ROLE: &str = "tab";
|
||||
|
||||
/// The family and style of the tab-title face in `fonts/latin-manifest.txt`.
|
||||
pub const TAB_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold");
|
||||
|
||||
/// Script tags of the CJK faces, which craft-fonts also ships as interface faces. `Hant` covers
|
||||
/// `Hant-HK`.
|
||||
pub const CJK_SCRIPTS: &[&str] = &["Hans", "Hant", "Jpan", "Kore", "Hani"];
|
||||
|
||||
@@ -368,3 +368,75 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() {
|
||||
let r = run(Embed::new(), Some(&dir), None);
|
||||
assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo);
|
||||
}
|
||||
|
||||
/// `Embed::tab_face` adds only the Noto Sans Condensed SemiBold row of `fonts/latin-manifest.txt`, with the `tab` role.
|
||||
/// A checkout without that manifest or row keeps its other faces, required or not; a broken manifest or row is an
|
||||
/// error only when required. The face counts for none of the scripts a required build asks for and covers none of the
|
||||
/// characters of a checked text, and a served table leaves it out.
|
||||
#[test]
|
||||
fn the_tab_face_comes_from_the_latin_manifest_with_the_tab_role() {
|
||||
let scratch = Scratch::new("tab-face");
|
||||
let dir = checkout(&scratch, &[("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x627, 0x627, None)], &[]))]);
|
||||
std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap();
|
||||
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
|
||||
std::fs::write(dir.join("fonts/inter.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
|
||||
let latin = dir.join("fonts/latin-manifest.txt");
|
||||
let row = |family: &str, style: &str, file: &str| format!("{family} | {style} | {file} | Latn | OFL-1.1 | fonts/OFL.txt | 00 | src\n");
|
||||
let both = row("Inter", "SemiBold", "fonts/inter.ttf") + &row("Noto Sans", "Condensed SemiBold", "fonts/condensed.ttf");
|
||||
std::fs::write(&latin, &both).unwrap();
|
||||
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
|
||||
assert!(r.table.contains(r#"family: "Noto Sans", style: "Condensed SemiBold""#) && r.table.contains(r#"role: Some("tab")"#), "{}", r.table);
|
||||
assert!(!r.table.contains("Inter"), "{}", r.table);
|
||||
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", latin.display())), "{:?}", r.cargo);
|
||||
// Scripts and the filter narrow only the main manifest's faces.
|
||||
let r = run(Embed::new().scripts(&["Arab"]).filter(|f| f.has_script("Arab")).tab_face(), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
|
||||
// The tab-title face does not stand in for a required script the main manifest lacks.
|
||||
let r = run(Embed::new().scripts(&["Latn"]).tab_face(), Some(&dir), Some("1"));
|
||||
assert!(matches!(&r.result, Err(Error::NoFaces { .. })), "{:?}", r.result);
|
||||
let r = run(Embed::new().scripts(&["Arab", "Latn"]).tab_face(), Some(&dir), Some("1"));
|
||||
assert!(matches!(&r.result, Err(Error::MissingScripts { scripts, .. }) if scripts == &["Latn"]), "{:?}", r.result);
|
||||
let r = run(Embed::new(), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
// A served table carries no roles, so it leaves the face out.
|
||||
let r = run(Embed::new().tab_face().serve(scratch.0.join("served"), "fonts/"), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("not serving the tab-title face")), "{:?}", r.cargo);
|
||||
// Only tab titles draw in the face, so it covers none of the characters of a checked text.
|
||||
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None), (0x4E00, 0x4E00, None)], &[])).unwrap();
|
||||
let text = scratch.0.join("text.ftl");
|
||||
std::fs::write(&text, "x = \u{4E00}\n").unwrap();
|
||||
let r = run(Embed::new().tab_face().check_text([&text]), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("1 character no embedded face covers (\u{4E00})")), "{:?}", r.cargo);
|
||||
|
||||
// No row for the face, or no latin manifest at all: the other faces and a warning, even when required.
|
||||
std::fs::write(&latin, row("Inter", "SemiBold", "fonts/inter.ttf")).unwrap();
|
||||
for required in [None, Some("1")] {
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), required);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("has no Noto Sans Condensed SemiBold row")), "{:?}", r.cargo);
|
||||
}
|
||||
std::fs::remove_file(&latin).unwrap();
|
||||
for required in [None, Some("1")] {
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), required);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("latin-manifest.txt does not exist")), "{:?}", r.cargo);
|
||||
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
|
||||
}
|
||||
|
||||
// A manifest line that does not parse, or a row whose file is missing.
|
||||
for broken in ["Noto Sans | Condensed SemiBold | fonts/condensed.ttf\n".to_owned(), row("Noto Sans", "Condensed SemiBold", "fonts/gone.ttf")] {
|
||||
std::fs::write(&latin, &broken).unwrap();
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), None);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"], "{broken}");
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("not embedding the tab-title face")), "{broken}: {:?}", r.cargo);
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
|
||||
assert!(matches!(r.result, Err(Error::Parse { .. } | Error::Read { .. })), "{broken}: {:?}", r.result);
|
||||
}
|
||||
// The build reruns when the missing file is added: it watches the folder the file would be in.
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), None);
|
||||
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
|
||||
}
|
||||
@@ -19,6 +19,8 @@
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::VecDeque;
|
||||
use std::hash::Hash;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::thread::{self, ThreadId};
|
||||
@@ -94,14 +96,17 @@ pub enum QueueOrder {
|
||||
|
||||
impl QueueOptions {
|
||||
/// Lanes for this machine: the number of cores less one, at least 2 and at most 8 (4 when
|
||||
/// the core count is unknown); 0 on wasm32.
|
||||
/// the core count is unknown); 0 on wasm32. The core count is read once per process.
|
||||
// lightcraft: crates/preview/src/pool.rs:104 `default_threads` (cores − 1 clamped to 2..=8;
|
||||
// ours is 0 on wasm32 instead of 1, because wasm runs jobs only through `run_inline`).
|
||||
pub fn default_lanes() -> usize {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return 0;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8))
|
||||
{
|
||||
static LANES: OnceLock<usize> = OnceLock::new();
|
||||
*LANES.get_or_init(|| thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -310,7 +310,8 @@ impl Component for Histogram<'_> {
|
||||
let accent = super::data::color32(colors.data.selection);
|
||||
let warn = cx.tone(craft_theme::variant::Tone::Warn);
|
||||
HistogramStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, tall)),
|
||||
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
|
||||
metrics: Metrics::new().min_size(Vec2::new(0.0, tall)),
|
||||
focus: cx.focus_look(),
|
||||
caption: TextLook::new(TypeRole::Caption, Stateful::new(cx.color(colors.text.normal))),
|
||||
stale: IconLook::new(cx.tokens.size.icon.sm, Stateful::new(warn)),
|
||||
|
||||
@@ -227,7 +227,8 @@ While a menu is open, a click or Escape in the window closes it and does not rea
|
||||
canvas gesture, no tool action); pointer moves pass through. Only one click is kept this way
|
||||
until the menu reports closed, so a menu wrongly reported open costs one click. Menu updates wait
|
||||
until the menu closes; the end of tracking wakes egui, and that frame applies them. A rebuild that
|
||||
fails keeps the menus as they were.
|
||||
fails keeps the menus as they were, and the same menus are tried once more a second later, with no
|
||||
input needed (`RebuildRetry`). When that fails too, the next change to the menus tries again.
|
||||
|
||||
AppKit's `NSMenuDidBeginTracking` and `NSMenuDidEndTracking` notifications say whether a menu is
|
||||
open (`craft_window::native_menu::menu_tracking()`, safe from any thread). Each begin comes back
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_keymap::{Chord, CommandRef, Key, Mods};
|
||||
use craft_ui::contract::{MemoKey, MemoProps};
|
||||
@@ -203,6 +204,67 @@ pub trait Backend {
|
||||
fn attach(&mut self, dispatch: Dispatch);
|
||||
}
|
||||
|
||||
/// How long a backend waits after a failed rebuild before it tries the same menus once more
|
||||
/// ([`RebuildRetry`]).
|
||||
pub const REBUILD_RETRY: Duration = Duration::from_secs(1);
|
||||
|
||||
/// When a backend tries again to build menus the platform could not build. New menus are always
|
||||
/// built. When their build fails, the same menus are tried once more [`REBUILD_RETRY`] after the
|
||||
/// failure; when that fails too, they are not tried again until they change.
|
||||
///
|
||||
/// The driver syncs a backend only when the menus' key, the gate or a menu event calls for it
|
||||
/// ([`NativeMenu::sync_with`]), so a backend keeps the menus it could not build and tries them
|
||||
/// again itself, for example from [`Backend::drain`], asking egui for a frame when the retry is
|
||||
/// due.
|
||||
#[derive(Debug)]
|
||||
pub struct RebuildRetry<B> {
|
||||
/// The menus whose build failed, and when to try them again (`None`: their retry failed too).
|
||||
failed: Option<(B, Option<Instant>)>,
|
||||
}
|
||||
|
||||
impl<B> Default for RebuildRetry<B> {
|
||||
fn default() -> RebuildRetry<B> {
|
||||
RebuildRetry { failed: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`RebuildRetry::attempt`] did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Attempt {
|
||||
/// The menus were built.
|
||||
Built,
|
||||
/// The menus were not built: their build failed, or their retry is not due yet. Try them again
|
||||
/// after this long.
|
||||
Retry(Duration),
|
||||
/// The build failed and so did its retry: these menus are not built again until they change.
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl<B: Clone + PartialEq> RebuildRetry<B> {
|
||||
/// Build `bar` with `build` (which returns whether it succeeded) unless `bar` failed before
|
||||
/// and its retry is not due, and record the outcome. `clock` gives the time. It is read again
|
||||
/// after a failed build, so the delay starts when the build fails.
|
||||
pub fn attempt(&mut self, bar: &B, clock: impl Fn() -> Instant, build: impl FnOnce() -> bool) -> Attempt {
|
||||
let now = clock();
|
||||
let retrying = match &self.failed {
|
||||
Some((failed, at)) if failed == bar => match at {
|
||||
Some(at) if now < *at => return Attempt::Retry(at.saturating_duration_since(now)),
|
||||
Some(_) => true,
|
||||
None => return Attempt::Failed,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
if build() {
|
||||
self.failed = None;
|
||||
return Attempt::Built;
|
||||
}
|
||||
let at = if retrying { None } else { clock().checked_add(REBUILD_RETRY) };
|
||||
self.failed = Some((bar.clone(), at));
|
||||
if at.is_some() { Attempt::Retry(REBUILD_RETRY) } else { Attempt::Failed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The native menu bar, while the app uses one (its in-window menus are hidden then).
|
||||
pub struct NativeMenu {
|
||||
backend: Box<dyn Backend>,
|
||||
|
||||
@@ -126,7 +126,7 @@ pub use craft_keymap::{Chord, CommandRef};
|
||||
pub use craft_ui::menu::Alternate;
|
||||
pub use customize::Customization;
|
||||
pub use documents::DOCUMENT_COMMAND_PREFIX;
|
||||
pub use driver::{Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu};
|
||||
pub use driver::{Attempt, Backend, ClipboardKeys, CommandHook, Dispatch, Event, Gate, NativeMenu, REBUILD_RETRY, RebuildRetry};
|
||||
pub use help::{HelpCommand, HelpLabels, HelpLink, HelpMenu};
|
||||
pub use keymap::{ItemState, apply_keymap, apply_state};
|
||||
pub use keytips::{KeytipControl, Keytips, KeytipsOutput};
|
||||
|
||||
+27
-5
@@ -26,16 +26,20 @@
|
||||
//! Hide Others and Minimize built-ins use the system's localized titles when the app supplies no
|
||||
//! translation, that is when the label is still the English name.
|
||||
//! - While a menu is open, changes wait until it closes.
|
||||
//! - When AppKit refuses a rebuild, the menus as they were stay up and the same menus are tried
|
||||
//! once more a second later ([`RebuildRetry`]), with no input needed; when that fails too, the
|
||||
//! next change to the menus tries again.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Instant;
|
||||
|
||||
use craft_keymap::{Chord, CommandRef, Key, Mods};
|
||||
use craft_ui::menu::Alternate;
|
||||
use craft_window::native_menu as native;
|
||||
|
||||
use crate::driver::{Backend, Dispatch, Event, NativeMenu, native_ok};
|
||||
use crate::driver::{Attempt, Backend, Dispatch, Event, NativeMenu, RebuildRetry, native_ok};
|
||||
use crate::model::{Builtin, Item, ItemKind, Menu, MenuBar, MenuRole, Node, Standard, label_or_system, native_id, structure_key, window_key};
|
||||
|
||||
/// Install the native menu bar for `bar` (a [`crate::mac_layout`] result) and return the driver
|
||||
@@ -83,7 +87,8 @@ pub fn install_with(ctx: &egui::Context, bar: &MenuBar, options: MacOptions) ->
|
||||
});
|
||||
let installed = native::NativeBar::install(&spec, native::Options::default().window_list(options.window_list), wake)?;
|
||||
let (tx, rx) = channel();
|
||||
let backend = Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None };
|
||||
let backend =
|
||||
Native { ctx: ctx.clone(), bar: installed, targets: Arc::new(Mutex::new(targets)), tx, rx, pending: None, retry: RebuildRetry::default() };
|
||||
// `NativeMenu::new` attaches the driver's dispatch, which points the handler at this menu.
|
||||
Some(NativeMenu::new(Box::new(backend)))
|
||||
}
|
||||
@@ -135,15 +140,32 @@ struct Native {
|
||||
targets: Targets,
|
||||
tx: Sender<Event>,
|
||||
rx: Receiver<Event>,
|
||||
/// The latest menus, waiting for the open menu to close.
|
||||
/// The latest menus, waiting for the open menu to close, or for the retry of a rebuild that
|
||||
/// failed.
|
||||
pending: Option<MenuBar>,
|
||||
/// Menus AppKit could not build, and when to try them again.
|
||||
retry: RebuildRetry<native::Bar>,
|
||||
}
|
||||
|
||||
impl Native {
|
||||
/// Bring the native menus in step with `bar`. When the rebuild fails and a retry is to come,
|
||||
/// `bar` waits in `pending` and egui is asked for a frame when the retry is due: the driver
|
||||
/// does not sync the same menus again.
|
||||
fn update(&mut self, bar: &MenuBar) {
|
||||
let (spec, targets) = lower(bar);
|
||||
if self.bar.apply(&spec) {
|
||||
*lock(&self.targets) = targets;
|
||||
let (native, live) = (&mut self.bar, &self.targets);
|
||||
let attempt = self.retry.attempt(&spec, Instant::now, || {
|
||||
let rebuilt = native.apply(&spec);
|
||||
if rebuilt {
|
||||
*lock(live) = targets;
|
||||
}
|
||||
!native.failed()
|
||||
});
|
||||
// egui keeps no repaint delay from one pass to the next, so a frame before the retry is
|
||||
// due asks again.
|
||||
if let Attempt::Retry(wait) = attempt {
|
||||
self.pending = Some(bar.clone());
|
||||
self.ctx.request_repaint_after(wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ use craft_ui::primitives::textures::{Revision, ThumbSource, Thumbnails};
|
||||
use craft_ui::primitives::{ContentPainterCx, HAlign, PaintShape, TextRun};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::KeyUse;
|
||||
use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx, TypeRole};
|
||||
use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, TypeRole};
|
||||
use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::{ColorImage, CornerRadius, Rect, Response, Ui, Vec2};
|
||||
|
||||
@@ -189,7 +189,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> {
|
||||
|
||||
fn sizes(&self, cx: &MeasureCx<'_, Self>) -> Sizes {
|
||||
let words = cx.env.words::<GalleryWords>();
|
||||
let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()));
|
||||
let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact));
|
||||
Sizes { tile: cx.face(GalleryTile::blank(self.aspect, self.thumb_size, self.captioned())), button, gap: cx.gap() }
|
||||
}
|
||||
}
|
||||
@@ -723,9 +723,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Component for Gallery<'_, K>
|
||||
draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1));
|
||||
draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2));
|
||||
}
|
||||
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0));
|
||||
ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last));
|
||||
ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()));
|
||||
ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0).glyphs(GlyphRole::Compact));
|
||||
ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last).glyphs(GlyphRole::Compact));
|
||||
ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact));
|
||||
}
|
||||
|
||||
/// The context request is recorded after `update`, so `finish` reads it: a secondary click on a tile, or the Menu
|
||||
|
||||
@@ -23,6 +23,7 @@ use craft_ui::contract::{BodyCx, CollectionEvent, Props as _, Scroll, Show as _,
|
||||
use craft_ui::display::Icon;
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::motion::Animate as _;
|
||||
use craft_ui::tabs::{Tab, TabKind, TabStrip};
|
||||
use egui::Ui;
|
||||
@@ -111,10 +112,10 @@ impl DisplayOrder<usize> for Titles<'_> {
|
||||
|
||||
impl ItemSource<usize> for Titles<'_> {}
|
||||
|
||||
/// A strip of text tabs over `titles` with `shown` selected; the tab picked this pass.
|
||||
pub(super) fn tab_strip(ui: &mut Ui, name: &'static str, titles: &[String], shown: usize) -> Option<usize> {
|
||||
/// A strip of text tabs named `name`, keyed by `id`, over `titles` with `shown` selected; the tab picked this pass.
|
||||
pub(super) fn tab_strip(ui: &mut Ui, id: &'static str, name: impl Into<Label>, titles: &[String], shown: usize) -> Option<usize> {
|
||||
let strip = TabStrip::new(name)
|
||||
.id_salt(name)
|
||||
.id_salt(id)
|
||||
.kind(TabKind::Text)
|
||||
.shown(shown)
|
||||
.show_items(ui, &Titles(titles), &mut |key, _| Tab::new(titles[*key].clone()).id_salt(("tab", *key)));
|
||||
@@ -139,7 +140,13 @@ fn app_tabs(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> Option<u
|
||||
state.set_tab(None);
|
||||
}
|
||||
let shown = current.map_or(0, |i| i + 1);
|
||||
let picked = Stack::new().fill_width().enabled(!state.modal()).show(ui, |ui, _| tab_strip(ui, "shortcuts.tab", &titles, shown)).inner.flatten();
|
||||
let name = env.title();
|
||||
let picked = Stack::new()
|
||||
.fill_width()
|
||||
.enabled(!state.modal())
|
||||
.show(ui, |ui, _| tab_strip(ui, "shortcuts.tab", name.clone(), &titles, shown))
|
||||
.inner
|
||||
.flatten();
|
||||
let shown = match picked {
|
||||
Some(i) => {
|
||||
state.set_tab(i.checked_sub(1).and_then(|k| ids.get(k).copied()));
|
||||
|
||||
@@ -23,7 +23,7 @@ const HOLD_DELAY_STEP: f64 = 0.05;
|
||||
/// The header for one pass.
|
||||
pub(super) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, now: f64, env: &mut Env<'_>, state: &mut DialogState) {
|
||||
if env.options.area_tabs {
|
||||
area_tabs(ui, state);
|
||||
area_tabs(ui, env, state);
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
if !env.options.area_tabs {
|
||||
@@ -66,11 +66,11 @@ fn holds(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Show as tabs.
|
||||
fn area_tabs(ui: &mut Ui, state: &mut DialogState) {
|
||||
/// Show as tabs, named like the Show select.
|
||||
fn area_tabs(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) {
|
||||
let titles: Vec<String> = state.areas.iter().map(|area| area.label.clone()).collect();
|
||||
let shown = state.areas.iter().position(|area| area.id == state.area).unwrap_or(0);
|
||||
if let Some(i) = tab_strip(ui, "shortcuts.area", &titles, shown)
|
||||
if let Some(i) = tab_strip(ui, "shortcuts.area", env.text.words().show.clone(), &titles, shown)
|
||||
&& let Some(area) = state.areas.get(i)
|
||||
{
|
||||
let id = area.id.clone();
|
||||
|
||||
@@ -5,11 +5,12 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_keymap::Mods;
|
||||
use craft_menu::{
|
||||
Alternate, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu, apply_state,
|
||||
mac_layout, structure_key,
|
||||
Alternate, Attempt, Backend, Builtin, Chord, ClipboardKeys, CommandRef, Dispatch, Event, Gate, ItemState, LayoutOptions, MenuBar, NativeMenu,
|
||||
REBUILD_RETRY, RebuildRetry, apply_state, mac_layout, structure_key,
|
||||
};
|
||||
use craft_ui::contract::{Props as _, Show as _, Tracked};
|
||||
use craft_ui::testing::focus::key_release;
|
||||
@@ -379,3 +380,56 @@ fn apply_state_with_no_change_keeps_the_revision() {
|
||||
apply_state(&mut model, |command| ItemState::default().enabled(*command != cmd("file.new")));
|
||||
assert_eq!(model.revision(), moved, "and the same changed state again does not");
|
||||
}
|
||||
|
||||
/// Menus whose build failed are not built again before their retry is due, are built once when it
|
||||
/// is due, and are not built again after that fails too; changed menus are built and get their own
|
||||
/// retry.
|
||||
#[trial]
|
||||
fn a_failed_rebuild_is_tried_once_more() {
|
||||
let (first, second) = (sample(false, true), sample(true, true));
|
||||
let mut retry = RebuildRetry::default();
|
||||
let start = Instant::now();
|
||||
let clock = Cell::new(start);
|
||||
let builds = Cell::new(0);
|
||||
let fail = || {
|
||||
builds.set(builds.get() + 1);
|
||||
false
|
||||
};
|
||||
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Retry(REBUILD_RETRY), "a failed build waits for its retry");
|
||||
clock.set(start + REBUILD_RETRY / 2);
|
||||
let Attempt::Retry(left) = retry.attempt(&first, || clock.get(), fail) else { panic!("the retry is not due yet") };
|
||||
assert!(left < REBUILD_RETRY, "a sync before the retry learns the time left: {left:?}");
|
||||
assert_eq!(builds.get(), 1, "nothing is built before the retry is due");
|
||||
clock.set(start + REBUILD_RETRY);
|
||||
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Failed, "the retry fails too");
|
||||
clock.set(start + REBUILD_RETRY * 10);
|
||||
assert_eq!(retry.attempt(&first, || clock.get(), fail), Attempt::Failed);
|
||||
assert_eq!(builds.get(), 2, "the same menus are tried once more, and only once");
|
||||
assert_eq!(retry.attempt(&second, || clock.get(), fail), Attempt::Retry(REBUILD_RETRY), "changed menus are built and get their own retry");
|
||||
assert_eq!(builds.get(), 3);
|
||||
clock.set(start + REBUILD_RETRY * 11);
|
||||
assert_eq!(retry.attempt(&second, || clock.get(), || true), Attempt::Built, "the retry builds them");
|
||||
assert_eq!(retry.attempt(&second, || clock.get(), || true), Attempt::Built, "built menus can be built again");
|
||||
}
|
||||
|
||||
/// A build that fails slowly gets the whole delay, counted from when it failed.
|
||||
#[trial]
|
||||
fn a_retry_waits_from_when_the_build_failed() {
|
||||
let bar = sample(false, true);
|
||||
let mut retry = RebuildRetry::default();
|
||||
let start = Instant::now();
|
||||
let clock = Cell::new(start);
|
||||
let slow = Duration::from_millis(1200);
|
||||
let slow_failure = || {
|
||||
clock.set(start + slow);
|
||||
false
|
||||
};
|
||||
assert_eq!(retry.attempt(&bar, || clock.get(), slow_failure), Attempt::Retry(REBUILD_RETRY));
|
||||
clock.set(start + REBUILD_RETRY);
|
||||
let Attempt::Retry(left) = retry.attempt(&bar, || clock.get(), || panic!("built before the retry was due")) else {
|
||||
panic!("the retry is not due a delay after the build began")
|
||||
};
|
||||
assert_eq!(left, slow, "the delay runs from the failure, not from when the build began");
|
||||
clock.set(start + slow + REBUILD_RETRY);
|
||||
assert_eq!(retry.attempt(&bar, || clock.get(), || true), Attempt::Built, "the retry runs when it is due");
|
||||
}
|
||||
@@ -145,6 +145,13 @@ fn own_areas_show_only_the_apps_entries_and_open_on_the_first() {
|
||||
assert_eq!(area(&rig), "all");
|
||||
}
|
||||
|
||||
/// Show as tabs is a tab list named like the Show select it replaces.
|
||||
#[trial]
|
||||
fn area_tabs_are_named_show() {
|
||||
let rig = Rig::tuned(Platform::Mac, |options| options.area_tabs = true);
|
||||
assert_eq!(rig.names_with(Role::TAB_LIST, ""), ["Show:"]);
|
||||
}
|
||||
|
||||
/// A dialog opened with a command selected, with Show listing only the app's entries, opens on the entry that lists it.
|
||||
#[trial]
|
||||
fn own_areas_open_on_the_selected_commands_entry() {
|
||||
|
||||
@@ -74,6 +74,16 @@ fn app_tabs_show_full_labels_at_125_percent_and_switch_pages() {
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn app_tabs_are_named_after_the_dialog() {
|
||||
let (mut frames, mut show) = dialog_at_125_percent("Toolbar");
|
||||
frames.idle(12, &mut show);
|
||||
let tree = frames.tree();
|
||||
let lists: Vec<&str> =
|
||||
tree.keys().into_iter().filter(|&key| tree.role_of(key) == Some(Role::TAB_LIST)).filter_map(|key| tree.name_of(key)).collect();
|
||||
assert_eq!(lists, ["Keyboard Shortcuts and Menus"]);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn app_tabs_keep_overflow_when_the_labels_do_not_fit() {
|
||||
let long_label = "Toolbar ".repeat(200);
|
||||
|
||||
@@ -25,8 +25,8 @@ pub(crate) mod stories;
|
||||
|
||||
use craft_behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, Selection, SelectionChange, keyed};
|
||||
use craft_ui::contract::{
|
||||
Bind, CollectionEvent, ColumnSpec, ContextMenuRequest, ListDrag, NoValue, Outcome, ReorderMove, ReorderRule, SelectMode, ShowCollection as _,
|
||||
ShowContainer as _, request_rename,
|
||||
Bind, CollectionEvent, ColumnSpec, ContextMenuRequest, ListDrag, NoValue, Outcome, Props as _, ReorderMove, ReorderRule, SelectMode,
|
||||
ShowCollection as _, ShowContainer as _, request_rename,
|
||||
};
|
||||
use craft_ui::list::{ListRow, RowEvent, TrailingFace, TrailingPart};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
@@ -197,13 +197,26 @@ pub struct PageList<'a> {
|
||||
picked: &'a mut Selection<usize>,
|
||||
active: usize,
|
||||
rename: Option<usize>,
|
||||
document: Option<u64>,
|
||||
}
|
||||
|
||||
impl<'a> PageList<'a> {
|
||||
/// A list named `label` of `rows`, with `picked` as the selection and `active` as the page or artboard being
|
||||
/// edited.
|
||||
pub fn new(label: impl Into<Label>, rows: &'a [PageListRow], picked: &'a mut Selection<usize>, active: usize) -> Self {
|
||||
PageList { label: label.into(), rows, picked, active, rename: None }
|
||||
PageList { label: label.into(), rows, picked, active, rename: None, document: None }
|
||||
}
|
||||
|
||||
/// The document the list shows, so the list's own state (rename, scroll, lead) is per document: a rename left
|
||||
/// open in one document does not open on the row with the same number in another. Without it every document
|
||||
/// shares one.
|
||||
#[must_use]
|
||||
pub fn document(mut self, key: impl std::hash::Hash) -> Self {
|
||||
use std::hash::Hasher as _;
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
key.hash(&mut hasher);
|
||||
self.document = Some(hasher.finish());
|
||||
self
|
||||
}
|
||||
|
||||
/// Starts renaming `row` (the app's Rename command): its field opens at the list's next pass.
|
||||
@@ -215,7 +228,14 @@ impl<'a> PageList<'a> {
|
||||
|
||||
/// Shows the list and returns its response and the events for the app to apply.
|
||||
pub fn show(self, ui: &mut Ui) -> PageListOutput {
|
||||
let PageList { label, rows, picked, active, rename } = self;
|
||||
let PageList { label, rows, picked, active, rename, document } = self;
|
||||
// Row numbers restart in every document, so with a document the list's state (the panel's scroll and the
|
||||
// table inside it) is keyed by the list's label and the document.
|
||||
let panel = Panel::new(label.clone());
|
||||
let panel = match document {
|
||||
Some(document) => panel.id(ui.scope_id().with(("page-list", label.as_str(), document))),
|
||||
None => panel,
|
||||
};
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PageListWords>();
|
||||
let unlocked = |from: &[usize]| from.iter().copied().filter(|&row| rows.get(row).is_some_and(|r| !r.locked)).collect::<Vec<_>>();
|
||||
@@ -235,7 +255,7 @@ impl<'a> PageList<'a> {
|
||||
let after = ReorderMove::new(active, vec![active], to, false);
|
||||
PageListEvent::Reorder(EditEvent::set(Mixed::Same(before), after, Arc::from(label.as_str()), None))
|
||||
};
|
||||
let response = Panel::new(label.clone())
|
||||
let response = panel
|
||||
.footer(|ui, _| {
|
||||
let list = *list_id.borrow();
|
||||
let ours = move |drag: &ListDrag<usize>| Some(drag.list) == list;
|
||||
|
||||
@@ -290,7 +290,8 @@ impl Component for ReadingView<'_> {
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ReadingViewStyleKey) -> ReadingViewStyle {
|
||||
ReadingViewStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, cx.tokens.size.plot.height)),
|
||||
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
|
||||
metrics: Metrics::new().min_size(Vec2::new(0.0, cx.tokens.size.plot.height)),
|
||||
focus: cx.focus_look(),
|
||||
gap: cx.tokens.space.gap.section,
|
||||
reach: cx.tokens.size.hit.target,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! `PageList`: with a document, a rename left open and the scroll position do not carry over to another document.
|
||||
|
||||
use craft_behavior::Selection;
|
||||
use craft_pages::ui::{PageList, PageListEvent, PageListRow};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
/// The room of the list: wide enough for the names, tall enough for a few rows and the footer.
|
||||
const PANEL: Vec2 = Vec2::new(320.0, 300.0);
|
||||
|
||||
type Seen = Rc<RefCell<Vec<PageListEvent>>>;
|
||||
|
||||
/// The list over the rows of the document the trial sets, with the events it reports.
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
seen: Seen,
|
||||
document: Rc<Cell<u32>>,
|
||||
}
|
||||
|
||||
/// The list over `rows(document)`, starting in document 0.
|
||||
fn rig(rows: fn(u32) -> Vec<PageListRow>) -> Rig {
|
||||
let seen: Seen = Rc::default();
|
||||
let document = Rc::new(Cell::new(0_u32));
|
||||
let picked = Rc::new(RefCell::new(Selection::single(0_usize)));
|
||||
let (sink, shown, choice) = (Rc::clone(&seen), Rc::clone(&document), Rc::clone(&picked));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let rows = rows(shown.get());
|
||||
let mut picked = choice.borrow_mut();
|
||||
let out = PageList::new("Artboards", &rows, &mut picked, 0).document(shown.get()).show(ui);
|
||||
sink.borrow_mut().extend(out.events);
|
||||
});
|
||||
fixture.room(PANEL);
|
||||
fixture.settle();
|
||||
Rig { fixture, seen, document }
|
||||
}
|
||||
|
||||
/// Two rows, named apart in each document.
|
||||
fn two_rows(document: u32) -> Vec<PageListRow> {
|
||||
let names = if document == 0 { ["Cover", "Back"] } else { ["Front", "Inside"] };
|
||||
names.into_iter().map(PageListRow::new).collect()
|
||||
}
|
||||
|
||||
/// Forty rows, more than the panel shows, named by document and number.
|
||||
fn many_rows(document: u32) -> Vec<PageListRow> {
|
||||
let prefix = if document == 0 { "Sheet" } else { "Page" };
|
||||
(1..=40).map(|n| PageListRow::new(format!("{prefix} {n}"))).collect()
|
||||
}
|
||||
|
||||
/// The renames reported since the last call, as row and name.
|
||||
fn renames(seen: &Seen) -> Vec<(usize, String)> {
|
||||
seen.borrow_mut()
|
||||
.drain(..)
|
||||
.filter_map(|event| if let PageListEvent::Rename { row, text, .. } = event { Some((row, text)) } else { None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Row numbers restart in every document, so the rename field of row 2 in one document is not the field of row 2 in
|
||||
/// another: a switch with the field open renames nothing in the document switched to.
|
||||
#[trial]
|
||||
fn a_rename_left_open_does_not_carry_over_to_another_document() {
|
||||
let mut rig = rig(two_rows);
|
||||
let back = rig.fixture.by_label("Back").expect("the second row shows");
|
||||
rig.fixture.click(&back);
|
||||
rig.fixture.idle(2);
|
||||
rig.fixture.key(Key::F2, Modifiers::NONE);
|
||||
rig.fixture.idle(2);
|
||||
rig.fixture.type_text("X");
|
||||
rig.fixture.idle(2);
|
||||
assert!(renames(&rig.seen).is_empty(), "typing in the field renames nothing yet");
|
||||
|
||||
rig.document.set(1);
|
||||
rig.fixture.idle(3);
|
||||
assert!(rig.fixture.by_label("Inside").is_some(), "the other document's rows show");
|
||||
rig.fixture.type_text("Y");
|
||||
rig.fixture.key(Key::Enter, Modifiers::NONE);
|
||||
rig.fixture.idle(2);
|
||||
let other = renames(&rig.seen);
|
||||
assert!(other.is_empty(), "the field of the first document does not open on the second's row 2: {other:?}");
|
||||
|
||||
rig.document.set(0);
|
||||
rig.fixture.idle(3);
|
||||
rig.fixture.key(Key::Enter, Modifiers::NONE);
|
||||
rig.fixture.idle(2);
|
||||
let back = renames(&rig.seen);
|
||||
assert!(back.iter().all(|(_, name)| !name.contains('Y')), "a rename back in the first document has nothing typed in the second: {back:?}");
|
||||
}
|
||||
|
||||
/// A list scrolled down in one document shows another document's list from its own position, the top.
|
||||
#[trial]
|
||||
fn the_scroll_position_does_not_carry_over_to_another_document() {
|
||||
let mut rig = rig(many_rows);
|
||||
let first = rig.fixture.by_label("Sheet 1").expect("the first row shows");
|
||||
rig.fixture.click(&first);
|
||||
rig.fixture.idle(2);
|
||||
rig.fixture.key(Key::End, Modifiers::NONE);
|
||||
rig.fixture.idle(3);
|
||||
// A row is in view when its rect is inside the room the list is shown in.
|
||||
let shown = |rig: &Rig, name: &str| rig.fixture.by_label(name).is_some_and(|row| rig.fixture.shown().contains_rect(row.rect));
|
||||
assert!(shown(&rig, "Sheet 40") && !shown(&rig, "Sheet 1"), "End scrolls the first document's list to its last row");
|
||||
|
||||
rig.document.set(1);
|
||||
rig.fixture.idle(3);
|
||||
assert!(shown(&rig, "Page 1"), "the second document's list shows its first row");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The screen tests of craft-pages, folded into the lib's test target.
|
||||
|
||||
pub(crate) mod access;
|
||||
pub(crate) mod list;
|
||||
pub(crate) mod range;
|
||||
pub(crate) mod rulers;
|
||||
pub(crate) mod setup;
|
||||
|
||||
@@ -23,7 +23,7 @@ pull in heavier dependencies.
|
||||
| always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. |
|
||||
| always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. |
|
||||
| always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. |
|
||||
| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. |
|
||||
| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` gives a file an access list of the user and SYSTEM only, `create_private_dir` and `create_private_file` create a folder or file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. |
|
||||
| always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. |
|
||||
| `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). |
|
||||
| `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. |
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
//! a new folder at a drive root, `C:\Users\Public` or `C:\ProgramData` let every signed-in user
|
||||
//! read what is created in them. `restrict_to_owner` replaces the whole list with the current
|
||||
//! user and SYSTEM only, makes that user the owner, and checks the result. `create_private_dir`
|
||||
//! does the same for a new folder whose list the files created in it inherit, so a file can be
|
||||
//! private from the moment it exists. `read_with_sddl` reads a file and its security descriptor
|
||||
//! creates a folder with that owner and list from the start, which the files created in it
|
||||
//! inherit, so a file can be private from the moment it exists. `read_with_sddl` reads a file and its security descriptor
|
||||
//! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts
|
||||
//! by SID and so reads the same in every Windows language, and says why another user could have
|
||||
//! written or could read the file. They run the tools Windows ships rather than calling the
|
||||
//! security API directly, which would need `unsafe`.
|
||||
//! security API directly, which would need `unsafe`. A run of a tool that takes longer than
|
||||
//! `TOOL_LIMIT` (10 s) is ended, and the function fails with an error of kind
|
||||
//! [`std::io::ErrorKind::TimedOut`].
|
||||
|
||||
/// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL or
|
||||
/// as `read_with_sddl` writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no
|
||||
@@ -21,6 +23,18 @@
|
||||
/// file over. `restrict_to_owner` never grants it, so the app's own file always passes; a file
|
||||
/// that inherited it from a user's folder is refused.
|
||||
pub fn foreign_access(sddl: &str, me: &str) -> Option<String> {
|
||||
foreign(sddl, me, false)
|
||||
}
|
||||
|
||||
/// [`foreign_access`] for a folder's descriptor: an inherit-only entry (`IO`) counts too, since
|
||||
/// every file and folder created in the folder gets it.
|
||||
#[cfg(any(test, windows))]
|
||||
fn foreign_folder_access(sddl: &str, me: &str) -> Option<String> {
|
||||
foreign(sddl, me, true)
|
||||
}
|
||||
|
||||
/// [`foreign_access`], counting inherit-only entries when `inherit_only` is set.
|
||||
fn foreign(sddl: &str, me: &str, inherit_only: bool) -> Option<String> {
|
||||
let me = me.trim();
|
||||
let owner = section(sddl, "O:");
|
||||
match owner {
|
||||
@@ -41,7 +55,7 @@ pub fn foreign_access(sddl: &str, me: &str) -> Option<String> {
|
||||
let (Some(kind), Some(flags)) = (parts.first(), parts.get(1)) else { continue };
|
||||
// Deny entries take access away, and inherit-only entries apply to children, not the file.
|
||||
let allows = matches!(*kind, "A" | "OA" | "XA" | "ZA");
|
||||
if !allows || flags.contains("IO") {
|
||||
if !allows || (flags.contains("IO") && !inherit_only) {
|
||||
continue;
|
||||
}
|
||||
// An entry that grants access but names no account can't be shown to be the user's.
|
||||
@@ -146,11 +160,129 @@ fn system_tool(relative: &str) -> std::process::Command {
|
||||
command
|
||||
}
|
||||
|
||||
/// How long one run of a tool may take before it is ended. Each tool finishes in a second or two.
|
||||
/// On some computers a new process is left suspended (security software holding it), and without
|
||||
/// a limit the caller would wait on it for as long as it stays that way.
|
||||
#[cfg(windows)]
|
||||
pub const TOOL_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// How often [`run_until`] checks whether the tool has exited.
|
||||
#[cfg(any(test, windows))]
|
||||
const POLL: std::time::Duration = std::time::Duration::from_millis(20);
|
||||
|
||||
/// How many more checks [`run_until`] makes for a tool it has ended to exit before it stops
|
||||
/// waiting on it.
|
||||
#[cfg(any(test, windows))]
|
||||
const EXIT_POLLS: u32 = 50;
|
||||
|
||||
/// How a run of [`run_until`] ended.
|
||||
#[cfg(any(test, windows))]
|
||||
enum Ran {
|
||||
/// The tool exited by itself: its status and output, and how writing its standard input went.
|
||||
Exited(std::process::Output, std::io::Result<()>),
|
||||
/// The time was up first and the tool was ended. `exited` is whether it was then seen to exit.
|
||||
Ended { exited: bool },
|
||||
}
|
||||
|
||||
/// Start `command` with its standard input, output and error piped, hand its standard input to
|
||||
/// `feed` on a thread of its own, and wait for it to exit. Between checks, `expired` gets what
|
||||
/// the tool has written to its standard output so far; when it answers `true` first, the tool is
|
||||
/// ended ([`std::process::Child::kill`]). Standard output and error are read on threads of their
|
||||
/// own, so a tool that writes more than a pipe holds is not stopped by it.
|
||||
#[cfg(any(test, windows))]
|
||||
fn run_until(
|
||||
mut command: std::process::Command,
|
||||
feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static,
|
||||
mut expired: impl FnMut(&[u8]) -> bool,
|
||||
) -> std::io::Result<Ran> {
|
||||
use std::io::Read as _;
|
||||
use std::process::Stdio;
|
||||
let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
|
||||
let fed = child.stdin.take().map(|stdin| std::thread::spawn(move || feed(stdin)));
|
||||
let (chunks, received) = std::sync::mpsc::channel::<Vec<u8>>();
|
||||
if let Some(mut out) = child.stdout.take() {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 4096];
|
||||
while let Ok(n @ 1..) = out.read(&mut buf) {
|
||||
if chunks.send(buf.get(..n).unwrap_or_default().to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let errors = child.stderr.take().map(|mut err| {
|
||||
std::thread::spawn(move || {
|
||||
let mut text = Vec::new();
|
||||
let _ = err.read_to_end(&mut text);
|
||||
text
|
||||
})
|
||||
});
|
||||
let mut stdout = Vec::new();
|
||||
loop {
|
||||
stdout.extend(received.try_iter().flatten());
|
||||
if let Some(status) = child.try_wait()? {
|
||||
// The pipes close when the tool exits, which ends both readers.
|
||||
stdout.extend(received.iter().flatten());
|
||||
let stderr = errors.and_then(|e| e.join().ok()).unwrap_or_default();
|
||||
let sent = match fed.map(std::thread::JoinHandle::join) {
|
||||
Some(Ok(sent)) => sent,
|
||||
Some(Err(_)) => Err(std::io::Error::other("the thread writing the standard input stopped")),
|
||||
None => Err(std::io::Error::other("the standard input could not be opened")),
|
||||
};
|
||||
return Ok(Ran::Exited(std::process::Output { status, stdout, stderr }, sent));
|
||||
}
|
||||
if expired(&stdout) {
|
||||
let _ = child.kill();
|
||||
let mut exited = false;
|
||||
for _ in 0..EXIT_POLLS {
|
||||
if child.try_wait().ok().flatten().is_some() {
|
||||
exited = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
return Ok(Ran::Ended { exited });
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `command`, with nothing on its standard input, for at most [`TOOL_LIMIT`]: its status and
|
||||
/// output, or an error of kind [`std::io::ErrorKind::TimedOut`] when it was ended.
|
||||
#[cfg(windows)]
|
||||
fn run(command: std::process::Command) -> std::io::Result<std::process::Output> {
|
||||
let deadline = std::time::Instant::now() + TOOL_LIMIT;
|
||||
let program = tool_name(&command);
|
||||
let close = |stdin: std::process::ChildStdin| {
|
||||
drop(stdin);
|
||||
Ok(())
|
||||
};
|
||||
match run_until(command, close, |_| std::time::Instant::now() >= deadline)? {
|
||||
Ran::Exited(out, _) => Ok(out),
|
||||
Ran::Ended { .. } => Err(timed_out(&program)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name of the program `command` starts, for messages.
|
||||
#[cfg(windows)]
|
||||
fn tool_name(command: &std::process::Command) -> String {
|
||||
let program = std::path::Path::new(command.get_program());
|
||||
program.file_name().unwrap_or(program.as_os_str()).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// The error for a run of `program` that [`run_until`] ended.
|
||||
#[cfg(windows)]
|
||||
fn timed_out(program: &str) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{program} did not finish within {} s and was ended", TOOL_LIMIT.as_secs()))
|
||||
}
|
||||
|
||||
/// The current user's SID (`whoami /user`). It starts a process, so a caller that needs it for
|
||||
/// several steps reads it once and passes it to each.
|
||||
#[cfg(windows)]
|
||||
pub fn current_user_sid() -> std::io::Result<String> {
|
||||
let out = system_tool(WHOAMI).args(["/user", "/fo", "csv", "/nh"]).output()?;
|
||||
let mut whoami = system_tool(WHOAMI);
|
||||
whoami.args(["/user", "/fo", "csv", "/nh"]);
|
||||
let out = run(whoami)?;
|
||||
if !out.status.success() {
|
||||
return Err(std::io::Error::other("whoami /user failed"));
|
||||
}
|
||||
@@ -177,32 +309,177 @@ fn sid_from_whoami(text: &str) -> Option<String> {
|
||||
/// replace it, while setting the owner needs the Full control it grants (a folder may give Modify).
|
||||
#[cfg(windows)]
|
||||
pub fn restrict_to_owner(path: &std::path::Path, me: &str) -> std::io::Result<()> {
|
||||
set_access_list(path, me, Kind::File)?;
|
||||
set_access_list(path, me)?;
|
||||
icacls(path, &["/setowner".into(), format!("*{me}")])?;
|
||||
still_foreign(&sddl_of(path)?, me)
|
||||
}
|
||||
|
||||
/// Create the folder `dir`, which must not exist yet, and give it an access list of user `me` (as
|
||||
/// for [`restrict_to_owner`]) and SYSTEM only, which every file created in it inherits; then make
|
||||
/// that user its owner and check the result as [`restrict_to_owner`] does. A file created in it is
|
||||
/// private from the moment it exists. Restricting a file after creating it leaves a window in which another user
|
||||
/// whom the parent folder lets read it can open a handle, and Windows checks access only when a
|
||||
/// handle is opened, so a later change of the list doesn't revoke it. A handle on the folder
|
||||
/// itself, opened during the folder's own window, gives no access to the files created in it
|
||||
/// later. The folder is removed again when it can't be restricted.
|
||||
/// Create the folder `dir`, which must not exist yet and whose parent must, with user `me` (as for
|
||||
/// [`restrict_to_owner`]) as its owner and an access list of that user and SYSTEM only, which every
|
||||
/// file created in it inherits, given to Windows in the call that creates the folder. The folder
|
||||
/// never has its parent's access list, and a file created in it is private from the moment it
|
||||
/// exists. The folder is created beside `dir` under a name of its own
|
||||
/// (`.<name>.<process id>.<count>.tmp`) and then moved to `dir`, which fails when `dir` exists.
|
||||
/// Then check its descriptor, inherit-only entries included. An existing `dir` is an error of kind
|
||||
/// [`std::io::ErrorKind::AlreadyExists`] and a missing parent one of kind
|
||||
/// [`std::io::ErrorKind::NotFound`]; the folder is removed again when the check fails.
|
||||
///
|
||||
/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error
|
||||
/// of kind [`std::io::ErrorKind::TimedOut`]; the folder under its own name is then removed once
|
||||
/// PowerShell has exited. A folder PowerShell had already moved to `dir` stays there, with the
|
||||
/// access list it was created with: this call can't tell it from a folder another process put at
|
||||
/// `dir` since, so it doesn't remove what is there.
|
||||
#[cfg(windows)]
|
||||
pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()> {
|
||||
std::fs::create_dir(dir)?;
|
||||
fn restrict(dir: &std::path::Path, me: &str) -> std::io::Result<()> {
|
||||
set_access_list(dir, me, Kind::Folder)?;
|
||||
icacls(dir, &["/setowner".into(), format!("*{me}")])?;
|
||||
still_foreign(&sddl_of(dir)?, me)
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
/// Numbers the staged folders of this process.
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
// No double quotes: the command line would strip them. `Directory.CreateDirectory` also creates
|
||||
// a missing parent and returns an existing folder as it is, hence the checks before it.
|
||||
// `Directory.Move` doesn't replace an existing folder (`std::fs::rename` does, when it is
|
||||
// empty).
|
||||
const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \
|
||||
if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \
|
||||
if (-not [IO.Directory]::Exists([IO.Path]::GetDirectoryName($env:CRAFT_ACL_PATH))) { exit 4 }; \
|
||||
if (Test-Path -LiteralPath $env:CRAFT_ACL_STAGED) { exit 5 }; \
|
||||
$s = New-Object Security.AccessControl.DirectorySecurity; \
|
||||
$s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)'); \
|
||||
[void][IO.Directory]::CreateDirectory($env:CRAFT_ACL_STAGED, $s); \
|
||||
try { [IO.Directory]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \
|
||||
catch { [IO.Directory]::Delete($env:CRAFT_ACL_STAGED); if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; throw }";
|
||||
// A relative `dir` such as `private` has no parent in its text; the script needs one.
|
||||
let dir = &std::path::absolute(dir)?;
|
||||
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let staged = dir.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
|
||||
let mut powershell = system_tool(POWERSHELL);
|
||||
powershell
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
|
||||
.env("CRAFT_ACL_PATH", dir)
|
||||
.env("CRAFT_ACL_STAGED", &staged)
|
||||
.env("CRAFT_ACL_USER", me);
|
||||
let deadline = std::time::Instant::now() + TOOL_LIMIT;
|
||||
let close = |stdin: std::process::ChildStdin| {
|
||||
drop(stdin);
|
||||
Ok(())
|
||||
};
|
||||
let out = match run_until(powershell, close, |_| std::time::Instant::now() >= deadline)? {
|
||||
Ran::Exited(out, _) => out,
|
||||
Ran::Ended { exited } => {
|
||||
if exited {
|
||||
let _ = std::fs::remove_dir(&staged);
|
||||
}
|
||||
return Err(timed_out("powershell.exe"));
|
||||
}
|
||||
};
|
||||
match out.status.code() {
|
||||
Some(3) => return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the folder already exists")),
|
||||
Some(4) => return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "the folder's parent does not exist")),
|
||||
_ if !out.status.success() => {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"PowerShell could not create the folder for its owner only: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let restricted = restrict(dir, me);
|
||||
if restricted.is_err() {
|
||||
let checked = sddl_of(dir).and_then(|sddl| match foreign_folder_access(&sddl, me) {
|
||||
None => Ok(()),
|
||||
Some(problem) => Err(std::io::Error::other(format!("the folder could not be restricted to its owner: {problem}"))),
|
||||
});
|
||||
if checked.is_err() {
|
||||
let _ = std::fs::remove_dir(dir);
|
||||
}
|
||||
restricted
|
||||
checked
|
||||
}
|
||||
|
||||
/// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`])
|
||||
/// as its owner and an access list of that user and SYSTEM only, given to Windows in the call that
|
||||
/// creates the file, so the file never has its folder's access list, and write `contents` through
|
||||
/// that handle, opened unshared. The file is created beside `path` under a name of its own
|
||||
/// (`.<name>.<process id>.<count>.tmp`) and takes the name `path` only once `contents` are
|
||||
/// written, so `path` never holds a partly written file. Then check the file's descriptor as
|
||||
/// [`restrict_to_owner`] does. An existing `path` is an error of kind
|
||||
/// [`std::io::ErrorKind::AlreadyExists`] and is left as it is. A file that was created but could
|
||||
/// not be written or checked is removed again. `contents` reach PowerShell through its standard
|
||||
/// input, never as script text or an environment variable.
|
||||
///
|
||||
/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error
|
||||
/// of kind [`std::io::ErrorKind::TimedOut`]. The file under its own name is then removed. If
|
||||
/// PowerShell is not seen to exit after being ended, that file may stay, and a file PowerShell had
|
||||
/// already moved to `path` stays there: this call can't tell it from a file another process put at
|
||||
/// `path` since. Either still has the access list given when it was created.
|
||||
#[cfg(windows)]
|
||||
pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> {
|
||||
use std::io::Write as _;
|
||||
let deadline = std::time::Instant::now() + TOOL_LIMIT;
|
||||
let contents = contents.to_vec();
|
||||
create_private_file_until(path, me, move |mut stdin| stdin.write_all(&contents), |_| std::time::Instant::now() >= deadline)
|
||||
}
|
||||
|
||||
/// [`create_private_file`], with `feed` writing the contents to PowerShell's standard input and
|
||||
/// `expired` saying when to end it, as [`run_until`] takes them.
|
||||
#[cfg(windows)]
|
||||
fn create_private_file_until(
|
||||
path: &std::path::Path,
|
||||
me: &str,
|
||||
feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static,
|
||||
expired: impl FnMut(&[u8]) -> bool,
|
||||
) -> std::io::Result<()> {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
/// The exit code the script ends with when the file already exists.
|
||||
const EXISTS: i32 = 3;
|
||||
/// Numbers the staged files of this process.
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
// No double quotes: the command line would strip them. -2147024816 and -2147024713 are the
|
||||
// HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. `File.Move` fails when the
|
||||
// destination exists.
|
||||
const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \
|
||||
if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \
|
||||
$s = New-Object Security.AccessControl.FileSecurity; \
|
||||
$s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)'); \
|
||||
$fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_STAGED, [IO.FileMode]::CreateNew, \
|
||||
[Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s); \
|
||||
try { [Console]::OpenStandardInput().CopyTo($fs); $fs.Flush($true); $fs.Dispose() } \
|
||||
catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_STAGED); throw }; \
|
||||
try { [IO.File]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \
|
||||
catch { [IO.File]::Delete($env:CRAFT_ACL_STAGED); $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \
|
||||
if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }";
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
|
||||
let mut powershell = system_tool(POWERSHELL);
|
||||
powershell
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
|
||||
.env("CRAFT_ACL_PATH", path)
|
||||
.env("CRAFT_ACL_STAGED", &staged)
|
||||
.env("CRAFT_ACL_USER", me);
|
||||
// A script that stops before reading (the file exists) closes the pipe; its exit code says why.
|
||||
let ran = run_until(powershell, feed, expired);
|
||||
// The staged name is this call's own, so removing it never removes another process's file.
|
||||
// PowerShell holds the staged file open unshared until it exits.
|
||||
let (out, sent) = match ran? {
|
||||
Ran::Exited(out, sent) => (out, sent),
|
||||
Ran::Ended { exited } => {
|
||||
if exited {
|
||||
let _ = std::fs::remove_file(&staged);
|
||||
}
|
||||
return Err(timed_out("powershell.exe"));
|
||||
}
|
||||
};
|
||||
if out.status.code() == Some(EXISTS) {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"));
|
||||
}
|
||||
if !out.status.success() {
|
||||
let _ = std::fs::remove_file(&staged);
|
||||
return Err(std::io::Error::other(format!(
|
||||
"PowerShell could not create the file for its owner only: {}",
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)));
|
||||
}
|
||||
let checked = sent.and_then(|()| sddl_of(path)).and_then(|sddl| still_foreign(&sddl, me));
|
||||
if checked.is_err() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
checked
|
||||
}
|
||||
|
||||
/// `Err` naming the problem when the descriptor read back after restricting still isn't `me`'s
|
||||
@@ -215,37 +492,18 @@ fn still_foreign(sddl: &str, me: &str) -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`set_access_list`] restricts: a file, or a folder whose entries the files and folders
|
||||
/// created in it inherit.
|
||||
/// Set file `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected
|
||||
/// from inheritance. Only the list is written, not the owner. `me` and the path reach PowerShell
|
||||
/// through environment variables, never as script text.
|
||||
#[cfg(windows)]
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
File,
|
||||
Folder,
|
||||
}
|
||||
|
||||
/// Set `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected from
|
||||
/// inheritance; on a folder, what is created in it inherits the two entries. Only the list is
|
||||
/// written, not the owner. `me` and the path reach PowerShell through environment variables, never
|
||||
/// as script text.
|
||||
#[cfg(windows)]
|
||||
fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Result<()> {
|
||||
fn set_access_list(path: &std::path::Path, me: &str) -> std::io::Result<()> {
|
||||
// No double quotes: the command line would strip them.
|
||||
const FILE: &str = "$s = New-Object Security.AccessControl.FileSecurity; \
|
||||
const SCRIPT: &str = "$s = New-Object Security.AccessControl.FileSecurity; \
|
||||
$s.SetSecurityDescriptorSddlForm('D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)', 'Access'); \
|
||||
[IO.File]::SetAccessControl($env:CRAFT_ACL_PATH, $s)";
|
||||
const FOLDER: &str = "$s = New-Object Security.AccessControl.DirectorySecurity; \
|
||||
$s.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)', 'Access'); \
|
||||
[IO.Directory]::SetAccessControl($env:CRAFT_ACL_PATH, $s)";
|
||||
let script = match kind {
|
||||
Kind::File => FILE,
|
||||
Kind::Folder => FOLDER,
|
||||
};
|
||||
let out = system_tool(POWERSHELL)
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", script])
|
||||
.env("CRAFT_ACL_PATH", path)
|
||||
.env("CRAFT_ACL_USER", me)
|
||||
.output()?;
|
||||
let mut powershell = system_tool(POWERSHELL);
|
||||
powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me);
|
||||
let out = run(powershell)?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -255,7 +513,9 @@ fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Res
|
||||
|
||||
#[cfg(windows)]
|
||||
fn icacls(path: &std::path::Path, args: &[String]) -> std::io::Result<()> {
|
||||
let out = system_tool(ICACLS).arg(path).args(args).output()?;
|
||||
let mut icacls = system_tool(ICACLS);
|
||||
icacls.arg(path).args(args);
|
||||
let out = run(icacls)?;
|
||||
if out.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -294,27 +554,30 @@ pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(Stri
|
||||
);
|
||||
// Bounded so the script's `[int]` and buffer stay small; a token file is far below this.
|
||||
let max = max.min(1 << 20);
|
||||
let out = system_tool(POWERSHELL)
|
||||
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
|
||||
.env("CRAFT_ACL_PATH", path)
|
||||
.env("CRAFT_ACL_MAX", max.to_string())
|
||||
.output()?;
|
||||
let mut powershell = system_tool(POWERSHELL);
|
||||
powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_MAX", max.to_string());
|
||||
let out = run(powershell)?;
|
||||
let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None };
|
||||
read.ok_or_else(|| std::io::Error::other("PowerShell could not read the file with its owner and access list"))
|
||||
}
|
||||
|
||||
/// The security descriptor of `path` as [`read_with_sddl`] writes it, read by name without opening
|
||||
/// the file's contents, so it works on a file that is open for writing (an app restricts its
|
||||
/// token file before writing the token through the handle it created).
|
||||
/// token file before writing the token through the handle it created). A folder is read as a
|
||||
/// folder, so its inherit-only entries are included (`IO`); a file's reading leaves them out.
|
||||
#[cfg(windows)]
|
||||
pub fn sddl_of(path: &std::path::Path) -> std::io::Result<String> {
|
||||
const SCRIPT: &str = concat!(
|
||||
// Stop: a failed read (a missing file) must end the script with an error, not print `O:`.
|
||||
"$ErrorActionPreference = 'Stop'; $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @([IO.File]::GetAccessControl($env:CRAFT_ACL_PATH).GetSecurityDescriptorBinaryForm(), 0); ",
|
||||
"$ErrorActionPreference = 'Stop'; $p = $env:CRAFT_ACL_PATH; \
|
||||
if ([IO.Directory]::Exists($p)) { $sec = [IO.Directory]::GetAccessControl($p) } else { $sec = [IO.File]::GetAccessControl($p) }; \
|
||||
$raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @($sec.GetSecurityDescriptorBinaryForm(), 0); ",
|
||||
describe_raw!(),
|
||||
"[Console]::Out.Write($sddl + [char]10)"
|
||||
);
|
||||
let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).output()?;
|
||||
let mut powershell = system_tool(POWERSHELL);
|
||||
powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path);
|
||||
let out = run(powershell)?;
|
||||
let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None };
|
||||
read.map(|(sddl, _)| sddl).ok_or_else(|| std::io::Error::other("PowerShell could not read the file's owner and access list"))
|
||||
}
|
||||
@@ -410,6 +673,15 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
|
||||
assert!(foreign_access("D:(A;;FA;;;SY)", ME).unwrap().contains("owner"));
|
||||
}
|
||||
|
||||
/// An inherit-only entry doesn't apply to a file, but does to what's created in a folder.
|
||||
#[test]
|
||||
fn an_inherit_only_entry_counts_for_a_folder_only() {
|
||||
let sddl = format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FR;;;BU)");
|
||||
assert_eq!(foreign_access(&sddl, ME), None, "{sddl}");
|
||||
assert!(foreign_folder_access(&sddl, ME).is_some_and(|p| p.contains("BU")), "{sddl}");
|
||||
assert_eq!(foreign_folder_access(&format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FA;;;SY)"), ME), None);
|
||||
}
|
||||
|
||||
/// A conditional entry can hold a `:` in a string; the access list doesn't end there, so the
|
||||
/// entry after it is still checked.
|
||||
#[test]
|
||||
@@ -495,6 +767,159 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder's inherit-only entries are read, and the folder check counts them: every file
|
||||
/// created in the folder would get them.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_folders_inherit_only_entries_are_read_and_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-inherit-only-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)(IO)R").output().unwrap();
|
||||
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
|
||||
let sddl = sddl_of(&dir).unwrap();
|
||||
assert!(sddl.contains(";IO;") && sddl.contains(";S-1-5-32-545)"), "the inherit-only entry for Users is read: {sddl}");
|
||||
let me = current_user_sid().unwrap();
|
||||
assert!(foreign_folder_access(&sddl, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `create_private_dir` gives the folder its owner and list in the call that creates it, so in
|
||||
/// a folder that lets Users read what's created in it, no step leaves the new folder with that
|
||||
/// entry: the folder is moved to its name only after it was created with its own list. An
|
||||
/// existing name and a missing parent are refused.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_private_folder_has_its_list_from_the_start() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-private-dir-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
|
||||
let me = current_user_sid().unwrap();
|
||||
let private = dir.join("staging");
|
||||
let made = create_private_dir(&private, &user());
|
||||
assert!(made.is_ok(), "{made:?}");
|
||||
let folder = sddl_of(&private).unwrap();
|
||||
assert_eq!((section(&folder, "O:"), foreign_folder_access(&folder, &me)), (Some(me.as_str()), None), "{folder}");
|
||||
assert!(!folder.contains(";S-1-5-32-545)") && !folder.contains(";BU)"), "Users must not inherit read access: {folder}");
|
||||
let names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(names, ["staging"], "no folder is left under its own name");
|
||||
let again = create_private_dir(&private, &user()).unwrap_err();
|
||||
assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}");
|
||||
let orphan = create_private_dir(&dir.join("missing").join("staging"), &user()).unwrap_err();
|
||||
assert_eq!(orphan.kind(), std::io::ErrorKind::NotFound, "{orphan}");
|
||||
assert!(!dir.join("missing").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A file created by `create_private_file` in a folder that lets Users read what's in it is the
|
||||
/// user's alone as soon as it exists, with nothing written to it yet; one created with contents
|
||||
/// holds them, and an existing file is refused and left as it is.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_private_file_is_private_from_the_start() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-private-file-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
|
||||
let me = current_user_sid().unwrap();
|
||||
let empty = dir.join("empty.token");
|
||||
create_private_file(&empty, &user(), b"").unwrap();
|
||||
let sddl = sddl_of(&empty).unwrap();
|
||||
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
|
||||
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
|
||||
assert_eq!(std::fs::read(&empty).unwrap(), b"");
|
||||
let file = dir.join("ctl.token");
|
||||
create_private_file(&file, &user(), b"secret\n").unwrap();
|
||||
let sddl = sddl_of(&file).unwrap();
|
||||
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), b"secret\n");
|
||||
let again = create_private_file(&file, &user(), b"other\n").unwrap_err();
|
||||
assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), b"secret\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A command that writes `ready` to its standard output and then reads its standard input until
|
||||
/// it closes.
|
||||
fn waiting_reader() -> std::process::Command {
|
||||
#[cfg(windows)]
|
||||
let command = {
|
||||
let mut powershell = system_tool(POWERSHELL);
|
||||
powershell.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
"[Console]::Out.Write('ready'); [Console]::Out.Flush(); $null = [Console]::In.ReadToEnd()",
|
||||
]);
|
||||
powershell
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let command = {
|
||||
let mut sh = std::process::Command::new("sh");
|
||||
sh.args(["-c", "printf ready; cat >/dev/null"]);
|
||||
sh
|
||||
};
|
||||
command
|
||||
}
|
||||
|
||||
/// A tool still running when the time is up is ended and exits. The time is up once the tool
|
||||
/// has said it is waiting (a handshake, not a clock).
|
||||
/// The same tool, given its input, exits by itself and nothing ends it.
|
||||
#[test]
|
||||
fn a_tool_that_does_not_finish_in_time_is_ended() {
|
||||
let (keep, kept) = std::sync::mpsc::channel();
|
||||
// The standard input stays open, so the tool waits until it is ended.
|
||||
let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other);
|
||||
match run_until(waiting_reader(), hold, |out| out == b"ready").unwrap() {
|
||||
Ran::Ended { exited } => assert!(exited, "the tool was ended but is still running"),
|
||||
Ran::Exited(out, _) => panic!("the tool exited by itself: {out:?}"),
|
||||
}
|
||||
drop(kept);
|
||||
let close = |stdin: std::process::ChildStdin| {
|
||||
drop(stdin);
|
||||
Ok(())
|
||||
};
|
||||
match run_until(waiting_reader(), close, |_| false).unwrap() {
|
||||
Ran::Exited(out, sent) => {
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert_eq!(out.stdout, b"ready");
|
||||
sent.unwrap();
|
||||
}
|
||||
Ran::Ended { .. } => panic!("the tool was ended"),
|
||||
}
|
||||
}
|
||||
|
||||
/// PowerShell that has created the file but not written it when the time is up is ended, the
|
||||
/// call fails as timed out, and the file it created is removed; nothing took the name. A file
|
||||
/// that was at the name before is another's, and it is left as it is whenever the time runs out.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_private_file_whose_create_does_not_finish_in_time_is_removed() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-owner-only-limit-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("ctl.token");
|
||||
let entries = || std::fs::read_dir(&dir).unwrap().count();
|
||||
let (keep, kept) = std::sync::mpsc::channel();
|
||||
let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other);
|
||||
// The time is up once the script has created its file and waits for the contents.
|
||||
let late = create_private_file_until(&file, &user(), hold, |_| entries() > 0).unwrap_err();
|
||||
drop(kept);
|
||||
assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "{late}");
|
||||
assert_eq!(entries(), 0, "the file PowerShell created is removed");
|
||||
std::fs::write(&file, b"other\n").unwrap();
|
||||
let (keep, kept) = std::sync::mpsc::channel();
|
||||
let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other);
|
||||
let refused = create_private_file_until(&file, &user(), hold, |_| true).unwrap_err();
|
||||
drop(kept);
|
||||
assert!(matches!(refused.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::AlreadyExists), "{refused}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), b"other\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A folder may give its user Modify but not Full control, so a file created there doesn't let
|
||||
/// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list,
|
||||
/// though, and the user's Full control on it then allows setting the owner.
|
||||
|
||||
@@ -31,5 +31,10 @@ keyring = "4.2"
|
||||
# machine-local persistence. `keyring` installs the platform store; this reads it.
|
||||
keyring-core = "1"
|
||||
|
||||
# The account list is created with an access list of its user and SYSTEM only
|
||||
# (`owner_only::create_private_file`).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-platform = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -263,7 +263,10 @@ pub fn read(path: &Path) -> Result<Accounts, Error> {
|
||||
/// [`Error::Malformed`] forever. Every mutation here reads the file first. There would be
|
||||
/// nothing left to repair it with.
|
||||
///
|
||||
/// Readable by this user alone where the platform has file modes. The file holds no token. It does
|
||||
/// Readable by this user alone: mode `0600` on Unix, and on Windows an access list of this user and
|
||||
/// SYSTEM only from the moment the file exists, whatever folder a portable install or
|
||||
/// [`crate::paths::ENV_VAR`] chose. On Windows the access list is protected, so a change to the
|
||||
/// folder's list does not reach the file. The file holds no token. It does
|
||||
/// say who is signed in. That is nobody else's business.
|
||||
///
|
||||
/// Refuses a list that would serialize past `MAX_BYTES`, before any file is touched. [`read`]
|
||||
@@ -282,14 +285,17 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("couldn't create {} ({e})", dir.display())))?;
|
||||
use std::io::Write;
|
||||
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let pid = std::process::id();
|
||||
let tmp = dir.join(format!(".{}.{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"), stamp, pid));
|
||||
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts");
|
||||
let tmp_name = format!(".{file_name}.{stamp}.{pid}.tmp");
|
||||
#[cfg(not(windows))]
|
||||
let tmp = dir.join(&tmp_name);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
@@ -300,14 +306,16 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
|
||||
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
|
||||
file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
#[cfg(windows)]
|
||||
let tmp = private_copy(path, dir, &tmp_name, &json)?;
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
let mut file =
|
||||
OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?;
|
||||
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
|
||||
file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?;
|
||||
restrict(&tmp)?;
|
||||
}
|
||||
std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("couldn't replace {} ({e})", path.display())))?;
|
||||
// The flush above persisted the file's bytes. The rename changed a directory entry, and that
|
||||
@@ -324,19 +332,147 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn restrict(_path: &Path) -> Result<(), Error> {
|
||||
// A no-op today. That is a real gap this comment used to paper over. A new file in the
|
||||
// platform configuration folder (the default `paths::Rule::Platform` home) inherits that
|
||||
// folder's own, profile-scoped access rules. The account list is this user's alone there.
|
||||
// `paths::Rule::Portable` and `paths::Rule::EnvVar` point `write` at whatever folder the
|
||||
// caller named. A new file there inherits that folder's own Windows access control list,
|
||||
// whatever it is. A shared or loosely permissioned folder in either of those two cases
|
||||
// leaves the account list (subjects, display names, emails, never a token) readable by
|
||||
// anyone else with access to it. Narrowing that needs a per-user Windows DACL on the file,
|
||||
// set through the Win32 authorization API. Every binding for that API is an `unsafe fn`.
|
||||
// This workspace forbids `unsafe_code` outright. Closing this for real needs either a
|
||||
// maintainer-approved exception for one call site or a vetted dependency that wraps that API
|
||||
// safely. Both are decisions for a dedicated PR. See `paths::Rule`.
|
||||
Ok(())
|
||||
/// Write `json` to a new file beside the list at `path`, in its folder `dir`, that only this user
|
||||
/// and SYSTEM can open, and return its path for [`write`] to rename into place.
|
||||
///
|
||||
/// A new file on Windows takes its folder's access list, and a portable install or
|
||||
/// [`crate::paths::ENV_VAR`] can name a folder that lets every local user read what is created in
|
||||
/// it. Every copy is created by `owner_only::create_private_file`, which gives the file a protected
|
||||
/// access list of this user and SYSTEM only in the call that creates it. The rename keeps that
|
||||
/// list, and a later change to the folder's list does not reach it. That call runs PowerShell, so
|
||||
/// [`prepare`] creates an empty copy before the accounts lock is taken, and this function writes
|
||||
/// the list into it. Without a copy this thread prepared (a direct call, or a failed preparation),
|
||||
/// the copy is created here, named `tmp_name`.
|
||||
#[cfg(windows)]
|
||||
fn private_copy(path: &Path, dir: &Path, tmp_name: &str, json: &[u8]) -> Result<std::path::PathBuf, Error> {
|
||||
use std::io::Write;
|
||||
if let Some((copy, mut file)) = take_prepared(path) {
|
||||
match file.write_all(json).and_then(|()| file.sync_all()) {
|
||||
Ok(()) => return Ok(copy),
|
||||
Err(e) => {
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(©);
|
||||
log::warn!("couldn't write a prepared copy of the account list ({e}); a new one is created");
|
||||
}
|
||||
}
|
||||
}
|
||||
let tmp = dir.join(tmp_name);
|
||||
user_sid()
|
||||
.and_then(|me| craft_platform::owner_only::create_private_file(&tmp, &me, json))
|
||||
.map_err(|e| Error::Io(format!("couldn't create {} for its owner only ({e})", tmp.display())))?;
|
||||
Ok(tmp)
|
||||
}
|
||||
|
||||
/// Copies made by [`prepare`] that wait for [`private_copy`]: the thread that made the copy, the
|
||||
/// list it is for, the copy, and the copy held open without delete sharing.
|
||||
#[cfg(windows)]
|
||||
type Prepared = Vec<(std::thread::ThreadId, std::path::PathBuf, std::path::PathBuf, std::fs::File)>;
|
||||
|
||||
/// The copy one [`prepare`] call made. Dropping it closes and removes the copy if no write took it.
|
||||
#[cfg(windows)]
|
||||
pub(crate) struct PreparedCopy(Option<std::path::PathBuf>);
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Drop for PreparedCopy {
|
||||
fn drop(&mut self) {
|
||||
let Some(copy) = self.0.take() else { return };
|
||||
let mut waiting = prepared();
|
||||
let Some(at) = waiting.iter().position(|(_, _, waiting, _)| *waiting == copy) else { return };
|
||||
let (_, _, copy, file) = waiting.swap_remove(at);
|
||||
drop(waiting);
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(©);
|
||||
}
|
||||
}
|
||||
|
||||
/// The copies waiting for [`private_copy`].
|
||||
#[cfg(windows)]
|
||||
fn prepared() -> std::sync::MutexGuard<'static, Prepared> {
|
||||
static PREPARED: std::sync::Mutex<Prepared> = std::sync::Mutex::new(Vec::new());
|
||||
PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The copy of the list at `path` that this thread prepared, with its open handle, removed from the
|
||||
/// waiting list. A copy another thread prepared is left for that thread's write.
|
||||
#[cfg(windows)]
|
||||
fn take_prepared(path: &Path) -> Option<(std::path::PathBuf, std::fs::File)> {
|
||||
let me = std::thread::current().id();
|
||||
let mut prepared = prepared();
|
||||
let at = prepared.iter().position(|(thread, list, ..)| *thread == me && list == path)?;
|
||||
let (_, _, copy, file) = prepared.swap_remove(at);
|
||||
Some((copy, file))
|
||||
}
|
||||
|
||||
/// This user's SID, read once per process (`whoami` is a process start).
|
||||
#[cfg(windows)]
|
||||
fn user_sid() -> std::io::Result<String> {
|
||||
static SID: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
if let Some(sid) = SID.get() {
|
||||
return Ok(sid.clone());
|
||||
}
|
||||
let sid = craft_platform::owner_only::current_user_sid()?;
|
||||
Ok(SID.get_or_init(|| sid).clone())
|
||||
}
|
||||
|
||||
/// Before the accounts lock is taken, create an empty copy of the list at `path` for its owner only
|
||||
/// and keep it open for [`private_copy`], so that the PowerShell run it needs doesn't hold the lock
|
||||
/// other processes wait on. The caller keeps the returned [`PreparedCopy`] until its change under
|
||||
/// the lock is done; a change that writes nothing then has its copy removed. A failure here is left
|
||||
/// for [`write`] to handle.
|
||||
///
|
||||
/// The copy is opened without delete sharing and then checked, so no other account can remove,
|
||||
/// rename or replace it between the check and the write. A copy that fails the check is removed.
|
||||
/// Empty copies beside the list that are at least a minute old, which ended processes left, are
|
||||
/// removed first; a copy that a running process holds open can't be, since removing it needs
|
||||
/// delete sharing.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn prepare(path: &Path) -> PreparedCopy {
|
||||
use std::os::windows::fs::OpenOptionsExt as _;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_platform::owner_only;
|
||||
/// `FILE_SHARE_READ | FILE_SHARE_WRITE`: no `FILE_SHARE_DELETE`.
|
||||
const SHARE_NO_DELETE: u32 = 0x1 | 0x2;
|
||||
/// How old an empty copy that no process holds must be before it is removed. Another process
|
||||
/// that is preparing its copy has it closed for a moment, between its creation and the open.
|
||||
const LEFT_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return PreparedCopy(None) };
|
||||
let Ok(me) = user_sid() else { return PreparedCopy(None) };
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let left = entry.file_name();
|
||||
let left = left.to_string_lossy();
|
||||
if left.starts_with(&format!(".{name}."))
|
||||
&& left.ends_with(".prepared.tmp")
|
||||
&& entry.metadata().is_ok_and(|meta| {
|
||||
meta.is_file() && meta.len() == 0 && meta.modified().ok().and_then(|at| at.elapsed().ok()).is_some_and(|age| age >= LEFT_AFTER)
|
||||
})
|
||||
{
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
let copy = dir.join(format!(".{name}.{}.{}.prepared.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
|
||||
if let Err(e) = owner_only::create_private_file(©, &me, b"") {
|
||||
log::warn!("couldn't prepare a copy of the account list for its owner only ({e})");
|
||||
return PreparedCopy(None);
|
||||
}
|
||||
let checked = std::fs::OpenOptions::new().write(true).share_mode(SHARE_NO_DELETE).open(©).and_then(|file| {
|
||||
match owner_only::foreign_access(&owner_only::sddl_of(©)?, &me) {
|
||||
None => Ok(file),
|
||||
Some(problem) => Err(std::io::Error::other(problem)),
|
||||
}
|
||||
});
|
||||
match checked {
|
||||
Ok(file) => {
|
||||
prepared().push((std::thread::current().id(), path.to_path_buf(), copy.clone(), file));
|
||||
PreparedCopy(Some(copy))
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(©);
|
||||
log::warn!("a prepared copy of the account list is not this user's alone ({e}); it was removed");
|
||||
PreparedCopy(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,8 @@ fn open_lock_file(path: &Path) -> io::Result<File> {
|
||||
/// [`Error::Io`]; `f` may return any [`Error`].
|
||||
pub(crate) fn with_lock<T>(path: &Path, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
|
||||
let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?;
|
||||
#[cfg(windows)]
|
||||
let _prepared = crate::accounts::prepare(path);
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match lock.try_lock() {
|
||||
|
||||
@@ -521,6 +521,159 @@ fn write_leaves_a_previously_good_file_untouched_when_the_new_one_is_too_large()
|
||||
assert_eq!(accounts::read(&path).unwrap(), good, "the earlier, readable file must still be exactly what was there before");
|
||||
}
|
||||
|
||||
/// A portable install or `ARTCRAFT_SUITE_DIR` can put the list in a folder that lets every local
|
||||
/// user read the files created in it, as a new folder at a drive root does. The list written there
|
||||
/// has an access list of its user and SYSTEM only.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_list_in_a_folder_users_can_read_is_still_this_users_alone() {
|
||||
use craft_platform::owner_only;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stderr));
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let list =
|
||||
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
|
||||
|
||||
accounts::write(&path, &list).unwrap();
|
||||
|
||||
let me = owner_only::current_user_sid().unwrap();
|
||||
let sddl = owner_only::sddl_of(&path).unwrap();
|
||||
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}");
|
||||
assert_eq!(accounts::read(&path).unwrap(), list);
|
||||
// A second write, through a copy prepared before the lock as a `Store` does, leaves no copy behind.
|
||||
let _copy = accounts::prepare(&path);
|
||||
accounts::write(&path, &list).unwrap();
|
||||
assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None);
|
||||
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(names, [std::ffi::OsString::from(paths::FILE)], "no temporary file is left behind");
|
||||
}
|
||||
|
||||
/// The list's access list is protected: a change to its folder's access list, which Windows hands
|
||||
/// down to the files in the folder that inherit from it, does not reach the list, whether the list
|
||||
/// was written directly or through a `Store`.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_change_to_the_folders_access_list_does_not_reach_the_list() {
|
||||
use craft_platform::owner_only;
|
||||
let me = owner_only::current_user_sid().unwrap();
|
||||
for through_store in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
if through_store {
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
} else {
|
||||
let list = accounts::Accounts {
|
||||
format: accounts::FORMAT,
|
||||
accounts: vec![account_at("a", 0)],
|
||||
active: Some("a".to_owned()),
|
||||
tombstones: Vec::new(),
|
||||
};
|
||||
accounts::write(&path, &list).unwrap();
|
||||
}
|
||||
|
||||
let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout));
|
||||
|
||||
let sddl = owner_only::sddl_of(&path).unwrap();
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &me), None, "through a Store: {through_store}; {sddl}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A prepared copy that no write took is closed and removed when its change under the lock is
|
||||
/// done, as for a discard of an account that is not in the list.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_prepared_copy_no_write_took_is_removed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let copy = accounts::prepare(&path);
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the copy is made");
|
||||
drop(copy);
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "the copy is removed");
|
||||
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let names = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::<Vec<_>>();
|
||||
let before = names();
|
||||
let _ = store.discard("no such account");
|
||||
assert_eq!(names(), before, "a change that writes nothing leaves no copy behind");
|
||||
}
|
||||
|
||||
/// A write uses the copy its own thread prepared and leaves another thread's copy for that
|
||||
/// thread, which would otherwise have to create one while it holds the accounts lock.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_write_takes_only_the_copy_its_thread_prepared() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let list =
|
||||
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
|
||||
let copies = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().path()).filter(|p| p != &path).collect::<Vec<_>>();
|
||||
let prepared = std::sync::Barrier::new(2);
|
||||
// The other thread keeps its copy until `done` is dropped, which a failed assertion does too.
|
||||
let (done, wait) = std::sync::mpsc::channel::<()>();
|
||||
std::thread::scope(|scope| {
|
||||
let (list_path, prepared) = (&path, &prepared);
|
||||
scope.spawn(move || {
|
||||
let _other = accounts::prepare(list_path);
|
||||
prepared.wait();
|
||||
let _ = wait.recv();
|
||||
});
|
||||
prepared.wait();
|
||||
let other = copies();
|
||||
assert_eq!(other.len(), 1, "{other:?}");
|
||||
let _mine = accounts::prepare(&path);
|
||||
accounts::write(&path, &list).unwrap();
|
||||
assert_eq!(copies(), other, "the other thread's copy is still waiting");
|
||||
drop(done);
|
||||
});
|
||||
assert_eq!(copies(), Vec::<std::path::PathBuf>::new());
|
||||
}
|
||||
|
||||
/// A prepared copy is created with an access list of its user and SYSTEM only, and can't be
|
||||
/// removed, renamed or replaced, nor its folder renamed, between its check and the write. An empty
|
||||
/// copy that an ended process left a minute or more ago is removed by the next preparation; a
|
||||
/// newer one, which another process may be about to open, is kept.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_prepared_copy_is_private_and_cannot_be_swapped_before_the_write() {
|
||||
use craft_platform::owner_only;
|
||||
let me = owner_only::current_user_sid().unwrap();
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let dir = root.path().join("suite");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let granted = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout));
|
||||
let path = dir.join(paths::FILE);
|
||||
let left = dir.join(format!(".{}.1.0.prepared.tmp", paths::FILE));
|
||||
std::fs::File::create(&left).unwrap().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(120)).unwrap();
|
||||
let fresh = dir.join(format!(".{}.2.0.prepared.tmp", paths::FILE));
|
||||
std::fs::write(&fresh, b"").unwrap();
|
||||
|
||||
let _copy = accounts::prepare(&path);
|
||||
|
||||
assert!(!left.exists(), "an old empty copy that no process holds is removed");
|
||||
assert!(fresh.exists(), "a new empty copy, which another process may be about to open, is kept");
|
||||
let copies: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != fresh).collect();
|
||||
assert_eq!(copies.len(), 1, "{copies:?}");
|
||||
let copy = &copies[0];
|
||||
let sddl = owner_only::sddl_of(copy).unwrap();
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}");
|
||||
assert!(std::fs::remove_file(copy).is_err(), "the checked copy must stay in place");
|
||||
assert!(std::fs::rename(copy, dir.join("moved")).is_err(), "the checked copy must not be renamed away");
|
||||
assert!(std::fs::rename(&dir, root.path().join("moved")).is_err(), "its folder must not be renamed away");
|
||||
|
||||
let list =
|
||||
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
|
||||
accounts::write(&path, &list).unwrap();
|
||||
assert!(!copy.exists(), "the write used the prepared copy");
|
||||
assert_eq!(accounts::read(&path).unwrap(), list);
|
||||
assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_in_with_an_oversized_display_name_fails_without_bricking_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
//! The Find and Replace dialog's protocol: fields set by automation are what the next request carries.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_text::find::FindOptions;
|
||||
use craft_text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Outcome as _, Role, Show as _};
|
||||
use craft_ui::dialog::{DialogStack, StackDialog as _};
|
||||
use craft_ui::runtime::env::RootEnv;
|
||||
use craft_ui::runtime::focus::{FocusTarget, request};
|
||||
use craft_ui::testing::access::{focused_key, name};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
use serde_json::json;
|
||||
|
||||
/// Presses the button named `name`.
|
||||
@@ -62,3 +67,45 @@ fn find_fields_set_by_automation_reach_the_next_request() {
|
||||
assert_eq!(fields["message"], json!("nothing found"));
|
||||
assert_eq!(fields["backwards"], json!(true));
|
||||
}
|
||||
|
||||
// Escape in Find what closes the dialog and puts the focus back on the control that opened it, also where Escape
|
||||
// otherwise takes a field's focus (`escape_leaves_fields`). Typing in the field is reverted by the first Escape, which
|
||||
// keeps the focus in the field, and the next Escape closes the dialog.
|
||||
#[trial]
|
||||
fn escape_in_find_what_closes_the_dialog_and_returns_the_focus() {
|
||||
for leaves in [false, true] {
|
||||
for typed in [false, true] {
|
||||
let open = Rc::new(Cell::new(false));
|
||||
let opener = Rc::new(Cell::new(None));
|
||||
let (shown, seen) = (Rc::clone(&open), Rc::clone(&opener));
|
||||
let dialog = RefCell::new(FindReplaceDialog::new("craft", FindTab::Find));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let button = Button::new("Find").show(ui);
|
||||
seen.set(Some(button.response().id));
|
||||
if shown.get() && dialog.borrow_mut().show(ui, &DialogStack::default()).is_some() {
|
||||
shown.set(false);
|
||||
}
|
||||
});
|
||||
let mut root = RootEnv::new();
|
||||
root.escape_leaves_fields = leaves;
|
||||
fixture.root(root).settle();
|
||||
request(fixture.ctx(), FocusTarget::Id(opener.get().expect("the opener is shown")));
|
||||
fixture.settle();
|
||||
assert_eq!(fixture.focused(), opener.get(), "the opener has the focus");
|
||||
open.set(true);
|
||||
fixture.settle();
|
||||
let focused_name = |fixture: &Fixture| name(fixture.tree(), focused_key(fixture.tree())).map(str::to_owned);
|
||||
assert_eq!(focused_name(&fixture).as_deref(), Some("Find what:"), "the dialog opens with the focus in Find what");
|
||||
let in_field = fixture.focused();
|
||||
if typed {
|
||||
fixture.type_text("teh").settle();
|
||||
fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
assert!(open.get(), "leaves {leaves}: the first Escape reverts the typing and keeps the dialog open");
|
||||
assert_eq!(fixture.focused(), in_field, "leaves {leaves}: the focus stays in Find what");
|
||||
}
|
||||
fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
assert!(!open.get(), "leaves {leaves}, typed {typed}: Escape closes the dialog");
|
||||
assert_eq!(fixture.focused(), opener.get(), "leaves {leaves}, typed {typed}: the focus goes back to the opener");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,6 +245,7 @@ fn slot(s: FontSlot) -> &'static str {
|
||||
FontSlot::Ui => "ui",
|
||||
FontSlot::UiSemibold => "ui_semibold",
|
||||
FontSlot::Mono => "mono",
|
||||
FontSlot::UiCondensed => "ui_condensed",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,9 @@ pub const SIZES_SCHEMA: &str = "craft-design-sizes";
|
||||
/// The size set file format this crate reads and writes.
|
||||
pub const SIZES_SCHEMA_VERSION: u64 = 1;
|
||||
|
||||
const FONT: &str = "\"ui\", \"ui_semibold\" or \"mono\"";
|
||||
const FONTS: [(&str, FontSlot); 3] = [("ui", FontSlot::Ui), ("ui_semibold", FontSlot::UiSemibold), ("mono", FontSlot::Mono)];
|
||||
const FONT: &str = "\"ui\", \"ui_semibold\", \"mono\" or \"ui_condensed\"";
|
||||
const FONTS: [(&str, FontSlot); 4] =
|
||||
[("ui", FontSlot::Ui), ("ui_semibold", FontSlot::UiSemibold), ("mono", FontSlot::Mono), ("ui_condensed", FontSlot::UiCondensed)];
|
||||
const TOP_ORDER: [&str; 5] = ["schema", "schema_version", "id", "name", "base"];
|
||||
|
||||
/// A parsed size set file: the set and the JSON it came from, so that [`write_sizes`] keeps
|
||||
|
||||
@@ -12,6 +12,8 @@ pub enum FontSlot {
|
||||
UiSemibold,
|
||||
/// The monospace face.
|
||||
Mono,
|
||||
/// The condensed semibold face of document tab titles, where the app embeds one; the semibold face otherwise.
|
||||
UiCondensed,
|
||||
}
|
||||
|
||||
/// Size, line height and font of one type role.
|
||||
@@ -48,6 +50,9 @@ pub enum TypeRole {
|
||||
Mono,
|
||||
/// A brand title: the app's name on its start screen.
|
||||
Display,
|
||||
/// Document tab titles in the semibold look: the label's size and line height, in the condensed face
|
||||
/// ([`FontSlot::UiCondensed`]).
|
||||
TabTitle,
|
||||
}
|
||||
|
||||
/// How a type role sets its letters.
|
||||
@@ -106,6 +111,7 @@ impl TypeTokens {
|
||||
TypeRole::BodyLarge => self.body_large,
|
||||
TypeRole::Mono => self.mono,
|
||||
TypeRole::Display => self.display,
|
||||
TypeRole::TabTitle => TypeStyle { font: FontSlot::UiCondensed, ..self.label },
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,8 @@ pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag, easing_view};
|
||||
pub(crate) mod rulers;
|
||||
pub(crate) mod scrollbars;
|
||||
pub use rulers::{
|
||||
INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, RulersOutput, StepLadder, TickRule,
|
||||
CENTIMETRE_LABEL_STEP_MIN, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers,
|
||||
RulersOutput, StepLadder, TickRule,
|
||||
};
|
||||
pub use scrollbars::{CanvasScrollbars, CanvasScrollbarsOutput};
|
||||
|
||||
@@ -259,6 +260,8 @@ pub struct Canvas<'a> {
|
||||
settled: Option<Settled>,
|
||||
/// The Menu key or Shift+F10 reached the focused canvas this pass.
|
||||
context_key: bool,
|
||||
/// The text of the paste the editor part takes this pass, taken in `update` with its inputs.
|
||||
pasted: Option<Arc<str>>,
|
||||
/// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)).
|
||||
ease: Option<Steer>,
|
||||
/// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional
|
||||
@@ -342,6 +345,7 @@ impl<'a> Canvas<'a> {
|
||||
snap: None,
|
||||
settled: None,
|
||||
context_key: false,
|
||||
pasted: None,
|
||||
ease: None,
|
||||
follows_pointer: false,
|
||||
tool_regions: Vec::new(),
|
||||
@@ -839,6 +843,7 @@ impl<'a> Canvas<'a> {
|
||||
navigation: self.navigation,
|
||||
editor_input: self.editor_input.clone(),
|
||||
editor: cx.editor_handle(),
|
||||
pasted: self.pasted.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -912,6 +917,11 @@ pub struct ToolPass {
|
||||
pub editor_input: Arc<[EditorInput]>,
|
||||
/// The editor part of this pass, through which the body reports its editor state; `None` without an editor.
|
||||
pub editor: Option<EditorHandle>,
|
||||
/// The text of the paste the editor part takes this pass (its [`EditorInput::Edit`] of
|
||||
/// [`EditCommand::Paste`](craft_behavior::EditCommand::Paste)), as the platform's paste event carried it: Ctrl+V's,
|
||||
/// or the one a Paste command asks the platform for. The framework takes that event out of egui's input, and the
|
||||
/// platform's read can succeed where the installed clipboard can't be opened. `None` in a pass without one.
|
||||
pub pasted: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
impl ToolPass {
|
||||
@@ -1031,6 +1041,10 @@ impl Component for Canvas<'_> {
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
// Taken once: `Cx::editor_input` empties the pass's inputs, and the body reads them from the `ToolPass`.
|
||||
self.editor_input = cx.editor_input().collect::<Vec<_>>().into();
|
||||
self.pasted = match cx.clipboard().paste() {
|
||||
crate::runtime::pending::Pending::Ready(content) => content.text.clone(),
|
||||
_ => None,
|
||||
};
|
||||
// Left untaken: the canvas's generic context request is recorded as for a secondary click.
|
||||
self.context_key = cx.intents().untaken(&Intent::ContextMenu);
|
||||
// The canvas is no value component: it reads and writes its view's binding itself, as a container does.
|
||||
|
||||
@@ -287,7 +287,8 @@ impl Component for Navigator<'_> {
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: NavigatorStyleKey) -> NavigatorStyle {
|
||||
NavigatorStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, cx.tokens.size.plot.height)),
|
||||
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
|
||||
metrics: Metrics::new().min_size(Vec2::new(0.0, cx.tokens.size.plot.height)),
|
||||
focus: cx.focus_look(),
|
||||
inset: cx.tokens.space.gap.inline,
|
||||
radius: UiTokens::corner(cx.tokens.shape.radius.sm),
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
pub(crate) mod stories;
|
||||
mod ticks;
|
||||
|
||||
pub use ticks::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule};
|
||||
pub use ticks::{CENTIMETRE_LABEL_STEP_MIN, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule};
|
||||
|
||||
use super::words::CanvasWords;
|
||||
use super::{CanvasRulers, CanvasSpace, GuideDrag, RulerText, Snap, context_menu, readout};
|
||||
|
||||
@@ -13,6 +13,12 @@ pub const INCH_EIGHTHS: [u32; 3] = [8, 4, 2];
|
||||
/// The least distance between labelled ticks, in points.
|
||||
pub const LABEL_STEP_MIN: f32 = 60.0;
|
||||
|
||||
/// The least distance between labelled ticks of a centimetre document ruler, in points: a whole centimetre at 100%
|
||||
/// (about 28 points) is labelled, as Word's ruler does.
|
||||
pub const CENTIMETRE_LABEL_STEP_MIN: f32 = 24.0;
|
||||
/// Labelled centimetre steps: 1, 2, 5, 10 times the base.
|
||||
const CENTIMETRE_STEPS: [f64; 9] = [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0];
|
||||
|
||||
/// The metric rule's subdivisions of a labelled step.
|
||||
const METRIC_SUBDIVISIONS: f32 = 10.0;
|
||||
/// Labelled inch steps in inches: 1, 2, 5, 10 times the base.
|
||||
@@ -71,6 +77,9 @@ impl StepLadder {
|
||||
pub enum TickRule<'a> {
|
||||
/// The units' own table ([`RulerUnits::step`]): decimal steps and ten subdivisions, or the host's custom table.
|
||||
Metric,
|
||||
/// Centimetres of a document ruler: a label every centimetre with quarter centimetre ticks, or every 2, 5, 10 and so
|
||||
/// on centimetres with halves when a centimetre is narrower than [`CENTIMETRE_LABEL_STEP_MIN`].
|
||||
Centimetres,
|
||||
/// Inches: a label every inch (every 2, 5, 10 and so on when smaller), subdivided by the first of these counts,
|
||||
/// finest first, that keeps the ticks a tenth of the least label step apart ([`INCH_SIXTEENTHS`],
|
||||
/// [`INCH_EIGHTHS`]).
|
||||
@@ -81,9 +90,14 @@ pub enum TickRule<'a> {
|
||||
}
|
||||
|
||||
impl TickRule<'static> {
|
||||
/// The rule for a ruler counting `kind`: Word's sixteenths for inches, `Metric` otherwise.
|
||||
/// The rule for a document ruler counting `kind`: Word's sixteenths for inches, whole labelled centimetres for
|
||||
/// centimetres, `Metric` otherwise.
|
||||
pub fn of_unit(kind: UnitKind) -> TickRule<'static> {
|
||||
if kind == UnitKind::Inches { TickRule::Inches(&INCH_SIXTEENTHS) } else { TickRule::Metric }
|
||||
match kind {
|
||||
UnitKind::Inches => TickRule::Inches(&INCH_SIXTEENTHS),
|
||||
UnitKind::Centimetres => TickRule::Centimetres,
|
||||
_ => TickRule::Metric,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +126,14 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) {
|
||||
(step, subdivisions)
|
||||
}
|
||||
|
||||
/// The labelled centimetre step and its subdivisions at `points_per_cm` screen points per centimetre.
|
||||
fn centimetre_step(points_per_cm: f64) -> (f64, u32) {
|
||||
let step_min = f64::from(CENTIMETRE_LABEL_STEP_MIN);
|
||||
let step = CENTIMETRE_STEPS.into_iter().find(|step| step * points_per_cm >= step_min).unwrap_or(1000.0);
|
||||
// A whole labelled centimetre is at least 24 points wide, so its quarters are 6 points apart.
|
||||
(step, if step > 1.0 { 2 } else { 4 })
|
||||
}
|
||||
|
||||
/// The ticks of one ruler over `values` (ruler units from the zero point): the one tick rule of every ruler, so a
|
||||
/// text ruler or a page view's ruler shows the same ticks as the canvas's. One labelled step beyond each end is
|
||||
/// included, since a label starts right of its tick. `zoom` is screen points per document unit along the axis, as
|
||||
@@ -119,6 +141,7 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) {
|
||||
pub fn ticks(units: &RulerUnits, rule: TickRule<'_>, zoom: f64, values: RangeInclusive<f64>) -> Vec<RulerTick> {
|
||||
let (step, subdivisions) = match rule {
|
||||
TickRule::Metric => units.step(zoom, LABEL_STEP_MIN),
|
||||
TickRule::Centimetres => centimetre_step(zoom / units.per_doc),
|
||||
TickRule::Inches(finest) => inch_step(zoom / units.per_doc, finest),
|
||||
TickRule::Steps(ladder) => {
|
||||
let (tick, label) = ladder.steps(zoom / units.per_doc);
|
||||
|
||||
@@ -391,7 +391,7 @@ impl<'a> TaskBar<'a> {
|
||||
Some(Mixed::Same(held)) => held,
|
||||
_ => TaskBarPlace::default(),
|
||||
};
|
||||
let rtl = env.direction.is_rtl();
|
||||
let rtl = env.layer_direction().is_rtl();
|
||||
let overlay = match kind {
|
||||
TaskBarKind::Selection => selection_overlay(hung.as_ref(), area, dismiss),
|
||||
TaskBarKind::Task | TaskBarKind::Fixed => layer_overlay(&held, hung.as_ref(), area, movable),
|
||||
|
||||
@@ -93,6 +93,40 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the
|
||||
);
|
||||
}
|
||||
|
||||
/// One pass's editor inputs and pasted text, as the body read them from its `ToolPass`.
|
||||
type PassPaste = (Vec<EditorInput>, Option<String>);
|
||||
|
||||
/// A paste event's text reaches the body with the editor part's paste in that pass's `ToolPass`, and in no later pass:
|
||||
/// the framework takes the event out of egui's input, and the body can't read the installed clipboard where it can't
|
||||
/// be opened.
|
||||
#[trial]
|
||||
fn a_paste_events_text_reaches_the_body_with_the_editors_paste() {
|
||||
let seen: Rc<RefCell<Vec<PassPaste>>> = Rc::default();
|
||||
let shown = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0);
|
||||
let _ = canvas(view).show_at(ui, room, |_, body| {
|
||||
let Some(pass) = tool_pass(&body.env) else { return };
|
||||
shown.borrow_mut().push((pass.editor_input.to_vec(), pass.pasted.as_deref().map(str::to_owned)));
|
||||
});
|
||||
});
|
||||
fixture.room(ROOM);
|
||||
fixture.settle();
|
||||
fixture.click_at((ROOM / 2.0).to_pos2());
|
||||
seen.borrow_mut().clear();
|
||||
fixture.frame(vec![Event::Paste("from the platform".into())]);
|
||||
fixture.frame(vec![]);
|
||||
let passes = seen.take();
|
||||
let pasted: Vec<&PassPaste> = passes.iter().filter(|(_, text)| text.is_some()).collect();
|
||||
assert!(!pasted.is_empty(), "a pass carries the paste's text: {passes:?}");
|
||||
for (inputs, text) in &pasted {
|
||||
assert_eq!(text.as_deref(), Some("from the platform"));
|
||||
assert!(inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))), "with the editor's paste: {inputs:?}");
|
||||
}
|
||||
assert!(passes.last().is_some_and(|(_, text)| text.is_none()), "a later pass carries none: {passes:?}");
|
||||
}
|
||||
|
||||
/// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines,
|
||||
/// so its caret reaches the input method and no empty text is announced on the canvas's node.
|
||||
#[trial]
|
||||
|
||||
@@ -4,8 +4,8 @@ use craft_behavior::geometry::{SnapOptions, SnapTargets};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect};
|
||||
use craft_behavior::{CancelReason, CanvasView, RulerUnits, TickLabels, Ticks};
|
||||
use craft_ui::canvas::{
|
||||
Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap, StepLadder, TickRule,
|
||||
ToolAction, ToolContext, ToolPath, ToolPointer,
|
||||
CENTIMETRE_LABEL_STEP_MIN, Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap,
|
||||
StepLadder, TickRule, ToolAction, ToolContext, ToolPath, ToolPointer,
|
||||
};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::primitives::TickRank;
|
||||
@@ -60,6 +60,24 @@ fn labelled_ticks_never_touch_at_any_zoom() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A document ruler labels every whole centimetre at 100% (28.35 points each), and thins the labels out when zoomed
|
||||
/// out so they never touch.
|
||||
#[trial]
|
||||
fn a_centimetre_document_ruler_labels_each_centimetre_and_thins_out_zoomed_out() {
|
||||
let centimetres = RulerUnits::new(2.54 / 72.0, Ticks::decimal(false));
|
||||
let rule = TickRule::of_unit(UnitKind::Centimetres);
|
||||
let at_full = least_label_gap(¢imetres, rule, 1.0);
|
||||
assert!(at_full < f64::from(LABEL_STEP_MIN), "labels at 100% are closer than the generic metric step: {at_full}");
|
||||
let one_cm = 72.0 / 2.54;
|
||||
assert!((at_full - one_cm).abs() < 1e-6, "labels at 100% are one centimetre apart: {at_full}");
|
||||
let least = f64::from(CENTIMETRE_LABEL_STEP_MIN) - 1e-9;
|
||||
for zoom in ZOOMS {
|
||||
let gap = least_label_gap(¢imetres, rule, zoom);
|
||||
assert!(gap >= least, "centimetre labels at zoom {zoom}: {gap} points apart");
|
||||
}
|
||||
assert!(least_label_gap(¢imetres, rule, 0.25) > at_full, "labels thin out when zoomed out");
|
||||
}
|
||||
|
||||
/// A vertical label stacks its characters one label-role size apart; the longest label the metric rule gives at the
|
||||
/// least step (five characters) and its gap to the tick stay inside that step, so neighbouring labels never touch.
|
||||
#[trial]
|
||||
|
||||
@@ -36,7 +36,7 @@ pub use scroll::{STRIP_BACK, STRIP_FORWARD};
|
||||
pub(crate) use window::MOVE_BAND;
|
||||
use window::WindowMode;
|
||||
pub use window::grip_band;
|
||||
pub(crate) use window::keep_inside;
|
||||
pub use window::keep_inside;
|
||||
|
||||
/// The scroll region's view in the last pass that showed it.
|
||||
#[derive(Clone, Default)]
|
||||
|
||||
@@ -329,6 +329,11 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
/// the room. What the regions took is recorded for the rest of the pass; a record this pass already holds serves
|
||||
/// instead when the room still allows it (`reusable`).
|
||||
fn measured_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Vec2 {
|
||||
// A layer measures under its opener's env and runs in its own, which flows in the layer's direction
|
||||
// (`Scoped::layer_direction`): its measuring run lays out in that direction too.
|
||||
let layer_env = matches!(self.props.mount, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow)
|
||||
.then(|| at.env.derive(|scoped| scoped.direction = scoped.layer_direction()));
|
||||
let at = &Measuring { env: layer_env.as_ref().unwrap_or(at.env), command: at.command.clone(), ..*at };
|
||||
let scrolled_share = match self.measure_room(comp, at, cx) {
|
||||
Ok(scrolled_share) => scrolled_share,
|
||||
Err(extent) => return extent,
|
||||
@@ -640,6 +645,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
self.end_unfit = Some(short);
|
||||
}
|
||||
self.after_body(ui, env, &mut plan);
|
||||
if plan.real {
|
||||
crate::runtime::focus::end_body(&plan.ctx, plan.id);
|
||||
}
|
||||
if plan.real && props.end.is_some() {
|
||||
self.end_step(comp, ui, cx, &mut plan);
|
||||
}
|
||||
@@ -647,6 +655,9 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
// A collapsed body keeps its last full size in layout memory, so opening it again places by that size
|
||||
// and asks for no discard pass.
|
||||
self.body_size = if props.collapse.is_some() { None } else { Some(Vec2::ZERO) };
|
||||
if plan.real {
|
||||
crate::runtime::focus::end_body(&plan.ctx, plan.id);
|
||||
}
|
||||
}
|
||||
self.close_label(&mut plan);
|
||||
// B4 footer: under the control column of a label-scoped container, which starts where the label step put
|
||||
@@ -1294,7 +1305,7 @@ impl BodyHooks<'_> {
|
||||
plan.footer_env = plan.region_env.derive_local(|scoped| scoped.content_column = true);
|
||||
}
|
||||
if plan.real {
|
||||
crate::runtime::focus::begin_body(&plan.ctx);
|
||||
crate::runtime::focus::begin_body(&plan.ctx, plan.id);
|
||||
}
|
||||
// A stack is a content column where its width comes from its content: a content-sized stack in flow, or a
|
||||
// held fill-width container. A stack given its width (a rect it is shown at, or a column's width it passes
|
||||
|
||||
@@ -362,7 +362,8 @@ impl<'b> BodyHooks<'b> {
|
||||
}
|
||||
|
||||
/// The header's line inside its inset, less the slots of the container's own header parts at its two edges: the
|
||||
/// rect the header's children get, and the slots.
|
||||
/// rect the header's children get, and the slots. An end edge that narrows (`HeaderParts::end_narrows`) gives up
|
||||
/// room, down to its least, until the children keep their room.
|
||||
pub(super) fn header_line(&self, header: Rect, inset: f32, parts: HeaderParts, rtl: bool) -> (Rect, HeaderSlots) {
|
||||
let mut flow = craft_behavior::Flow::new(header.shrink2(Vec2::new(inset, 0.0)), rtl);
|
||||
let mut slots = HeaderSlots::default();
|
||||
@@ -371,8 +372,12 @@ impl<'b> BodyHooks<'b> {
|
||||
slots.start = Some(slot);
|
||||
flow = rest.take_start(self.region_gap).1;
|
||||
}
|
||||
if parts.end > 0.0 {
|
||||
let (slot, rest) = flow.take_end(parts.end);
|
||||
let end = match parts.end_least {
|
||||
Some(least) => parts.end.min((flow.rect().width() - self.region_gap - parts.keep).max(least)),
|
||||
None => parts.end,
|
||||
};
|
||||
if end > 0.0 {
|
||||
let (slot, rest) = flow.take_end(end);
|
||||
slots.end = Some(slot);
|
||||
flow = rest.take_end(self.region_gap).1;
|
||||
}
|
||||
|
||||
@@ -199,10 +199,11 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
if let Some(view) = self.view {
|
||||
use crate::contract::Pointer as _;
|
||||
let overlay = scroll_of(props).is_some_and(|scroll| scroll.has_overlay());
|
||||
let overlay = scroll_of(props).is_some_and(|scroll| scroll.overlay_hides_at_rest());
|
||||
for (bar, span) in self.scroll_geometry(props, view, rtl, tokens) {
|
||||
let overflow = span.content.end - span.content.start > span.visible.end - span.visible.start;
|
||||
// An overlay bar shows while the pointer is over the container, or keeps the press that drags it.
|
||||
// An overlay bar shows while the pointer is over the container, or keeps the press that drags it, unless
|
||||
// it shows at rest.
|
||||
let hidden = overlay && !cx.response.contains_pointer() && !cx.part_if_declared(bar.key).is_some_and(|track| track.pressed());
|
||||
if !overflow || hidden {
|
||||
continue;
|
||||
|
||||
@@ -316,7 +316,7 @@ impl<'b> BodyHooks<'b> {
|
||||
// offers it: a body taller than that scrolls instead of covering the anchor.
|
||||
let ctx = ui.ctx();
|
||||
let own = Rect::from_min_max(ui.cursor().min, ui.cursor().min);
|
||||
let rtl = Env::of(ui).direction.is_rtl();
|
||||
let rtl = env.layer_direction().is_rtl();
|
||||
match crate::contract::overlay::measuring_room(
|
||||
ctx,
|
||||
&env,
|
||||
|
||||
@@ -215,7 +215,7 @@ fn resized_edge(before: Rect, after: Rect) -> Option<ResizeEdge> {
|
||||
/// `rect` moved, at its size, the least distance that puts it inside `bounds`: the one keep rule for a layer's
|
||||
/// bounds, whether the user moves the layer or the host places it. On an axis where it is longer than the bounds, its
|
||||
/// low edge sits on theirs.
|
||||
pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect {
|
||||
pub fn keep_inside(rect: Rect, bounds: Rect) -> Rect {
|
||||
let keep = |low: f32, high: f32, bounds_low: f32, bounds_high: f32| low.min(bounds_high - (high - low)).max(bounds_low) - low;
|
||||
rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y)))
|
||||
}
|
||||
@@ -847,7 +847,7 @@ impl BodyHooks<'_> {
|
||||
let handle = grip_band(pcx.tokens);
|
||||
let corner = 2.0 * handle;
|
||||
let top = top_band(props, &ctx, pcx.id, pcx.tokens);
|
||||
let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.direction().is_rtl()));
|
||||
let pinned = overlay_of(props).map_or(Pinned::NONE, |overlay| Pinned::of(overlay, &ctx, pcx.id, pcx.env.text_direction().is_rtl()));
|
||||
let caller_sizes = overlay_of(props).is_some_and(|overlay| overlay.resize.by_caller);
|
||||
let grip_name = props.resize_name.as_ref().map(|name| pcx.env.resolve(name).as_str().to_owned());
|
||||
for (index, (dx, dy, cursor)) in GRIPS.into_iter().enumerate() {
|
||||
|
||||
@@ -280,11 +280,16 @@ pub struct HeaderParts {
|
||||
pub start: f32,
|
||||
/// The width at the end edge.
|
||||
pub end: f32,
|
||||
/// The least the end edge narrows to, when the line is too narrow for the header's children to keep `keep`
|
||||
/// beside the end parts' whole width. `None`: the end edge keeps its width.
|
||||
pub end_least: Option<f32>,
|
||||
/// The room the header's children keep before the end edge narrows below `end` (to `end_least`).
|
||||
pub keep: f32,
|
||||
}
|
||||
|
||||
impl HeaderParts {
|
||||
/// No room for parts.
|
||||
pub const NONE: HeaderParts = HeaderParts { start: 0.0, end: 0.0 };
|
||||
pub const NONE: HeaderParts = HeaderParts { start: 0.0, end: 0.0, end_least: None, keep: 0.0 };
|
||||
|
||||
/// `width` at the start edge.
|
||||
pub const fn start(mut self, width: f32) -> Self {
|
||||
@@ -297,6 +302,14 @@ impl HeaderParts {
|
||||
self.end = width;
|
||||
self
|
||||
}
|
||||
|
||||
/// The end edge narrows, down to `least`, so the header's children keep `keep` of the line: on a line too narrow
|
||||
/// for both, the children's least room comes before the end parts' whole width.
|
||||
pub const fn end_narrows(mut self, least: f32, keep: f32) -> Self {
|
||||
self.end_least = Some(least);
|
||||
self.keep = keep;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// An edge of a header's line, where a container's own header parts sit.
|
||||
@@ -653,7 +666,8 @@ pub enum ScrollIndicator {
|
||||
Strips,
|
||||
/// A bar that takes no room from the content, as a tool rail or an options bar shows its overflow: it lies in the
|
||||
/// container's end padding (its bottom padding for x), over the content where the container has none, and shows
|
||||
/// only while the pointer is over the container or presses the bar.
|
||||
/// only while the pointer is over the container or presses the bar, or while the content overflows when the scroll
|
||||
/// shows it at rest ([`Scroll::at_rest`]).
|
||||
Overlay,
|
||||
}
|
||||
|
||||
@@ -669,11 +683,13 @@ pub struct Scroll {
|
||||
pub notch: Notch,
|
||||
/// How the overflow shows.
|
||||
pub indicator: ScrollIndicator,
|
||||
/// Whether an overlay bar also shows while the pointer is away from the container.
|
||||
pub at_rest: bool,
|
||||
}
|
||||
|
||||
impl Scroll {
|
||||
const fn on(axes: ScrollAxes) -> Scroll {
|
||||
Scroll { axes, anchor: ScrollAnchor::Start, notch: Notch::Lines(3.0), indicator: ScrollIndicator::Bar }
|
||||
Scroll { axes, anchor: ScrollAnchor::Start, notch: Notch::Lines(3.0), indicator: ScrollIndicator::Bar, at_rest: false }
|
||||
}
|
||||
|
||||
/// Shows the overflow along y as scroll strips instead of a bar.
|
||||
@@ -699,6 +715,18 @@ impl Scroll {
|
||||
matches!(self.indicator, ScrollIndicator::Overlay)
|
||||
}
|
||||
|
||||
/// Shows an overlay bar whenever the content overflows, also while the pointer is away from the container. A bar of
|
||||
/// another indicator already shows at rest.
|
||||
pub const fn at_rest(mut self) -> Scroll {
|
||||
self.at_rest = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the overlay bar shows only while the pointer is over the container or presses the bar.
|
||||
pub const fn overlay_hides_at_rest(&self) -> bool {
|
||||
self.has_overlay() && !self.at_rest
|
||||
}
|
||||
|
||||
/// Scrolls along y.
|
||||
pub const fn vertical() -> Scroll {
|
||||
Scroll::on(ScrollAxes::Vertical)
|
||||
|
||||
@@ -84,13 +84,14 @@ impl<C: Component> MeasureCx<'_, C> {
|
||||
}
|
||||
|
||||
/// The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes
|
||||
/// the room it is offered, down to `least` and up to `most`. At its least, where the width is unbounded, and in a
|
||||
/// measuring run of a column that sizes its width from its content (which offers no room), it is `least`: a
|
||||
/// picture needs no width of its own, so it never sets that column's width, and the real run shows it across the
|
||||
/// width the column settles on.
|
||||
/// the room it is offered, up to `most`. At its least, where the width is unbounded, and in a measuring run of a
|
||||
/// column that sizes its width from its content (which offers no room), it is `least`: a picture needs no width of
|
||||
/// its own, so it never sets that column's width, and the real run shows it across the width the column settles
|
||||
/// on. Offered less room than `least` (a panel at its narrowest width), it takes that room, down to the plot's
|
||||
/// least height (`size.plot.height`, or `least` when that is smaller), so it stays inside its container.
|
||||
pub fn picture_width(&self, least: f32, most: f32) -> f32 {
|
||||
match self.room.filter(|_| self.proposal != Proposal::Min) {
|
||||
Some(room) => room.clamp(least, most.max(least)),
|
||||
Some(room) => room.clamp(least.min(self.tokens.size.plot.height), most.max(least)),
|
||||
None => least,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +273,9 @@ impl PartBuilder<'_> {
|
||||
/// the popup, so press, drag and release over a row picks it, and a click leaves it open (`on_click` acts on the
|
||||
/// release instead), AccessKit Expand and Collapse on its sub-node open and close it, Alt+Down from the part (or from
|
||||
/// the component when no toggling part is focused) opens the first toggled popup that is closed and Alt+Up closes
|
||||
/// the open ones, and the sub-node reports `expanded`. The component declares the sub-node with `Access::node`.
|
||||
/// the open ones, and the sub-node reports `expanded`. The component declares the sub-node with `Access::node`; a
|
||||
/// component's one toggling part with no sub-node (a corner mark) leaves `expanded`, Expand and Collapse to the
|
||||
/// component's own node.
|
||||
pub fn toggles(self, popup: &'static str) -> Self {
|
||||
self.toggles_at(popup, 0)
|
||||
}
|
||||
|
||||
@@ -110,6 +110,9 @@ fn paint_pointer(ctx: &Context, env: &Env, painter: &egui::Painter) {
|
||||
let closed = pointer::frame_raw(ctx).buttons.contains(craft_behavior::Buttons::PRIMARY);
|
||||
let tip = matches!(cursor, PaintedCursor::Circle { .. } | PaintedCursor::Outline { .. });
|
||||
let whole = pointer_art(env, &cursor, closed, false);
|
||||
// A brush tip is canvas geometry at the canvas's zoom; any other pointer takes the interface zoom only where it
|
||||
// follows it.
|
||||
let whole = if tip { whole } else { whole.scaled(cursor::art_scale(ctx)) };
|
||||
let confined = cursor::current_region(ctx).filter(|region| tip && !shows_whole(ctx, region, &whole, at));
|
||||
let ring = |painter: &egui::Painter| {
|
||||
let art = pointer_art(env, &cursor.clone().marked(false, None), closed, false);
|
||||
|
||||
@@ -401,6 +401,7 @@ impl<C: Collection> ShapeHooks<C> for ItemsHooks<'_, '_, C> {
|
||||
focus::registration::record_tree(&ctx, id, tree);
|
||||
let focused = focus::is_focused(&ctx, id);
|
||||
let lead = self.lead.key.clone();
|
||||
focus::registration::record_lead(&ctx, id, lead.as_ref().is_some_and(|key| self.index_of(key).is_some()));
|
||||
let mut lead_child = None;
|
||||
let striped = comp.items().striped;
|
||||
let mut stripe: Option<(usize, usize)> = None;
|
||||
|
||||
Loaded 100 of 269 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user