Merge branch 'main' into fix/cmyk-vector-shape-paint

This commit is contained in:
aiongg authored and GitHub committed 2026-11-24 22:30:12 -05:00
commit a39646d494
86 files changed
+2421 -498

No files matched your search

Generated
+198 -160
View File
File diff suppressed because it is too large. Load diff
+53 -53
View File
@@ -12,21 +12,21 @@ rust-version = "1.95"
[workspace.dependencies]
# The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match
# `craft::egui_fork::REV` (checked by `cargo xtask ci`).
craft = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", default-features = false }
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163", default-features = false }
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
photocraft-raster = { path = "crates/raster" }
photocraft-doc = { path = "crates/doc" }
photocraft-ops = { path = "crates/ops" }
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
photocraft-raw = { path = "crates/raw" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
photocraft-compose = { path = "crates/compose" }
photocraft-gpu = { path = "crates/gpu" }
photocraft-paint = { path = "crates/paint" }
@@ -48,36 +48,36 @@ photocraft-ipp = { path = "crates/ipp" }
# external
# ICC colour management: the shared crate (replaces crates/cms; craft-libs#779).
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163", features = ["raster", "write-raster"] }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
# Keep the shared embedded-image validation API until the framework revision includes it.
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163", features = ["tree-render", "tree-render-system-fonts"] }
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
# Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563.
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" }
craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a" }
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
# the commit in `craft-i18n.rev`). Already in the tree through craft.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163", features = ["ui"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
@@ -350,28 +350,28 @@ opt-level = 3
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
krilla = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
emath = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "a87d00caaec947ea781657c6ff410c9838016d18" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+1 -1
View File
@@ -70,7 +70,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSGraphics", "NSResponder", "NSView", "NSWindow"] }
[target.'cfg(unix)'.dependencies]
rustix = { version = "=1.1.5", features = ["fs"] }
rustix = { version = "=1.1.6", features = ["fs"] }
# Reads CFBundleExecutable from a chosen macOS application bundle's Info.plist (XML or binary) for
# external vector editing. Already in Cargo.lock (craft-update); built on every Unix so Linux CI
# compiles and tests the bundle checks. The event-stream reader (behind plist's "unstable"
+6 -1
View File
@@ -126,7 +126,12 @@ fn a_launch_waiting_on_a_closing_instance_takes_over() {
let primary = primary(&dir);
// The UI never drains (it is shutting down, or never came up).
let waiting = launch(&dir, &["a.psd"], FAST);
std::thread::sleep(Duration::from_millis(200));
// Shut down only once the launch has handed its path over and waits for the UI to take it.
let deadline = Instant::now() + Duration::from_secs(10);
while primary.shared.inbox.lock().unwrap().pending.is_empty() {
assert!(Instant::now() < deadline, "the launch never queued its path");
std::thread::sleep(Duration::from_millis(1));
}
primary.shutdown();
assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary");
// After shutdown new connections are refused too.
+202 -11
View File
@@ -1,5 +1,6 @@
//! High-quality separable resampling of surfaces (Image Size).
use photocraft_color::{PixelFormat, SampleType};
use photocraft_geom::{Rect, TILE_SIZE};
use photocraft_raster::Surface;
use serde::{Deserialize, Serialize};
@@ -388,6 +389,7 @@ pub fn resize_surface_with_interrupt(
fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface {
let mut cur: Option<Surface> = None;
let canvas_in = canvas;
let mut canvas = canvas;
for p in plan(filter, sx, sy) {
if ctl.cancelled() {
@@ -397,23 +399,206 @@ fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Op
canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy));
cur = Some(next);
}
let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), filter, sx, sy);
let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), Some((s, canvas_in)), filter, sx, sy);
out.prune();
out
}
/// Preserve Details' light sharpening of an enlargement (Lanczos's output, for the other filters
/// nothing).
fn preserve_details(mut out: Surface, filter: Resample, sx: f64, sy: f64) -> Surface {
if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) {
let dst = out.content_bounds();
let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
let area = crate::output_area(&p, dst, dst, None);
out = crate::apply(&out, &p, area, dst, None);
/// Whether `filter` at `(sx, sy)` ends with Preserve Details' sharpening of an enlargement.
fn sharpens(filter: Resample, sx: f64, sy: f64) -> bool {
filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0)
}
/// Whether Preserve Details' enlargement of `fmt` at `(sx, sy)` is the case #14794 measured
/// against the reference application, an 8-bit image enlarged 2x on both axes, and so gets
/// [`dering`] and the fitted sharpening. The issue keeps every case it didn't measure (other
/// scales, 16 and 32 bits) as it was.
fn derings(fmt: PixelFormat, filter: Resample, sx: f64, sy: f64) -> bool {
sharpens(filter, sx, sy) && fmt.sample == SampleType::U8 && sx == 2.0 && sy == 2.0
}
/// Preserve Details' sharpening of an enlargement (Lanczos's output `out` of `src`, read with
/// `canvas`; for the other filters nothing): an Unsharp Mask that steepens edges. In the measured
/// case (see [`derings`]) every sample is kept within the source pixels around it before and after
/// it, so the edges get no ringing halo (#14794); elsewhere it is the light 30 % mask as before.
/// `src` is only needed in the measured case.
fn preserve_details(mut out: Surface, src: Option<(&Surface, Option<Rect>)>, filter: Resample, sx: f64, sy: f64) -> Surface {
if !sharpens(filter, sx, sy) {
return out;
}
let dering_src = src.filter(|_| derings(out.format(), filter, sx, sy));
if let Some((src, canvas)) = dering_src {
dering(&mut out, src, sx, sy, canvas);
}
let (amount, radius) = match dering_src {
Some(_) => (PD_AMOUNT, (PD_RADIUS * sx.max(sy)) as f32),
None => (30.0, 0.6 * sx.max(sy) as f32),
};
let dst = out.content_bounds();
let p = crate::FilterParams::UnsharpMask { amount, radius, threshold: 0.0 };
let area = crate::output_area(&p, dst, dst, None);
out = crate::apply(&out, &p, area, dst, None);
if let Some((src, canvas)) = dering_src {
dering(&mut out, src, sx, sy, canvas);
}
out
}
/// Preserve Details' Unsharp Mask amount (%) in the measured case and radius (per unit of
/// scale), fitted to the reference application's 2x enlargement of a hard edge (#14794).
pub(crate) const PD_AMOUNT: f32 = 127.0;
pub(crate) const PD_RADIUS: f64 = 0.6;
/// Keeps each sample of `out` (a resize of `src` by `(sx, sy)`) within the range of the two by
/// two source pixels around its source position, channel by channel. Colour channels only count
/// the source pixels that are not fully transparent. Source positions are clamped into the area
/// the resize reads: with `canvas` the content and the canvas, whose edges repeat outwards;
/// without, the content and one pixel around it, since beyond the content the resize reads the
/// default pixel (so an opaque layer's partly transparent fringe stays so).
///
/// Source rows are read one at a time, whatever the scale, and bands of output rows are written
/// a group at a time, like [`resize_pass`], so memory stays bounded.
pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: Option<Rect>) {
let dst = out.content_bounds();
let content = src.content_bounds();
let area = match canvas {
Some(c) => content.union(&c),
None if content.is_empty() => content,
None => content.inflate(1),
};
if dst.is_empty() || area.is_empty() || !(sx > 0.0 && sy > 0.0) {
return;
}
let fmt = out.format();
let n = fmt.channels();
let alpha = fmt.alpha;
// The two source samples around output sample `o`, as indices into `lo..=hi`.
let pair = |o: i32, scale: f64, lo: i32, hi: i32| -> (usize, usize) {
let u = ((o as f64 + 0.5) / scale - 0.5).floor();
let i0 = (u.clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize;
let i1 = ((u + 1.0).clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize;
(i0, i1)
};
let mut xs: Vec<(usize, usize)> = (dst.x0..dst.x1).map(|o| pair(o, sx, area.x0, area.x1 - 1)).collect();
// Only the source columns the output reads (a small layer on a wide canvas reads a few), with
// `xs` rebased to them.
let c0 = xs.iter().map(|&(a, _)| a).min().unwrap_or(0);
let c1 = xs.iter().map(|&(_, b)| b + 1).max().unwrap_or(c0);
for (a, b) in &mut xs {
(*a, *b) = (*a - c0, *b - c0);
}
let sw = (c1 - c0) * n;
let x0 = area.x0.saturating_add(i32::try_from(c0).unwrap_or(i32::MAX));
let x1 = area.x0.saturating_add(i32::try_from(c1).unwrap_or(i32::MAX));
// Source row `k` of the area (as `pair` indexes it), columns `c0..c1`, into `buf`.
let read_row = |k: usize, buf: &mut Vec<f32>| {
let y = area.y0.saturating_add(i32::try_from(k).unwrap_or(i32::MAX));
let r = Rect::new(x0, y, x1, y.saturating_add(1));
#[cfg(test)]
DERING_MAX_READ_ROWS.fetch_max(r.height() as usize, std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
DERING_READ_COLUMNS.with(|c| c.set(c.get().max(r.width() as usize)));
src.read_region_into(r, buf);
};
let band = |out: &Surface, b: usize| -> (Rect, Vec<f32>) {
let y0 = dst.y0.saturating_add(i32::try_from(b * BAND).unwrap_or(i32::MAX)).min(dst.y1);
let r = Rect::new(dst.x0, y0, dst.x1, y0.saturating_add(BAND as i32).min(dst.y1));
let ys: Vec<(usize, usize)> = (r.y0..r.y1).map(|o| pair(o, sy, area.y0, area.y1 - 1)).collect();
let mut data = out.read_region(r);
// The two source rows of the current pair, with their indices: a row shared with the
// previous pair is kept instead of read again.
let (mut ra, mut rb): (SourceRow, SourceRow) = ((None, Vec::new()), (None, Vec::new()));
// The range of each source column over the current pair of rows: colour channels of
// transparent pixels count as nothing (an empty range, `lo > hi`).
let (mut vlo, mut vhi) = (vec![0.0f32; sw], vec![0.0f32; sw]);
let mut rows = None;
for (&(y0, y1), row) in ys.iter().zip(data.chunks_exact_mut(dst.width() as usize * n)) {
if rows != Some((y0, y1)) {
rows = Some((y0, y1));
if rb.0 == Some(y0) {
std::mem::swap(&mut ra, &mut rb);
}
if ra.0 != Some(y0) {
read_row(y0, &mut ra.1);
ra.0 = Some(y0);
}
if rb.0 != Some(y1) {
read_row(y1, &mut rb.1);
rb.0 = Some(y1);
}
for (((pa, pb), lo), hi) in ra.1.chunks_exact(n).zip(rb.1.chunks_exact(n)).zip(vlo.chunks_exact_mut(n)).zip(vhi.chunks_exact_mut(n)) {
let seen = |p: &[f32]| !alpha || p.last().is_some_and(|&v| v > 0.0);
let (sa, sb) = (seen(pa), seen(pb));
for (c, (((&va, &vb), l), h)) in pa.iter().zip(pb).zip(lo.iter_mut()).zip(hi.iter_mut()).enumerate() {
let all = alpha && c == n - 1;
let (ia, ib) = (sa || all, sb || all);
*l = match (ia, ib) {
(true, true) => va.min(vb),
(true, false) => va,
(false, true) => vb,
(false, false) => f32::INFINITY,
};
*h = match (ia, ib) {
(true, true) => va.max(vb),
(true, false) => va,
(false, true) => vb,
(false, false) => f32::NEG_INFINITY,
};
}
}
}
for (&(x0, x1), px) in xs.iter().zip(row.chunks_exact_mut(n)) {
let (l0, l1, h0, h1) = (vlo.get(x0 * n..), vlo.get(x1 * n..), vhi.get(x0 * n..), vhi.get(x1 * n..));
let (Some(l0), Some(l1), Some(h0), Some(h1)) = (l0, l1, h0, h1) else { continue };
for ((((v, &l0), &l1), &h0), &h1) in px.iter_mut().zip(l0).zip(l1).zip(h0).zip(h1) {
let (lo, hi) = (l0.min(l1), h0.max(h1));
if lo <= hi {
*v = v.clamp(lo, hi);
}
}
}
}
(r, data)
};
let bands: Vec<usize> = (0..(dst.height() as usize).div_ceil(BAND)).collect();
// Bands read disjoint output rows, so each group is written before the next is computed, and
// the `f32` rows held at once are bounded by the group (#1544).
#[cfg(not(target_arch = "wasm32"))]
let group = rayon::current_num_threads().max(1) * 2;
#[cfg(target_arch = "wasm32")]
let group = 1;
for chunk in bands.chunks(group) {
#[cfg(not(target_arch = "wasm32"))]
let parts: Vec<(Rect, Vec<f32>)> = {
use rayon::prelude::*;
let o: &Surface = out;
chunk.par_iter().map(|&b| band(o, b)).collect()
};
#[cfg(target_arch = "wasm32")]
let parts: Vec<(Rect, Vec<f32>)> = chunk.iter().map(|&b| band(out, b)).collect();
#[cfg(test)]
DERING_MAX_HELD_BANDS.fetch_max(parts.len(), std::sync::atomic::Ordering::Relaxed);
for (r, d) in parts {
out.write_region(r, &d);
}
}
}
/// A source row read by [`dering`]: its index (if any yet) and samples.
type SourceRow = (Option<usize>, Vec<f32>);
/// The most source rows one read of [`dering`] has spanned, and the most bands it has held
/// before writing them, so tests can check both stay bounded.
#[cfg(test)]
pub(crate) static DERING_MAX_READ_ROWS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
#[cfg(test)]
thread_local! {
/// The most source columns one read of [`dering`] has spanned on this thread.
pub(crate) static DERING_READ_COLUMNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
pub(crate) static DERING_MAX_HELD_BANDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// Output rows computed together by [`PassState::band`].
const BAND: usize = 64;
@@ -607,6 +792,8 @@ pub struct ResizeSteps {
canvas: Option<Rect>,
filter: Resample,
scale: (f64, f64),
/// The input and its canvas, kept for Preserve Details' closing sharpening.
orig: Option<(Surface, Option<Rect>)>,
run: Option<PassRun>,
/// Final pruning must yield too: sparse output can contain many default-filled tiles.
prune: Option<photocraft_raster::PruneCursor>,
@@ -625,7 +812,8 @@ impl ResizeSteps {
/// or [`resize_surface_in_canvas`] does.
pub fn new(src: Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>) -> Self {
let passes = plan(filter, sx, sy);
Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), run: None, prune: None }
let orig = derings(src.format(), filter, sx, sy).then(|| (src.clone(), canvas));
Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), orig, run: None, prune: None }
}
/// How far along it is, `0.0..=1.0`: whole passes plus the bands done of the current one.
@@ -677,7 +865,8 @@ impl ResizeSteps {
if self.prune.is_none() {
let placeholder = Surface::new(self.src.format());
let out = std::mem::replace(&mut self.src, placeholder);
self.src = preserve_details(out, self.filter, self.scale.0, self.scale.1);
let orig = self.orig.take();
self.src = preserve_details(out, orig.as_ref().map(|(o, c)| (o, *c)), self.filter, self.scale.0, self.scale.1);
self.prune = Some(self.src.prune_cursor());
}
let cursor = self.prune.as_mut()?;
@@ -704,5 +893,7 @@ pub fn crop_surface(s: &Surface, keep: Rect) -> Surface {
out
}
#[cfg(test)]
mod preserve_details_edge_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,239 @@
//! Preserve Details enlarges hard edges without a ringing halo (#14794).
use super::*;
use photocraft_color::{ColorMode, PixelFormat, SampleType};
const CANVAS: Rect = Rect { x0: 0, y0: 0, x1: 400, y1: 300 };
/// The issue's flattened document: white, a red square at (0,0), a blue one at (300,200) and a
/// green one at (175,125), each opaque.
fn document(sample: SampleType, alpha: bool) -> Surface {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, alpha));
let px = |r: f32, g: f32, b: f32| if alpha { vec![r, g, b, 1.0] } else { vec![r, g, b] };
s.fill_rect(CANVAS, &px(1.0, 1.0, 1.0));
s.fill_rect(Rect::new(0, 0, 100, 100), &px(1.0, 0.0, 0.0));
s.fill_rect(Rect::new(300, 200, 400, 300), &px(0.0, 0.0, 1.0));
s.fill_rect(Rect::new(175, 125, 225, 175), &px(0.0, 1.0, 0.0));
s
}
/// The green channel at y, x in `xs`, in 8-bit levels.
fn green(s: &Surface, y: i32, xs: std::ops::Range<i32>) -> Vec<i32> {
xs.map(|x| (s.pixel(x, y)[1] * 255.0).round() as i32).collect()
}
fn within(actual: &[i32], expected: &[i32], tol: i32) -> bool {
actual.len() == expected.len() && actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= tol)
}
/// The reference application enlarges the red/white edge 2x to `0,0,0,8,247,255,255,255,255`
/// (green channel, y=20, x 196..204) with Preserve Details: no overshoot on either side, a
/// steep edge. Measured at 8 bits only (16 and 32 bits keep the previous result, see
/// [`unmeasured_enlargements_keep_the_previous_sharpening`]).
#[test]
fn enlarging_a_hard_edge_does_not_ring() {
let reference = [0, 0, 0, 8, 247, 255, 255, 255, 255];
for alpha in [false, true] {
let o = resize_surface_in_canvas(&document(SampleType::U8, alpha), 2.0, 2.0, Resample::PreserveDetails, CANVAS);
let row = green(&o, 20, 196..205);
assert!(within(&row, &reference, 2), "alpha={alpha}: {row:?}, reference {reference:?}");
}
}
/// Reducing with Preserve Details stays Bicubic Sharper: `0,0,0,13,242,255,255,255` at 200x150.
#[test]
fn reducing_stays_bicubic_sharper() {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let s = document(sample, false);
let pd = resize_surface_in_canvas(&s, 0.5, 0.5, Resample::PreserveDetails, CANVAS);
let sharper = resize_surface_in_canvas(&s, 0.5, 0.5, Resample::BicubicSharper, CANVAS);
let r = Rect::new(0, 0, 200, 150);
assert_eq!(pd.read_region(r), sharper.read_region(r), "{sample:?}");
if sample == SampleType::U8 {
assert_eq!(green(&pd, 10, 46..54), [0, 0, 0, 13, 242, 255, 255, 255]);
}
}
}
/// The other methods enlarge the edge as before (#14794 changes Preserve Details only).
#[test]
fn other_methods_keep_their_edge() {
let s = document(SampleType::U8, false);
let cases: [(Resample, [i32; 9]); 7] = [
(Resample::Nearest, ROWS[0]),
(Resample::Bilinear, ROWS[1]),
(Resample::Bicubic, ROWS[2]),
(Resample::BicubicSmoother, ROWS[3]),
(Resample::BicubicSharper, ROWS[4]),
(Resample::BicubicAutomatic, ROWS[5]),
(Resample::Lanczos, ROWS[6]),
];
for (f, expected) in cases {
let o = resize_surface_in_canvas(&s, 2.0, 2.0, f, CANVAS);
assert_eq!(green(&o, 20, 196..205), expected, "{f:?}");
}
}
/// The rows main 406ac677e1 gives, for [`other_methods_keep_their_edge`].
const ROWS: [[i32; 9]; 7] = [
[0, 0, 0, 0, 255, 255, 255, 255, 255],
[0, 0, 0, 64, 191, 255, 255, 255, 255],
[0, 0, 0, 58, 197, 255, 255, 255, 255],
[0, 0, 0, 66, 189, 255, 255, 255, 255],
[0, 0, 0, 66, 189, 255, 255, 255, 255],
[0, 0, 0, 66, 189, 255, 255, 255, 255],
[8, 0, 0, 54, 201, 255, 255, 247, 253],
];
/// The measured enlargement (8 bits, 2x) stays within the source's levels: no halo darker than
/// the red or brighter than the white, and flat areas stay flat.
#[test]
fn the_measured_enlargement_never_overshoots() {
let s = document(SampleType::U8, true);
let o = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::PreserveDetails, CANVAS);
let dst = scaled_rect(CANVAS, 2.0, 2.0);
assert_eq!(o.content_bounds(), dst);
for v in o.read_region(dst) {
assert!((0.0..=1.0).contains(&v), "{v}");
}
// Inside the red square, away from its edge.
assert_eq!(o.pixel(100, 100), vec![1.0, 0.0, 0.0, 1.0]);
}
/// A layer smaller than the canvas, on transparency: in the measured case the clamp doesn't pull
/// its colour towards the transparent pixels, and at any scale and depth the stepped resize gives
/// the same pixels as the one-shot one.
#[test]
fn transparent_surroundings_and_steps_match() {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]);
for k in [2.0, 2.5] {
let o = resize_surface_in_canvas(&s, k, k, Resample::PreserveDetails, CANVAS);
if sample == SampleType::U8 && k == 2.0 {
// On the layer's edge the colour stays the layer's.
let edge = o.pixel(20, 40);
assert!(edge[3] > 0.0 && edge[3] < 1.0, "{edge:?}");
let off = edge.iter().take(3).zip([0.2, 0.6, 1.0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(off < 0.01, "{edge:?}");
}
let mut steps = ResizeSteps::new(s.clone(), k, k, Resample::PreserveDetails, Some(CANVAS));
let stepped = loop {
if let Some(out) = steps.step(&mut || true) {
break out;
}
};
let r = o.content_bounds().union(&stepped.content_bounds());
assert_eq!(stepped.read_region(r), o.read_region(r), "{sample:?} {k}");
}
}
}
/// Preserve Details before #14794: Lanczos, then an Unsharp Mask of 30 % at radius 0.6 x scale.
fn lanczos_and_unsharp_mask(s: &Surface, sx: f64, sy: f64) -> Surface {
let out = resize_surface(s, sx, sy, Resample::Lanczos);
let dst = out.content_bounds();
let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
let area = crate::output_area(&p, dst, dst, None);
let mut out = crate::apply(&out, &p, area, dst, None);
out.prune();
out
}
/// The issue measured only 8-bit 2x enlargements; other scales and 16/32-bit documents keep
/// Preserve Details' previous result (#14794, "not measured ... keep today's behaviour").
#[test]
fn unmeasured_enlargements_keep_the_previous_sharpening() {
let cases = [
(SampleType::U8, 1.37, 1.37),
(SampleType::U8, 3.0, 3.0),
(SampleType::U8, 2.0, 1.5),
(SampleType::U8, 1.0, 2.0),
(SampleType::U16, 2.0, 2.0),
(SampleType::F32, 2.0, 2.0),
];
for (sample, sx, sy) in cases {
let s = document(sample, false);
let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails);
let expected = lanczos_and_unsharp_mask(&s, sx, sy);
let r = actual.content_bounds().union(&expected.content_bounds());
assert!(actual.read_region(r) == expected.read_region(r), "{sample:?} {sx}x{sy}: differs from Lanczos + Unsharp Mask 30 %");
}
}
/// One axis shrinking and the other growing: the columns black, black, black, white reduced to a
/// quarter keep the white averaged in by the reduction instead of being clamped back to black.
#[test]
fn mixed_axis_resize_keeps_reduced_detail() {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
for x in 0..64 {
let v = if x % 4 == 3 { 1.0 } else { 0.0 };
s.fill_rect(Rect::new(x, 0, x + 1, 16), &[v, v, v, 1.0]);
}
let o = resize_surface(&s, 0.25, 2.0, Resample::PreserveDetails);
let v = o.pixel(8, 16)[1];
assert!(v > 0.1, "{sample:?}: green {v} at (8,16), the white columns were clamped away");
let expected = lanczos_and_unsharp_mask(&s, 0.25, 2.0);
let r = o.content_bounds().union(&expected.content_bounds());
assert!(o.read_region(r) == expected.read_region(r), "{sample:?}: differs from Lanczos + Unsharp Mask 30 %");
}
}
/// A band of output rows that spans thousands of source rows (6000x4000 at 2 x 0.01 spans about
/// 3900 per band) reads them a row at a time, so a read stays within the read budget.
#[test]
fn dering_reads_a_bounded_number_of_source_rows() {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false));
s.fill_rect(Rect::new(0, 0, 8, 4000), &[0.5, 0.5, 0.5]);
let mut o = resize_surface(&s, 2.0, 0.01, Resample::Lanczos);
dering(&mut o, &s, 2.0, 0.01, None);
let rows = DERING_MAX_READ_ROWS.load(std::sync::atomic::Ordering::Relaxed);
assert!(rows <= 1, "one dering read spanned {rows} source rows");
}
/// Dering writes its bands a group at a time, like `resize_pass`, instead of holding them all.
#[test]
fn dering_holds_a_bounded_group_of_bands() {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false));
s.fill_rect(Rect::new(0, 0, 2, 6400), &[0.5, 0.5, 0.5]);
let mut o = resize_surface(&s, 2.0, 2.0, Resample::Lanczos);
dering(&mut o, &s, 2.0, 2.0, None);
let held = DERING_MAX_HELD_BANDS.load(std::sync::atomic::Ordering::Relaxed);
let group = rayon::current_num_threads().max(1) * 2;
assert!(held <= group, "dering held {held} of {} bands at once (group {group})", 12800usize.div_ceil(BAND));
}
/// Without a canvas, positions outside the content read the default pixel, as the resize does:
/// an opaque square on transparency keeps its partly transparent fringe instead of the clamp
/// making it opaque, and the result equals the one in a canvas of transparency around it.
#[test]
fn enlarging_without_a_canvas_keeps_the_transparent_fringe() {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]);
let o = resize_surface(&s, 2.0, 2.0, Resample::PreserveDetails);
// The square's first output column: Lanczos leaves it partly transparent (about 0.79).
let fringe = o.pixel(20, 40)[3];
assert!(fringe > 0.0 && fringe < 1.0, "alpha {fringe} on the square's edge");
let framed = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::PreserveDetails, CANVAS);
let r = o.content_bounds().union(&framed.content_bounds());
assert!(o.read_region(r) == framed.read_region(r), "differs from the same square in a transparent canvas");
}
/// With a canvas much wider than the layer, dering reads only the source columns the output
/// samples use, not the whole canvas width.
#[test]
fn dering_reads_only_the_columns_it_uses() {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
s.fill_rect(Rect::new(1000, 10, 1020, 30), &[0.2, 0.6, 1.0, 1.0]);
let canvas = Rect::new(0, 0, 20_000, 40);
let mut o = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::Lanczos, canvas);
// One worker thread, so the thread-local counter sees every read.
let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();
let cols = pool.install(|| {
DERING_READ_COLUMNS.with(|c| c.set(0));
dering(&mut o, &s, 2.0, 2.0, Some(canvas));
DERING_READ_COLUMNS.with(std::cell::Cell::get)
});
assert!(cols <= 40, "one dering read spanned {cols} source columns");
}
+21 -4
View File
@@ -1581,14 +1581,29 @@ mod tests {
let before = mcp.headless_op(|h| h.inspect(None)).await.unwrap().unwrap();
let Backend::Headless(session) = &*mcp.backend else { panic!("headless") };
let session = session.clone();
// A call holds clones of the session until it returns. A waited start holds exactly three
// once its blocking closure is queued on `spawn_blocking` (from where it can only wait for
// the lock): `step`'s, `headless_wait`'s target, and `headless_op`'s, taken last, right
// before the closure is queued. The wait below matches that count exactly, so a call path
// that takes one more clone times out here instead of letting the test go on with only
// one start queued.
let idle = Arc::strong_count(&session);
let held = session.clone();
let (locked, acquired) = std::sync::mpsc::channel();
let (release, released) = std::sync::mpsc::channel();
let holder = std::thread::spawn(move || {
let _held = session.lock().unwrap();
let _held = held.lock().unwrap();
locked.send(()).unwrap();
released.recv().unwrap();
});
acquired.recv().unwrap();
async fn until(what: &str, done: impl Fn() -> bool) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !done() {
assert!(std::time::Instant::now() < deadline, "timed out waiting until {what}");
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
}
let (mut input, server_in) = tokio::io::duplex(65536);
let (server_out, output) = tokio::io::duplex(65536);
@@ -1607,7 +1622,8 @@ mod tests {
)
.await;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
// The holder's clone, and three for each start.
until("both starts are queued", || Arc::strong_count(&session) == idle + 1 + 2 * 3).await;
for id in [2, 3] {
send(&mut input, json!({"jsonrpc":"2.0", "method":"notifications/cancelled", "params":{"requestId":id}})).await;
}
@@ -1620,8 +1636,9 @@ mod tests {
}
release.send(()).unwrap();
holder.join().unwrap();
// Let both blocked starts acquire the mutex before inspecting their effects.
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
// Both blocked starts took the lock and returned (their replies are dropped, as cancelled)
// before their effects are inspected.
until("both starts returned", || Arc::strong_count(&session) == idle).await;
let (after, jobs) = mcp.headless_op(|h| Ok((h.inspect(None)?, h.session.jobs_with_recent()))).await.unwrap().unwrap();
assert_eq!(after, before);
assert!(jobs.is_empty(), "cancelled queued job started: {jobs:?}");
+12 -3
View File
@@ -149,7 +149,11 @@ async fn a_waited_command_reports_progress_serves_other_calls_and_cancels_cleanl
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_batch_cancels_its_waited_step_and_runs_no_later_step() {
let mut wire = Wire::start(PhotocraftMcp::headless()).await;
let session = Arc::new(Mutex::new(photocraft_automation::headless::Headless::new()));
let mut wire = Wire::start(PhotocraftMcp::with_backend(Backend::Headless(session.clone()))).await;
// Every call holds a clone of the session until it returns, and a batch holds one for its
// whole run (the target it pinned), so the count is back here once no call is running.
let idle = Arc::strong_count(&session);
wire.big_document().await;
let before = wire.history(4).await;
@@ -158,8 +162,13 @@ async fn cancelling_a_batch_cancels_its_waited_step_and_runs_no_later_step() {
assert!(wire.first_progress(5, "batch", 2.0).await < 1.0, "still in the first step");
wire.cancel(5).await;
wire.settle(6, 5).await;
// Give a (wrongly) continuing batch time to start its next step.
tokio::time::sleep(Duration::from_millis(200)).await;
// The cancelled batch never answers, so its end is not visible on the wire: wait until it
// has returned, after which a (wrongly) continuing batch has run its next step.
let deadline = Instant::now() + Duration::from_secs(30);
while Arc::strong_count(&session) != idle {
assert!(Instant::now() < deadline, "the cancelled batch never returned");
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert_eq!(wire.history(1000).await, before, "neither the blur nor the later step ran");
wire.finish().await;
}
+1 -1
View File
@@ -19,7 +19,7 @@ photocraft-geom = { workspace = true }
photocraft-color = { workspace = true }
craft-cms = { workspace = true }
# PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide.
craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
photocraft-raster = { workspace = true }
photocraft-doc = { workspace = true }
photocraft-ops = { workspace = true }
@@ -430,6 +430,83 @@ fn recording_document_activation_uses_opening_order_offset() {
assert_eq!(s.actions().list.actions()[0].steps, [ActionStep::new("document.activate", json!({"offset": -1}))]);
}
/// #10769 "Playing on another document": recording is not tied to an open document. It starts
/// with none open, and the commands that create and edit a document land in the action.
#[test]
fn recording_starts_with_no_document_open() {
let mut s = crate::session();
s.execute("actions.record", json!({"name": "Open and ink"})).unwrap();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap();
assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 2);
assert_eq!(s.execute("actions.get", json!({"action": "Open and ink"})).unwrap()["steps"][0][0], "file.new");
}
/// A document with layers X, Y and Z: none of the layer names a recording on A, B, C refers to.
fn other_names_document(s: &mut Session) {
s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
for name in ["X", "Y", "Z"] {
s.execute("layer.new.layer", json!({"name": name})).unwrap();
}
}
/// The active document's layer names, bottom to top, without the Background.
fn played_layer_names(s: &Session) -> Vec<String> {
s.active().unwrap().doc.walk().into_iter().filter(|(_, _, layer)| layer.name != "Background").map(|(_, _, layer)| layer.name.clone()).collect()
}
/// "Playing on another document" (#10769): a step that names a layer the playing document does
/// not have stops the playback there and names the layer in its error; it must not act on another
/// layer, and the steps after it must not run. The panel's Continue / Stop ask builds on this stop.
/// A name the playing document does not have covers both cases: one it never had, and one deleted
/// from the document the recording was made on.
#[test]
fn a_step_naming_a_missing_layer_stops_instead_of_acting_on_the_wrong_layer() {
let mut s = crate::session();
other_names_document(&mut s);
s.actions_mut()
.list
.push(Action::new("On B", vec![ActionStep::new("layer.select", json!({"name": "B"})), ActionStep::new("layer.new.layer", json!({"name": "Made"}))]))
.unwrap();
let played = s.execute("actions.play", json!({"action": "On B"})).unwrap();
assert_eq!(played["failed"]["step"], 0, "{played}");
assert_eq!(played["failed"]["id"], "layer.select", "{played}");
assert!(played["failed"]["error"].as_str().is_some_and(|error| error.contains('B')), "{played}");
assert_eq!(played_layer_names(&s), ["X", "Y", "Z"], "the playback stopped at the step naming B, on no wrong layer, and ran no later step");
}
/// The eye-icon step keeps its layer by `_actionLayer`; on a document without that name it stops
/// there without hiding one of the present layers.
#[test]
fn an_eye_step_naming_a_missing_layer_stops_without_hiding_another_layer() {
let mut s = crate::session();
other_names_document(&mut s);
s.actions_mut()
.list
.push(Action::new("Hide B", vec![ActionStep::new("layer.setProps", json!({"visible": false, "_actionLayer": {"name": "B", "ordinal": 0}}))]))
.unwrap();
let played = s.execute("actions.play", json!({"action": "Hide B"})).unwrap();
assert_eq!(played["failed"]["step"], 0, "{played}");
assert!(played["failed"]["error"].as_str().is_some_and(|error| error.contains("recorded layer `B`")), "{played}");
let doc = s.active().unwrap().doc.clone();
assert!(doc.walk().into_iter().filter(|(_, _, layer)| layer.name != "Background").all(|(_, _, layer)| layer.visible), "X, Y and Z stay visible");
}
/// A step on the target (no layer reference) does not stop on another document: it acts on
/// whatever layer is selected there, as the reference records it (Ctrl+J copied Z).
#[test]
fn a_target_step_acts_on_the_selected_layer_of_another_document() {
let mut s = crate::session();
other_names_document(&mut s);
s.actions_mut().list.push(Action::new("Dim", vec![ActionStep::new("layer.setProps", json!({"opacity": 0.5}))])).unwrap();
let played = s.execute("actions.play", json!({"action": "Dim"})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
let doc = s.active().unwrap().doc.clone();
let opacity = |name: &str| doc.walk().into_iter().find(|(_, _, layer)| layer.name == name).map(|(_, _, layer)| layer.opacity);
assert_eq!(opacity("Z"), Some(0.5), "the active layer Z took the step");
assert_eq!(opacity("X"), Some(1.0), "the others are untouched");
}
#[test]
fn recorded_point_text_position_scales_with_the_playback_canvas() {
let mut s = crate::session();
@@ -652,7 +652,7 @@ mod tests {
s.execute("actions.stop", json!({})).unwrap();
let i = r["index"].as_u64().unwrap() as usize;
assert_eq!(s.actions().list.actions()[i].set.as_deref(), Some("Retouch"));
assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action");
assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"], "Retouch keeps its place now that it holds an action");
assert!(s.execute("actions.record", json!({"set": 3})).is_err());
}
@@ -84,7 +84,7 @@ fn reset_appends_a_numbered_set_and_persists_it() {
assert!(s.execute("actions.reset", json!({"confirm":true,"mode":"bad"})).is_err());
assert_eq!(s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap()["set"], "PhotoCraft Basics");
assert_eq!(s.execute("actions.reset", json!({"confirm":true,"mode":"append"})).unwrap()["set"], "PhotoCraft Basics 2");
assert_eq!(s.actions().list.sets(), ["PhotoCraft Basics", "PhotoCraft Basics 2", "Existing"]);
assert_eq!(s.actions().list.sets(), ["Existing", "PhotoCraft Basics", "PhotoCraft Basics 2"], "sets in the order they were made");
assert_eq!(names(&s), ["Invert Colors", "Desaturate", "Invert Colors 2", "Desaturate 2"]);
assert_eq!(s.actions().list.actions()[0].steps[0].command, "image.adjustments.invert");
assert_eq!(s.actions().list.actions()[1].steps[0].command, "image.adjustments.desaturate");
+19 -6
View File
@@ -15,7 +15,9 @@ use craft::color_ui::palette::{SwatchFormat, SwatchNote, default_swatches, read_
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::presets::swatches::{SwatchColor, SwatchConv, SwatchEntry, SwatchGroup, SwatchKind, color_from_param, color_json, hex, kind_id, parse_kind};
use crate::presets::swatches::{
SwatchColor, SwatchConv, SwatchEntry, SwatchGroup, SwatchKind, SwatchPaint, color_from_param, color_json, hex, kind_id, parse_kind,
};
use crate::presets::{bad, str_param};
use crate::{Result, Session};
@@ -119,10 +121,18 @@ fn group_of(s: &Session, name: &str, cmd: &str) -> Result<usize> {
s.presets().swatches.iter().position(|g| g.name == name).ok_or_else(|| bad(cmd, format!("no swatch group \"{name}\"")))
}
/// A swatch's name and kind, and its colour fields when it holds a colour (gradient, pattern and None swatches
/// hold none).
fn swatch_json(conv: &SwatchConv, sw: &SwatchEntry) -> Value {
let mut v = color_json(&sw.color);
let mut v = match sw.color() {
Some(color) => {
let mut v = color_json(color);
v["hex"] = json!(hex(conv.rgb(color)));
v
}
None => json!({}),
};
v["name"] = json!(sw.name);
v["hex"] = json!(hex(conv.rgb(&sw.color)));
if sw.kind != SwatchKind::Process {
v["kind"] = json!(kind_id(sw.kind));
}
@@ -192,7 +202,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => entries.len(),
Some(v) => usize::try_from(v.as_u64().ok_or_else(|| bad(CMD, "`index` must be a non-negative integer"))?).unwrap_or(usize::MAX).min(entries.len()),
};
entries.insert(at, SwatchEntry { name: name.clone(), color, kind });
entries.insert(at, SwatchEntry { name: name.clone(), paint: SwatchPaint::Color(color), kind });
let gname = groups[gi].name.clone();
presets_changed(s);
Ok(json!({"name": name, "group": gname, "index": at}))
@@ -351,7 +361,10 @@ fn use_swatch(s: &mut Session, p: &Value) -> Result<Value> {
let (gi, ii) = locate(s, p, CMD)?;
let target = str_param(p, "target").unwrap_or("foreground");
let sw = s.presets().swatches[gi].entries[ii].clone();
let rgb = SwatchConv::new(s).rgb(&sw.color);
let Some(&color) = sw.color() else {
return Err(bad(CMD, format!("swatch \"{}\" holds no colour", sw.name)));
};
let rgb = SwatchConv::new(s).rgb(&color);
let c = [rgb[0], rgb[1], rgb[2], 1.0];
match target {
"foreground" => s.tools.foreground = c,
@@ -362,7 +375,7 @@ fn use_swatch(s: &mut Session, p: &Value) -> Result<Value> {
// shows them and a CMYK document is painted with them, not with the sRGB round trip (#7474).
let role = if target == "background" { 1 } else { 0 };
s.tools.clear_role_cmyk(role);
if let SwatchColor::Cmyk(inks) = sw.color
if let SwatchColor::Cmyk(inks) = color
&& inks.iter().all(|v| v.is_finite())
{
let inks = inks.map(|v| v.clamp(0.0, 1.0));
@@ -33,7 +33,7 @@ fn add_from_foreground_and_explicit_models() {
s.tools.foreground = [1.0, 0.5, 0.0, 1.0];
let r = s.execute("swatches.add", json!({})).unwrap();
assert_eq!((r["name"].as_str(), r["group"].as_str()), (Some("Color Swatch 1"), Some("Grays")));
assert_eq!(s.presets().swatches[0].entries.last().unwrap().color, SwatchColor::Rgb([1.0, 0.5, 0.0]));
assert_eq!(s.presets().swatches[0].entries.last().unwrap().color(), Some(&SwatchColor::Rgb([1.0, 0.5, 0.0])));
let r = s.execute("swatches.add", json!({})).unwrap();
assert_eq!(r["name"], "Color Swatch 2");
// CMYK into a new group at the front, spot.
@@ -42,7 +42,7 @@ fn add_from_foreground_and_explicit_models() {
.unwrap();
assert_eq!(r["group"], "Print");
let g = s.presets().swatches.last().unwrap();
assert_eq!(g.entries[0], SwatchEntry { name: "Ink".into(), color: SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0]), kind: SwatchKind::Spot });
assert_eq!(g.entries[0], SwatchEntry { name: "Ink".into(), paint: SwatchPaint::Color(SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0])), kind: SwatchKind::Spot });
// Names stay unique.
let r = s.execute("swatches.add", json!({"name": "Ink"})).unwrap();
assert_eq!(r["name"], "Ink 2");
@@ -163,8 +163,8 @@ fn aco_round_trip_keeps_16_bit_values_and_books() {
assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("aco"), Some(6)));
assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the colour book is reported");
assert_eq!(s.presets().swatches.len(), 1);
assert_eq!(s.presets().swatches[0].entries[3].color, SwatchColor::Lab([53.21, -128.0, 127.0]));
assert_eq!(color_model(&s.presets().swatches[0].entries[4].color), "gray");
assert_eq!(s.presets().swatches[0].entries[3].color(), Some(&SwatchColor::Lab([53.21, -128.0, 127.0])));
assert_eq!(color_model(s.presets().swatches[0].entries[4].color().unwrap()), "gray");
assert_eq!(export_bytes(&mut s, json!({"format": "aco"})), file, "byte-identical .aco");
// On disk too, with the group taken from the file name.
let dir = std::env::temp_dir().join(format!("pc-swatch-{}", std::process::id()));
@@ -196,7 +196,7 @@ fn act_round_trip_loads_a_photoshop_color_table() {
let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "group": "Table", "mode": "replace"})).unwrap();
assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("act"), Some(256)));
assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the transparent color is reported");
assert_eq!(s.presets().swatches[0].entries[0].color, SwatchColor::Rgb([1.0, 1.0, 1.0]));
assert_eq!(s.presets().swatches[0].entries[0].color(), Some(&SwatchColor::Rgb([1.0, 1.0, 1.0])));
assert_eq!(s.presets().swatches[0].entries[1].name, "Swatch 2");
// Sniffed by length without a format, and by extension from a path.
let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "mode": "replace"})).unwrap();
@@ -265,8 +265,8 @@ fn ase_round_trip_keeps_groups_floats_and_kinds() {
assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the unknown model is reported");
let brand = s.presets().swatches.iter().find(|g| g.name == "Brand").unwrap();
assert_eq!(brand.entries[0].kind, SwatchKind::Spot);
assert_eq!(brand.entries[1].color, SwatchColor::Lab([50.0, 20.0, -30.0]));
assert_eq!(brand.entries[2].color, SwatchColor::Gray(0.75));
assert_eq!(brand.entries[1].color(), Some(&SwatchColor::Lab([50.0, 20.0, -30.0])));
assert_eq!(brand.entries[2].color(), Some(&SwatchColor::Gray(0.75)));
// Export both groups and read them back.
let out = export_bytes(&mut s, json!({"format": "ase", "swatches": ["Loose", "Spot ink", "Global lab", "Gray"]}));
let back = craft_psd::ase::parse(&out).unwrap();
@@ -456,3 +456,17 @@ fn values_beyond_f32_range_are_rejected_so_presets_survive_a_restart() {
assert_eq!(t.presets().swatches, s.presets().swatches, "user swatches survive a save and reload");
assert!(names(&t).contains(&"Keep me".to_string()));
}
/// A swatch that holds no colour (a gradient one, from another app's library) lists without colour fields, and using
/// it is refused.
#[test]
fn a_swatch_without_a_colour() {
let mut s = crate::session();
s.presets_mut().swatches[0].entries.push(SwatchEntry::with_paint("Fade", SwatchPaint::Gradient));
let r = s.execute("swatches.list", json!({})).unwrap();
let fade = r["groups"][0]["swatches"].as_array().unwrap().iter().find(|sw| sw["name"] == "Fade").unwrap().clone();
assert_eq!(fade, json!({"name": "Fade"}));
let before = s.tools.foreground;
assert!(s.execute("swatches.use", json!({"swatch": "Fade"})).is_err());
assert_eq!(s.tools.foreground, before);
}
+10 -8
View File
@@ -20,7 +20,7 @@ use serde_json::{Value, json};
use crate::Session;
pub use craft::color_ui::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchKind};
pub use craft::color_ui::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchKind, SwatchPaint};
/// Rewrites a saved `swatches` value from the shape before craft-color's model (groups holding
/// `items`) to the current one (`entries`). Called once, where the preferences are read.
@@ -36,16 +36,18 @@ pub fn upgrade_saved(saved: &mut Value) {
}
}
/// The id of a swatch kind (`process`, `global`, `spot`).
/// The id of a swatch kind (`process`, `global`, `spot`, `registration`).
pub fn kind_id(kind: SwatchKind) -> &'static str {
match kind {
SwatchKind::Process => "process",
SwatchKind::Global => "global",
SwatchKind::Spot => "spot",
SwatchKind::Registration => "registration",
}
}
/// The swatch kind an id names (`normal` is a synonym of `process`).
/// The swatch kind an id names (`normal` is a synonym of `process`). `registration` names none: the Registration
/// swatch is built in, never made by a command.
pub fn parse_kind(s: &str) -> Option<SwatchKind> {
Some(match s {
"process" | "normal" => SwatchKind::Process,
@@ -263,7 +265,7 @@ mod tests {
uniq.dedup();
assert_eq!(uniq.len(), 46, "names are unique: {names:?}");
assert_eq!(b[3].name, "Pure");
assert_eq!(b[3].entries[0].color, SwatchColor::Rgb([230.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0]));
assert_eq!(b[3].entries[0].color(), Some(&SwatchColor::Rgb([230.0 / 255.0, 40.0 / 255.0, 40.0 / 255.0])));
}
#[test]
@@ -273,7 +275,7 @@ mod tests {
let g = &b[1];
assert_eq!(g.name, "RGB");
let conv = SwatchConv::builtin();
let hexes: Vec<String> = g.entries.iter().map(|s| hex(conv.rgb(&s.color))).collect();
let hexes: Vec<String> = g.entries.iter().map(|s| hex(conv.rgb(s.color().unwrap()))).collect();
assert_eq!(hexes, ["#ff0000", "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#ff00ff"]);
}
@@ -352,9 +354,9 @@ mod tests {
assert_eq!(groups.len(), 1);
assert_eq!(groups[0].name, "Old");
let e = &groups[0].entries;
assert_eq!((e[0].color, e[0].kind), (SwatchColor::Gray(0.5), SwatchKind::Process));
assert_eq!((e[1].color, e[1].kind), (SwatchColor::Lab([50.0, -1.5, 2.25]), SwatchKind::Spot));
assert_eq!(e[2].color, SwatchColor::Book { space: 3, values: [1, 2, 3, 4] });
assert_eq!((e[0].color(), e[0].kind), (Some(&SwatchColor::Gray(0.5)), SwatchKind::Process));
assert_eq!((e[1].color(), e[1].kind), (Some(&SwatchColor::Lab([50.0, -1.5, 2.25])), SwatchKind::Spot));
assert_eq!(e[2].color(), Some(&SwatchColor::Book { space: 3, values: [1, 2, 3, 4] }));
let mut t = crate::session();
t.load_presets_json(s.presets().to_json(&s));
assert_eq!(t.presets().swatches, s.presets().swatches);
+26 -3
View File
@@ -144,8 +144,9 @@ pub fn describe(p: &Preferences) -> Value {
})
}
/// A key as the Summarize table shows it on `mac` (⌘ spelled Cmd, ⌥ Option) or elsewhere
/// (Ctrl, Alt).
/// A key as the Summarize table shows it on `mac` (⌘ spelled Cmd, ⌥ Option, in the stored order)
/// or elsewhere (Ctrl, Alt, ordered Alt, Shift, Ctrl as the reference shows them:
/// `Alt+Shift+Ctrl+K`).
fn key_label(sc: &str, mac: bool) -> String {
let Some(n) = normalize_shortcut(sc) else { return sc.to_string() };
// `Cmd++` splits into an empty part before the key, which joins back as `++`.
@@ -163,6 +164,16 @@ fn key_label(sc: &str, mac: bool) -> String {
}
parts.push(shown);
}
// Off the Mac the modifiers read Alt, Shift, Ctrl. The key stays last, and `Cmd++`'s empty
// part before it ranks after the modifiers.
if !mac && let Some((_, modifiers)) = parts.split_last_mut() {
modifiers.sort_by_key(|m| match *m {
"Alt" => 0,
"Shift" => 1,
"Ctrl" => 2,
_ => 3,
});
}
parts.join("+")
}
@@ -364,10 +375,22 @@ mod tests {
assert!(mac.contains("Cmd+Control+Option+G") && mac.contains("Gaussian Blur &amp; more") && mac.contains("Filter &lt;x&gt;"), "{mac}");
assert!(!mac.contains("Unbound") && !mac.contains("Empty"), "{mac}");
let pc = summarize("S", &sections, false);
assert!(pc.contains("<td>Ctrl+C, F3</td>") && pc.contains("Ctrl+Alt+G"), "{pc}");
assert!(pc.contains("<td>Ctrl+C, F3</td>") && pc.contains("Alt+Ctrl+G"), "{pc}");
assert_eq!(key_label("Cmd++", true), "Cmd++");
}
#[test]
fn summarize_orders_modifiers_alt_shift_ctrl_off_the_mac() {
// Edit › Keyboard Shortcuts… as the reference's Summarize page lists it (#14882).
let sections = vec![("Edit".to_string(), vec![("Keyboard Shortcuts...".to_string(), vec!["Cmd+Alt+Shift+K".to_string()])])];
let pc = summarize("S", &sections, false);
assert!(pc.contains("<td>Keyboard Shortcuts...</td><td>Alt+Shift+Ctrl+K</td>"), "{pc}");
assert_eq!(key_label("Shift+Ctrl+F8", false), "Shift+Ctrl+F8");
assert_eq!(key_label("Cmd+Alt++", false), "Alt+Ctrl++");
// The Mac keeps the stored order.
assert_eq!(key_label("Cmd+Ctrl+Alt+Shift+K", true), "Cmd+Control+Option+Shift+K");
}
#[test]
fn bound_lists_main_keys_then_alternates() {
crate::install().unwrap();
+2 -1
View File
@@ -117,7 +117,8 @@ fn set_duplication_preserves_metadata_call_targets_and_empty_folder_order() {
});
let result = s.execute("actions.duplicate", json!({"set":"S"})).unwrap();
assert_eq!(result["set"], "S copy");
assert_eq!(actions_edit_cmds::set_names(&s), ["S", "T", "S copy"]);
// The copy goes right after its source set, like the reference application.
assert_eq!(actions_edit_cmds::set_names(&s), ["S", "S copy", "T"]);
// The copies go after the set's last action, so a call to an action before that point keeps its target.
assert_eq!(s.actions().list.actions().iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["A", "Other", "B", "A copy", "B copy"]);
for a in s.actions().list.actions() {
+31 -14
View File
@@ -139,7 +139,7 @@ pub(crate) fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Re
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
#[test]
fn reentrant_admission_does_not_deadlock() {
@@ -201,29 +201,40 @@ mod tests {
assert_eq!(active_attempt_remaining(), Some(1));
}
/// Wait (at most 10 s) until a thread waiting at the gate has checked its interrupt `n`
/// times. It checks once on every pass of the wait loop, which it only enters while another
/// thread holds admission, so the count says it is waiting there rather than not there yet.
fn until_checked(checks: &AtomicUsize, n: usize) {
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while checks.load(Ordering::SeqCst) < n {
assert!(std::time::Instant::now() < deadline, "the second thread never waited at the gate");
std::thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn gate_serializes_concurrent_threads() {
let ctl = photocraft_raster::Interrupt::NONE;
let guard = acquire_decode_admission(&ctl).unwrap();
let thread_started = Arc::new(AtomicBool::new(false));
let checks = Arc::new(AtomicUsize::new(0));
let thread_acquired = Arc::new(AtomicBool::new(false));
let t_started = Arc::clone(&thread_started);
let t_checks = Arc::clone(&checks);
let t_acquired = Arc::clone(&thread_acquired);
let handle = std::thread::spawn(move || {
let ctl = photocraft_raster::Interrupt::NONE;
t_started.store(true, Ordering::SeqCst);
let counted = || {
t_checks.fetch_add(1, Ordering::SeqCst);
false
};
let ctl = photocraft_raster::Interrupt::cancel_only(&counted);
let g = acquire_decode_admission(&ctl).unwrap();
t_acquired.store(true, Ordering::SeqCst);
drop(g);
});
while !thread_started.load(Ordering::SeqCst) {
std::thread::yield_now();
}
// Give background thread time to reach condvar wait
std::thread::sleep(Duration::from_millis(60));
// Two passes of the wait loop: the thread has waited on the condvar at least once.
until_checked(&checks, 2);
assert!(!thread_acquired.load(Ordering::SeqCst), "second thread must block while guard held");
drop(guard);
@@ -236,19 +247,25 @@ mod tests {
let ctl = photocraft_raster::Interrupt::NONE;
let guard = acquire_decode_admission(&ctl).unwrap();
let checks = Arc::new(AtomicUsize::new(0));
let cancelled = Arc::new(AtomicBool::new(false));
let c_flag = Arc::clone(&cancelled);
let flag_for_thread = Arc::clone(&cancelled);
let (flag_for_thread, t_checks) = (Arc::clone(&cancelled), Arc::clone(&checks));
let handle = std::thread::spawn(move || {
let cancelled = || flag_for_thread.load(Ordering::SeqCst);
// Read the flag before counting: once the count moves, that check has said "go on".
let cancelled = || {
let cancelled = flag_for_thread.load(Ordering::SeqCst);
t_checks.fetch_add(1, Ordering::SeqCst);
cancelled
};
let progress = |_: f32| {};
let interrupt = photocraft_raster::Interrupt::new(&cancelled, &progress);
acquire_decode_admission(&interrupt).map(drop)
});
// Let thread block on condvar
std::thread::sleep(Duration::from_millis(60));
// The thread is in the wait loop, blocked behind the guard.
until_checked(&checks, 1);
// Cancel waiting thread
c_flag.store(true, Ordering::SeqCst);
+1 -1
View File
@@ -7,7 +7,7 @@ license.workspace = true
rust-version.workspace = true
[dependencies]
craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "5c5e0d52c387c0a4ae2908a07e476d7584f60362" }
craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "3656e8aaa41cba15ec5d11b7c77045cb72dec163" }
[lints]
workspace = true
+7 -2
View File
@@ -30,7 +30,12 @@ use craft::ui::runtime::install::WheelModifiers;
use craft::ui::runtime::{InstallError, InstallSpec};
use craft::ui::shell::embed;
use craft::window::policy::Decision;
use craft::window::system::SystemWindows;
// Tests run headless: the desktop pointer Windows tells is the mouse of the machine running them, not the test's
// pointer, so tests see no desktop services on any platform, as on Linux.
#[cfg(test)]
use craft::window::system::NoWindows as Desktop;
#[cfg(not(test))]
use craft::window::system::SystemWindows as Desktop;
use photocraft_engine::Session;
use photocraft_engine::prefs::{AppearanceMode, Preferences};
use serde_json::Value;
@@ -48,7 +53,7 @@ pub(crate) fn install(ctx: &egui::Context, fonts: &UiFonts<'_>, frame: Option<De
// PhotoCraft's input always has.
let wheel = WheelModifiers::new(egui::Modifiers::NONE, egui::Modifiers::SHIFT | egui::Modifiers::COMMAND);
let wake = ctx.clone();
let mut spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), Arc::new(SystemWindows))
let mut spec = InstallSpec::new(ShellInfo::default().backend(Backend::from_env()), Arc::new(Desktop))
.wheel(wheel)
.app_id(crate::os_window::app_id())
.system(SystemReader::start(move || wake.request_repaint()));
@@ -1728,10 +1728,10 @@ fn choose_eyedropper(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMe
return Ok(());
}
let rgb = menu.color.ok_or("No colour under the pointer")?;
use craft::color_ui::ui::{ColorPanelCommand, ColorPanelMenu, ColorPanelState};
use craft::color_ui::ui::{ColorPanelAction, ColorPanelCommand, ColorPanelMenu, ColorPanelState};
let copy = if command == EYEDROPPER_COPY_HTML { ColorPanelCommand::CopyHtml } else { ColorPanelCommand::CopyHex };
let color = craft::theme::Srgba::rgb(rgb[0], rgb[1], rgb[2]);
if let Some(text) = ColorPanelMenu::run_command(&mut ColorPanelState::default(), copy, color) {
if let Some(ColorPanelAction::Copy(text)) = ColorPanelMenu::run_command(&mut ColorPanelState::default(), copy, color) {
ctx.copy_text(text);
}
Ok(())
+11 -5
View File
@@ -9,7 +9,7 @@ use craft::behavior::{CanvasView, PixelSize};
use craft::imaging::ui::SelectionOverlay;
use craft::ui::canvas::{
Canvas, CanvasOutput, CanvasScrollbars, CanvasSpace, Extent, NavigationOptions, PageBorder, PageFrame, Pasteboard, PasteboardColor, PixelRect,
RasterDisplay, RasterSource, RotateView, ToolHost, ToolHostResponse, ViewTarget, canvas_space, easing_view, ruler_guide, tool_pass,
RasterDisplay, RasterSource, RotateView, ToolHost, ToolHostResponse, ViewTarget, WheelScheme, canvas_space, easing_view, ruler_guide, tool_pass,
};
use craft::ui::canvas_controls::{GuidesOutput, SelectionOutline};
use craft::ui::contract::{Bind, Props, Show, ShowContainer};
@@ -137,7 +137,7 @@ pub(crate) fn view_follows_pointer(app: &PhotocraftApp) -> bool {
pub(crate) fn navigation(app: &PhotocraftApp) -> NavigationOptions {
let p = app.session.prefs();
let mut options = NavigationOptions::default();
options.zoom_with_wheel = p.general.zoom_with_scroll_wheel;
options.wheel = if p.general.zoom_with_scroll_wheel { WheelScheme::Zoom } else { WheelScheme::Scroll };
options.animated_zoom = p.general.animated_zoom;
options.zoom_clicked_point_to_center = p.tools.zoom_clicked_point_to_center;
options.flick_panning = p.tools.enable_flick_panning;
@@ -546,7 +546,13 @@ fn canvas_controls(
// above the earlier ones, and the Crop frame covers the whole canvas (its outside turns the frame; #16231). They
// declare parts only over the bars and the compass, so a press elsewhere still reaches the controls below.
let mut shown = space.view;
// The task bars float above everything, so they stay inside the canvas short of the scroll bars: a bar that slides
// over a crop frame larger than the view would otherwise sit on the horizontal bar and take its presses (#16231).
let mut bar_area = rect;
if !app.ui.view.hides_chrome() {
// Document chrome draws the bars `size.icon.md` thick along the bottom and right edges, with no margin.
let thickness = craft::ui::runtime::env::Env::of(ui).tokens.tokens().size.icon.md;
bar_area.max -= egui::vec2(thickness, thickness);
let size = app.session.documents()[host.idx].doc.size;
let bounds = Rect64::from_origin_size(Point::ZERO, Size::new(f64::from(size.width), f64::from(size.height)));
CanvasScrollbars::new("Scroll bars", Bind::bound(&mut shown), bounds)
@@ -561,11 +567,11 @@ fn canvas_controls(
}
// One contextual task bar per window: the active document's tile carries it, not the tile drawn last.
if app.session.active_index() == Some(host.idx) {
crate::crop_task_bar::show(app, ui, rect);
crate::crop_task_bar::show(app, ui, bar_area);
if primary {
crate::transform_task_bar::show(app, ui, rect);
crate::transform_task_bar::show(app, ui, bar_area);
}
crate::frame_tool::task_bar::show(ui, app, rect);
crate::frame_tool::task_bar::show(ui, app, bar_area);
}
crate::crop_ui::each_pass(app);
crate::vector_ui::shapes::show_preview(app, ui, rect, &space.view);
+2 -2
View File
@@ -161,8 +161,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, host: CanvasHost,
// `command_guide_at` had it, so a plain marquee drag over a guide still draws a marquee.
.moves_with_command(takes && tool != Tool::Move && moves_with_command(app, tool))
.bounds(page);
if let Some(key) = selected {
guides = guides.selected_guide(key);
if let Some(key) = &selected {
guides = guides.selected_guides(std::slice::from_ref(key));
}
let output = guides.show_at(ui, content);
// A preview's guides are not the document's: nothing they report is an edit.
+3 -1
View File
@@ -55,7 +55,8 @@ fn selection_moves(app: &PhotocraftApp) -> bool {
/// The layers a drag moves or resizes: they are not targets. The selected layers when the Move tool drags and,
/// unless selected pixels float, what it moves whole (the layers linked to them and everything inside a group, so a
/// group does not snap to its own layers' starting edges), the type layer being edited (a paragraph-box handle drag
/// does not snap to the text it resizes, #6819) and the layers of the open Free Transform.
/// does not snap to the text it resizes, #6819), the layers of the open Free Transform and the shape layers the shape
/// scale box or a corner widget is pressing.
fn moving_set(app: &PhotocraftApp) -> Vec<LayerId> {
let mut set = Vec::new();
if moves_as_move_tool(app)
@@ -79,6 +80,7 @@ fn moving_set(app: &PhotocraftApp) -> Vec<LayerId> {
if let Some(t) = app.ui.transform.as_ref() {
set.extend(crate::transform_tool::moving_layers(t));
}
set.extend(crate::shape_controls::pressed_layers(app));
set
}
+2 -2
View File
@@ -1,6 +1,6 @@
use super::document_display::{CanvasHost, active_view};
use super::*;
use craft::behavior::canvas::ZoomLadder;
use craft::behavior::canvas::ZoomScheme;
use craft::behavior::kurbo::Size;
use craft::ui::canvas::{PixelRect, RasterSource};
use craft::ui::primitives::Revision;
@@ -936,7 +936,7 @@ fn torn_off_document_is_not_drawn_again_in_the_main_window() {
/// The zoom typed into a zoom field: the field's percent, kept inside the zoom range of the document.
fn type_zoom(view: &mut View, percent: f32) {
view.zoom = ZoomLadder::clamp(f64::from(percent) / 100.0, Size::new(f64::from(view.doc_size[0]), f64::from(view.doc_size[1]))) as f32;
view.zoom = ZoomScheme::PHOTOSHOP.clamp(f64::from(percent) / 100.0, Size::new(f64::from(view.doc_size[0]), f64::from(view.doc_size[1]))) as f32;
view.clear_pending();
}
+4 -2
View File
@@ -290,7 +290,9 @@ fn screenshot(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Reply
// (modals, popups) have settled (craft-automation's screenshot queue).
let token = app.ui.alloc_id();
ctx.request_repaint();
Reply::screenshot(token, path, viewport)
let mut params = craft::automation::screenshot::ScreenshotParams::default();
params.path = path;
Reply::screenshot(token, params, viewport)
}
/// `ui.notice.post {title, lines?, tone?}`: shows a notice in the named tone and replies its id.
@@ -997,7 +999,7 @@ impl ViewSet {
}
if let Some(z) = self.zoom {
let size = app.session.documents().get(i).map_or(Size::ZERO, |st| Size::new(f64::from(st.doc.size.width), f64::from(st.doc.size.height)));
app.ui.views[i].zoom = craft::behavior::canvas::ZoomLadder::clamp(z, size) as f32;
app.ui.views[i].zoom = craft::behavior::canvas::ZoomScheme::PHOTOSHOP.clamp(z, size) as f32;
app.ui.views[i].clear_pending();
}
if let Some(c) = self.center {
+1
View File
@@ -167,6 +167,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
"rect": task_bar_rect,
"pinned": app.ui.panels.task_bar.pinned,
"at": app.ui.panels.task_bar.at,
"offset": app.ui.panels.task_bar.offset,
}),
"dockTabs": legacy.get("dockTabs").cloned().unwrap_or(Value::Null),
"docking": app.ui.docking,
+3 -3
View File
@@ -271,11 +271,11 @@ pub(crate) mod params {
let key = key_of(app, id);
let Some(dialog) = dialog_mut(app, id) else { continue };
let (colour, path, dropper, listing, footer, range) = (
dialog.pick_color(),
dialog.take_color_request(),
dialog.pick_path(),
dialog.take_eyedropper(),
dialog.take_listing(),
dialog.take_footer_action(),
dialog.take_action(),
dialog.take_range_alert(),
);
if let Some(alert) = range {
@@ -287,7 +287,7 @@ pub(crate) mod params {
if let Some((row, colour)) = color_picker_ui::answer_for(app, id)
&& let Some(dialog) = dialog_mut(app, id)
{
dialog.answer_color(row, colour);
dialog.answer_color(&row, colour);
}
if let Some(request) = path {
start_pick(app, ctx, id, request);
@@ -1,4 +1,5 @@
use craft::ui::canvas::ShieldColor;
use craft::ui::dialog::StackDialog as _;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use craft::ui::runtime::requests::ColorRequest;
use serde_json::{Value, json};
@@ -121,7 +122,7 @@ fn ok_keeps_the_colour_and_the_dialog_makes_one_history_step() {
assert_eq!((answered_key.as_str(), rgb_hex(color).as_str()), (key.as_str(), "#336699"));
assert!(answer_for(&mut app, fill).is_none(), "an answer is taken once");
// The dialog takes the answer into its values as its pass does.
app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(fill).expect("Fill is open").answer_color(key.clone(), color);
app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(fill).expect("Fill is open").answer_color(&key, color);
host_pass(&mut app);
assert_eq!(held_color(&app, fill, &key).as_deref(), Some("#336699"));
+5 -6
View File
@@ -19,9 +19,9 @@ pub use print::open_print;
pub(crate) use print::print_status;
#[cfg(test)]
use print::{drag_print_position, print_params, printer_list};
pub use web::open_web;
#[cfg(test)]
use web::{WEB_COMMAND, download_for_web, options_of, pane_key, web_frame_document, web_params};
pub use web::{WebTable, open_web};
fn no_params(p: &Value) -> bool {
p.as_object().is_none_or(|o| o.is_empty())
@@ -186,20 +186,19 @@ mod web_playback_tests {
let ctx = app.ctx().clone();
take(&mut app, &ctx);
let first = encoded(&app, 0);
set_option(&mut app, id, "palette_edits", json!({"0": [255, 255, 0]}));
let shifted = [(first.color_table[0], [255, 255, 0])];
app.ui.web_table.apply(id, [(craft::ui::patterns::form_dialogs::ColorTableEdit::Shift(shifted[0].1), vec![shifted[0].0])]);
pass(&mut app);
take(&mut app, &ctx);
assert!(Arc::ptr_eq(&first, &encoded(&app, 0)), "palette edits reuse the current frame's indices");
let edits = app.framework.dialogs.get_by_id::<craft::ui::patterns::form_dialogs::HostedSaveForWeb>(id).unwrap().current().palette_edits.clone();
assert_eq!(edits.len(), 1);
assert_eq!(app.ui.web_table.of(id), &shifted);
let mut previous = first;
for (frame, rgba) in [(1, [0, 255, 0, 255]), (2, [0, 0, 255, 255]), (0, [255, 0, 0, 255])] {
set_frame(&mut app, id, frame);
let next = encoded(&app, 0);
assert!(!Arc::ptr_eq(&previous, &next), "a changed frame needs fresh indexed pixels");
assert_eq!(&next.preview[..4], &rgba);
let kept = app.framework.dialogs.get_by_id::<craft::ui::patterns::form_dialogs::HostedSaveForWeb>(id).unwrap().current().palette_edits.clone();
assert_eq!(kept, edits);
assert_eq!(app.ui.web_table.of(id), &shifted, "the shifts outlast a frame change");
assert_eq!(app.session.active().unwrap().doc.timeline.as_ref().unwrap().current, 0);
previous = next;
}
+8 -3
View File
@@ -3,7 +3,7 @@ use craft::ui::dialog::{DialogId, DialogResult, StackDialog as _};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, NumberUnit, Param, ParamKind};
use craft::ui::runtime::env::UnitKind;
use craft::ui::runtime::requests::PathKind;
use craft_print::ui::{Duplex, HostedPrint, PrintAnswer, PrintFinish, PrintMarks, PrintSection, PrintSheet, Printer, Settings, State};
use craft_print::ui::{Destination, Duplex, HostedPrint, PrintAnswer, PrintFinish, PrintMarks, PrintSection, PrintSheet, Printer, Settings, State};
use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
@@ -55,7 +55,7 @@ fn field_value(key: &str, v: &Value) -> Option<FieldValue> {
fn last_settings(m: &Map<String, Value>) -> Settings {
let mut settings = Settings::default();
if let Some(printer) = m.get("printer").and_then(Value::as_str) {
settings.printer = printer.to_string();
settings.destination = Destination::Printer(printer.to_string());
}
if let Some(copies) = m.get("copies").and_then(Value::as_u64) {
settings.copies = copies.clamp(1, 999) as u32;
@@ -72,7 +72,12 @@ fn last_settings(m: &Map<String, Value>) -> Settings {
/// Writes the panel's settings into the `file.print` fields that carry them.
fn write_settings(fields: &mut DialogFields, settings: &Settings) {
fields.set("printer", FieldValue::Text(settings.printer.clone()));
// The image layout lists printers only: Save as PDF is the dialog's own `output` row, not a destination.
let printer = match &settings.destination {
Destination::Printer(name) => name.clone(),
_ => String::new(),
};
fields.set("printer", FieldValue::Text(printer));
fields.set("copies", FieldValue::Int(i64::from(settings.copies)));
match settings.duplex {
Some(Duplex::Off) => fields.set("duplex", FieldValue::Text("off".into())),
+136 -23
View File
@@ -7,8 +7,8 @@ use std::sync::Arc;
use craft::behavior::PixelSize;
use craft::ui::dialog::{DialogId, DialogResult, StackDialog};
use craft::ui::patterns::form_dialogs::{
Animation, ColorTable, Dither, HostedSaveForWeb, Resample, SaveForWebOptions, SaveForWebResult, WantedVariant, WebFormat, WebMetadata, WebPreset, WebSlice,
WebSlices, WebVariant,
Animation, ColorTable, ColorTableEdit, Dither, HostedSaveForWeb, Resample, SaveForWebOptions, SaveForWebResult, TableMarks, WantedVariant, WebFormat,
WebMetadata, WebPreset, WebSlice, WebSlices, WebVariant,
};
use craft::ui::runtime::env::Label;
use egui::load::SizedTexture;
@@ -59,7 +59,7 @@ fn hex(rgb: [u8; 3]) -> String {
format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])
}
fn parse_hex(text: &str) -> Option<[u8; 3]> {
pub(super) fn parse_hex(text: &str) -> Option<[u8; 3]> {
let digits = text.trim().strip_prefix('#').unwrap_or(text.trim());
if digits.len() != 6 || !digits.is_ascii() {
return None;
@@ -68,6 +68,72 @@ fn parse_hex(text: &str) -> Option<[u8; 3]> {
Some([channel(0)?, channel(2)?, channel(4)?])
}
/// The colour table of the open Save for Web dialog: each shifted colour with the colour it becomes. The dialog names
/// colours by value; the engine edits palette entries by index, so the shifts become `colorTableEdits` over the palette
/// each encode indexes with.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WebTable {
/// The dialog the shifts belong to.
dialog: Option<DialogId>,
/// Each shifted colour and the colour it becomes, in the order they were shifted.
shifted: Vec<([u8; 3], [u8; 3])>,
}
impl WebTable {
/// Applies the edits of dialog `id`, each with the colours it applies to; a table of another dialog starts empty.
/// Returns whether the shifts changed. Lock, Make Transparent, Delete and Sort have no engine counterpart and
/// change nothing.
pub(super) fn apply(&mut self, id: DialogId, edits: impl IntoIterator<Item = (ColorTableEdit, Vec<[u8; 3]>)>) -> bool {
if self.dialog != Some(id) {
*self = WebTable { dialog: Some(id), shifted: Vec::new() };
}
let before = self.shifted.clone();
for (edit, colors) in edits {
match edit {
ColorTableEdit::Shift(to) => colors.iter().for_each(|from| self.shift(*from, to)),
ColorTableEdit::WebShift => colors.iter().for_each(|from| self.shift(*from, web_safe(*from))),
ColorTableEdit::Unshift => self.shifted.retain(|(from, _)| !colors.contains(from)),
ColorTableEdit::UnshiftAll | ColorTableEdit::Restore => self.shifted.clear(),
_ => {}
}
}
self.shifted != before
}
fn shift(&mut self, from: [u8; 3], to: [u8; 3]) {
self.shifted.retain(|(shifted, _)| *shifted != from);
if from != to {
self.shifted.push((from, to));
}
}
/// The marks the dialog's table shows.
fn marks(&self) -> TableMarks {
let mut marks = TableMarks::default();
marks.shifted = self.shifted.clone();
marks
}
/// The shifts of dialog `id`; none for another dialog.
pub(super) fn of(&self, id: DialogId) -> &[([u8; 3], [u8; 3])] {
if self.dialog == Some(id) { &self.shifted } else { &[] }
}
}
/// The nearest web-safe colour: each channel on the nearest multiple of 51.
fn web_safe(rgb: [u8; 3]) -> [u8; 3] {
rgb.map(|v| ((f32::from(v) / 51.0).round() * 51.0) as u8)
}
/// The engine's `colorTableEdits` for `shifted` over `palette`: every entry holding a shifted colour, by index.
pub(super) fn shift_edits(palette: &[[u8; 3]], shifted: &[([u8; 3], [u8; 3])]) -> serde_json::Map<String, Value> {
palette
.iter()
.enumerate()
.filter_map(|(at, color)| shifted.iter().find(|(from, _)| from == color).map(|(_, to)| (at.to_string(), json!(hex(*to)))))
.collect()
}
/// The dialog's options for engine parameters: remembered ones, a preset's, or the last export's. Keys the
/// parameters lack keep the dialog's defaults.
pub(super) fn options_of(p: &Value) -> SaveForWebOptions {
@@ -116,9 +182,6 @@ pub(super) fn options_of(p: &Value) -> SaveForWebOptions {
if let Some(v) = text("resample").and_then(|n| by_name(&RESAMPLES, n)) {
o.resample = v;
}
if let Some(edits) = p.get("colorTableEdits").and_then(Value::as_object) {
o.palette_edits = edits.iter().filter_map(|(k, v)| Some((k.parse().ok()?, parse_hex(v.as_str()?)?))).collect();
}
o.slices = match text("slices") {
Some("user") => WebSlices::User,
Some("selected") => {
@@ -162,9 +225,6 @@ pub(super) fn params_of(o: &SaveForWebOptions, has_slices: bool) -> Value {
p["width"] = json!(size.width);
p["height"] = json!(size.height);
}
if !o.palette_edits.is_empty() {
p["colorTableEdits"] = Value::Object(o.palette_edits.iter().map(|(i, c)| (i.to_string(), json!(hex(*c)))).collect());
}
if has_slices {
p["html"] = json!(o.html);
match &o.slices {
@@ -264,7 +324,9 @@ pub fn open_web(app: &mut PhotocraftApp) -> Option<DialogId> {
if let Some(t) = doc.timeline.as_ref().filter(|t| t.duration >= 2) {
dialog = dialog.animation(Animation::new(t.duration as u32, t.fps));
}
Some(app.framework.dialogs.open(dialog))
let id = app.framework.dialogs.open(dialog);
app.ui.web_table = WebTable { dialog: Some(id), shifted: Vec::new() };
Some(id)
}
/// The notice under the preview captions when the document has more slices than are resolved (`overflow_warning`):
@@ -288,8 +350,8 @@ pub(super) fn web_frame_document(doc: &photocraft_doc::Document, frame: Option<u
}
/// The picture of one wanted pane: the options' encode of the document's `frame`, reduced to a proxy of at most
/// 2048 px, with the size and palette the dialog shows.
fn encode(ctx: &egui::Context, app: &PhotocraftApp, wanted: &WantedVariant, frame: Option<usize>) -> WebVariant {
/// 2048 px, with the size and palette the dialog shows and the table's `shifted` colours.
fn encode(ctx: &egui::Context, app: &PhotocraftApp, wanted: &WantedVariant, frame: Option<usize>, shifted: &[([u8; 3], [u8; 3])]) -> WebVariant {
let (index, revision) = (wanted.index, wanted.request.revision);
let fail = |message: String| WebVariant::failed(index, revision, message);
let Some(st) = app.session.active() else { return fail("no document".into()) };
@@ -308,7 +370,7 @@ fn encode(ctx: &egui::Context, app: &PhotocraftApp, wanted: &WantedVariant, fram
let (w, h) = (proxy.size.width, proxy.size.height);
Ok((photocraft_compose::flatten(&proxy).into_px(), w, h))
};
let encoded = match web_preview::optimized(ctx, pane_key(doc.id.0, index), &signature, &p, source) {
let encoded = match web_preview::optimized(ctx, pane_key(doc.id.0, index), &signature, &p, shifted, source) {
Ok(encoded) => encoded,
Err(message) => return fail(message),
};
@@ -352,8 +414,16 @@ pub(super) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
let Some(dialog) = app.framework.dialogs.get_mut::<HostedSaveForWeb>() else { return };
let id = dialog.id();
let events = dialog.take_table_events();
if app.ui.web_table.apply(id, events.into_iter().map(|event| (event.edit, event.colors))) {
let marks = app.ui.web_table.marks();
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedSaveForWeb>(id) {
dialog.set_marks(marks);
}
}
let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedSaveForWeb>(id) else { return };
let wanted = dialog.wanted_variants();
let (color, path, frame) = (dialog.pick_color(), dialog.pick_path(), dialog.frame());
let (color, path, frame) = (dialog.take_color_request(), dialog.pick_path(), dialog.frame());
let current = dialog.current().clone();
if let Some(request) = color {
crate::color_picker_ui::open_for_request(app, id, request);
@@ -361,7 +431,7 @@ pub(super) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
if let Some((key, color)) = crate::color_picker_ui::answer_for(app, id)
&& let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedSaveForWeb>(id)
{
dialog.answer_color(key, color);
dialog.answer_color(&key, color);
}
if let Some(request) = path {
pick_save(app, id, request.key, &current);
@@ -370,7 +440,8 @@ pub(super) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
return;
}
let animated = app.session.active().is_some_and(|st| st.doc.timeline.as_ref().is_some_and(|t| t.duration >= 2));
let variants: Vec<WebVariant> = wanted.iter().map(|w| encode(ctx, app, w, animated.then_some(frame as usize))).collect();
let shifted = app.ui.web_table.of(id);
let variants: Vec<WebVariant> = wanted.iter().map(|w| encode(ctx, app, w, animated.then_some(frame as usize), shifted)).collect();
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedSaveForWeb>(id) {
for variant in variants {
dialog.set_variant(variant);
@@ -382,7 +453,8 @@ pub(super) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
/// opens, then the save picker answers the dialog's path request `key`.
fn pick_save(app: &mut PhotocraftApp, id: DialogId, key: String, current: &SaveForWebOptions) {
let slices = has_slices(app);
let checked = web_params(current, slices).and_then(|p| checked_params(app, &p));
let shifted = app.ui.web_table.of(id).to_vec();
let checked = web_params(current, slices).and_then(|p| checked_params(app, &p, &shifted));
let refuse = |app: &mut PhotocraftApp, error: String| {
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedSaveForWeb>(id) {
dialog.cancel_requests();
@@ -410,12 +482,15 @@ fn pick_save(app: &mut PhotocraftApp, id: DialogId, key: String, current: &SaveF
}
/// OK: the export runs with the confirmed options and the picked path; the settings are remembered once it succeeded.
/// Done writes nothing and remembers the settings.
fn finish(app: &mut PhotocraftApp, ctx: &egui::Context, result: SaveForWebResult) {
let shifted = std::mem::take(&mut app.ui.web_table).shifted;
let Some(picked) = result.path.as_deref() else { return result.remember(ctx) };
let slices = has_slices(app);
let outcome = web_params(&result.options, slices).and_then(|mut p| {
let path = result.path.to_string_lossy().into_owned();
let path = picked.to_string_lossy().into_owned();
if slices {
p["dir"] = json!(result.path.parent().map(|d| d.to_string_lossy().into_owned()).filter(|d| !d.is_empty()).unwrap_or_else(|| ".".into()));
p["dir"] = json!(picked.parent().map(|d| d.to_string_lossy().into_owned()).filter(|d| !d.is_empty()).unwrap_or_else(|| ".".into()));
} else {
// The suggested name kept: only the folder, so a recorded action saves each document under its own
// name, as in Photoshop (#5305). A document renamed since the picker opened no longer matches the
@@ -426,7 +501,7 @@ fn finish(app: &mut PhotocraftApp, ctx: &egui::Context, result: SaveForWebResult
None => p["path"] = json!(path),
}
}
web_confirm(app, &p)
web_confirm(app, &p, &shifted)
});
match outcome {
Ok(_) => result.remember(ctx),
@@ -449,10 +524,19 @@ fn authorize_web(app: &PhotocraftApp, p: &Value) -> Result<(), String> {
}
/// `p` with its generated palette, after the policy approved both the request and the palette-bearing parameters.
fn checked_params(app: &PhotocraftApp, p: &Value) -> Result<Value, String> {
/// The table's `shifted` colours become `colorTableEdits` over that palette.
fn checked_params(app: &PhotocraftApp, p: &Value, shifted: &[([u8; 3], [u8; 3])]) -> Result<Value, String> {
authorize_web(app, p)?;
let mut prepared = p.clone();
web_preview::prepare_table(app, &mut prepared)?;
let palette: Option<Vec<[u8; 3]>> =
prepared.get("colorTable").and_then(Value::as_array).map(|table| table.iter().filter_map(|c| c.as_str().and_then(parse_hex)).collect());
if let Some(palette) = palette.filter(|_| prepared.get("colorTableEdits").is_none()) {
let edits = shift_edits(&palette, shifted);
if !edits.is_empty() {
prepared["colorTableEdits"] = Value::Object(edits);
}
}
if prepared != *p {
authorize_web(app, &prepared)?;
}
@@ -460,8 +544,8 @@ fn checked_params(app: &PhotocraftApp, p: &Value) -> Result<Value, String> {
}
/// Runs Save for Web with the final parameters `p`, which say where to write.
pub(super) fn web_confirm(app: &mut PhotocraftApp, p: &Value) -> Result<Value, String> {
let p = checked_params(app, p)?;
pub(super) fn web_confirm(app: &mut PhotocraftApp, p: &Value, shifted: &[([u8; 3], [u8; 3])]) -> Result<Value, String> {
let p = checked_params(app, p, shifted)?;
save_for_web(app, p)
}
@@ -504,3 +588,32 @@ pub(super) fn download_for_web(app: &mut PhotocraftApp, mut p: Value) -> Result<
web_cmds::save_for_web_with_writer(&mut app.session, &p, &mut |path, bytes| write(path, bytes).map_err(photocraft_engine::EngineError::Other))
.map_err(|e| e.to_string())
}
#[cfg(test)]
mod table_tests {
use super::*;
fn event(edit: ColorTableEdit, colors: &[[u8; 3]]) -> (ColorTableEdit, Vec<[u8; 3]>) {
(edit, colors.to_vec())
}
/// The table's shifts follow the dialog's edits, and an export edits every palette entry of a shifted colour.
#[test]
fn table_shifts_become_palette_edits() {
let id = egui::Id::unique("save-for-web");
let (red, blue, off) = ([255, 0, 0], [0, 0, 255], [10, 100, 160]);
let mut table = WebTable::default();
assert!(table.apply(id, vec![event(ColorTableEdit::Shift([0, 255, 0]), &[red]), event(ColorTableEdit::WebShift, &[off])]));
assert_eq!(table.of(id), &[(red, [0, 255, 0]), (off, [0, 102, 153])]);
assert!(!table.apply(id, vec![event(ColorTableEdit::Lock, &[blue])]), "Lock has no engine counterpart");
assert!(table.of(egui::Id::unique("another")).is_empty(), "shifts belong to their dialog");
let edits = shift_edits(&[red, blue, red], table.of(id));
assert_eq!(Value::Object(edits), json!({"0": "#00ff00", "2": "#00ff00"}));
assert!(table.apply(id, vec![event(ColorTableEdit::Unshift, &[red])]));
assert_eq!(table.of(id), &[(off, [0, 102, 153])]);
assert!(table.apply(id, vec![event(ColorTableEdit::Restore, &[])]));
assert!(table.of(id).is_empty());
}
}
@@ -85,19 +85,20 @@ pub struct EncodedPreview {
pub height: u32,
}
/// Encodes the proxy `source` makes with `p`; `source` gets the settings of `p` without the palette edits. Palette
/// Encodes the proxy `source` makes with `p`, each colour of `shifted` replaced by the colour it shifts to. Palette
/// replacements reuse the cached index buffer (kept under `key` while `signature` and the other options are
/// unchanged): picker drags do not re-quantize or re-encode the proxy, and `source` does not run then. The GIF payload length is unchanged by RGB table replacements. The edits
/// (`colorTableEdits`) index the palette the encode chose, unless `p` fixes a `colorTable` of its own.
/// unchanged): picker drags do not re-quantize or re-encode the proxy, and `source` does not run then. The GIF payload
/// length is unchanged by RGB table replacements. The shifts edit the palette the encode chose, unless `p` fixes a
/// `colorTable` of its own.
pub fn optimized(
ctx: &egui::Context,
key: egui::Id,
signature: &str,
p: &Value,
shifted: &[([u8; 3], [u8; 3])],
source: impl FnOnce(&WebSettings) -> Result<(Vec<[f32; 4]>, u32, u32), String>,
) -> Result<EncodedPreview, String> {
let mut base = p.clone();
let edits = base.as_object_mut().and_then(|m| m.remove("colorTableEdits"));
let base = p.clone();
let signature = format!("{signature}|{base}");
let key = key.with("indexed-source");
let cached: Option<(String, Arc<Optimized>)> = ctx.data(|d| d.get_temp(key));
@@ -114,12 +115,16 @@ pub fn optimized(
encoded
};
let mut full = base;
let fixed: Option<Vec<[u8; 3]>> =
full.get("colorTable").and_then(Value::as_array).map(|table| table.iter().filter_map(|c| c.as_str().and_then(super::web::parse_hex)).collect());
let palette = fixed.unwrap_or_else(|| encoded.color_table.clone());
// A format without a palette has nothing to edit.
if let Some(edits) = edits.filter(|_| full.get("colorTable").is_some() || !encoded.color_table.is_empty()) {
let edits = super::web::shift_edits(&palette, shifted);
if !edits.is_empty() {
if full.get("colorTable").is_none() {
full["colorTable"] = json!(encoded.color_table.iter().map(|c| web_cmds::rgb_hex(*c)).collect::<Vec<_>>());
}
full["colorTableEdits"] = edits;
full["colorTableEdits"] = Value::Object(edits);
}
let settings = WebSettings::from_params(&full, "preview").map_err(|e| e.to_string())?;
let rgba = if settings.color_table_edits.is_empty() || !settings.format.indexed() {
@@ -154,13 +159,12 @@ mod tests {
let ctx = egui::Context::default();
let key = egui::Id::unique("test-web-preview");
let px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]];
let run = |p: &Value| optimized(&ctx, key, "fixture", p, |_| Ok((px.clone(), 2, 1))).unwrap().rgba;
let p = json!({"format": "gif", "colorTable": ["#ff0000", "#0000ff"], "dither": "none"});
let run = |shifted: &[([u8; 3], [u8; 3])]| optimized(&ctx, key, "fixture", &p, shifted, |_| Ok((px.clone(), 2, 1))).unwrap().rgba;
let cached = || ctx.data(|d| d.get_temp::<(String, Arc<Optimized>)>(key.with("indexed-source"))).unwrap().1;
let mut p = json!({"format": "gif", "colorTable": ["#ff0000", "#0000ff"], "dither": "none"});
assert_eq!(run(&p), [255, 0, 0, 255, 0, 0, 255, 255]);
assert_eq!(run(&[]), [255, 0, 0, 255, 0, 0, 255, 255]);
let before = cached();
p["colorTableEdits"] = json!({"0": "#00ff00"});
assert_eq!(run(&p), [0, 255, 0, 255, 0, 0, 255, 255]);
assert_eq!(run(&[([255, 0, 0], [0, 255, 0])]), [0, 255, 0, 255, 0, 0, 255, 255], "red shifted to green");
assert!(Arc::ptr_eq(&before, &cached()), "picker drag must not re-encode");
}
+6 -2
View File
@@ -18,6 +18,7 @@ use craft::ui::dialog::{DialogId, dialog_id};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft::ui::runtime::env::{Env, Label, UnitKind};
use craft::ui::runtime::requests::PathKind;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::text::NumberField;
use photocraft_doc::Document;
use photocraft_engine::color_cmds::ColorSettings;
@@ -581,8 +582,10 @@ fn builder(
dialog = dialog.canvas(canvas);
}
if key == "image.mode.colorTable" {
dialog = dialog
.extra_buttons(vec![("load".to_owned(), Label::from(tl!("Load…").to_string())), ("save".to_owned(), Label::from(tl!("Save…").to_string()))]);
dialog = dialog.extra_buttons(vec![
("load".to_owned(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
("save".to_owned(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
]);
}
dialog
}
@@ -1140,6 +1143,7 @@ pub(crate) fn ask_displace_map(app: &mut PhotocraftApp, command: String, result:
app.ask_file(request, move |app, picked| {
let path = match picked {
Picked::Paths(paths) => paths.into_iter().next().ok_or("no displacement map was chosen")?,
Picked::Saved { .. } => return Err(crate::file_dialog::UNEXPECTED.into()),
Picked::Cancelled | Picked::Downloaded(_) => return Err(crate::file_dialog::CANCELLED.into()),
Picked::Unavailable(error) | Picked::Failed(error) => return Err(error),
Picked::Contents(_) => return Err("open the displacement map as a document, then choose it as the Map Document".into()),
@@ -8,7 +8,7 @@
//! the pointer is a small square there, and a press centres the pane on that document point ([`centre_on`], #9648).
use craft::ui::dialog::{DialogId, StackDialog as _};
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use craft::ui::patterns::form_dialogs::{HostedParamDialog, PreviewState};
use egui::load::SizedTexture;
use egui::{Pos2, pos2};
use photocraft_doc::Document;
@@ -77,7 +77,7 @@ pub(crate) fn feed(app: &mut PhotocraftApp, ctx: &egui::Context) {
for id in ids {
let Some(picture) = picture(app, ctx, id) else { continue };
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(id) {
dialog.set_preview(picture);
dialog.set_preview(picture.map(PreviewState::Ready));
}
}
}
+6 -2
View File
@@ -1,9 +1,10 @@
//! ⌘F command palette: the framework's `CommandPalette` over every menu command and tool.
use craft::ui::contract::Bind;
use craft::ui::menu::HelpEntry;
use craft::ui::menu::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft::ui::patterns::panels::CommandPalette;
use craft::ui::runtime::commands::CommandRef;
use craft::ui::runtime::env::Env;
use crate::PhotocraftApp;
use crate::state::Tool;
@@ -40,8 +41,11 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
let ctx = ui.ctx().clone();
let listed = entries(app, &ctx);
let env = Env::of(ui);
let view = env.view();
let index = SearchIndex::new(&view, &listed, &Synonyms::of(&view.words::<SearchWords>()));
let PaletteState { open, recents } = &mut app.ui.palette;
CommandPalette::new(tl!("Command Palette"), &listed, Bind::bound(open)).recents(Bind::bound(recents)).show(ui);
CommandPalette::new(tl!("Command Palette"), &listed, &index, Bind::bound(open)).recents(Bind::bound(recents)).show(ui);
}
/// Records `id` as the most recently run command. The palette records its own picks; this covers commands run from
+7 -7
View File
@@ -22,7 +22,7 @@ fn harness() -> Harness<'static, Box<PhotocraftApp>> {
h
}
/// The value field showing `value`: the options bar's Smoothing is the brush's only one at 10.
/// The value field showing `value`, unit included: the options bar's Smoothing is the brush's only one at 10 %.
fn field<'a>(h: &'a Harness<'_, Box<PhotocraftApp>>, value: &str) -> egui_kittest::Node<'a> {
h.query_all_by_role(Role::SpinButton).find(|n| n.value().as_deref() == Some(value)).unwrap()
}
@@ -50,12 +50,12 @@ fn view(h: &Harness<'_, Box<PhotocraftApp>>) -> (f32, [f32; 2]) {
fn the_wheel_over_a_field_steps_it_without_a_click() {
let mut h = harness();
let before = view(&h);
let at = field(&h, "10").rect().center();
let at = field(&h, "10 %").rect().center();
wheel(&mut h, at, 1.0, egui::Modifiers::NONE);
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("11")), "Smoothing stepped from 10 to 11");
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("11 %")), "Smoothing stepped from 10 to 11");
wheel(&mut h, at, 1.0, egui::Modifiers::SHIFT);
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("21")), "Shift: ten a notch");
assert!(!field(&h, "21").is_focused(), "hovering doesn't put the cursor in the field");
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("21 %")), "Shift: ten a notch");
assert!(!field(&h, "21 %").is_focused(), "hovering doesn't put the cursor in the field");
assert_eq!(view(&h), before, "the canvas didn't move");
}
@@ -70,7 +70,7 @@ const TAIL_STEPS: usize = 4;
fn canvas_pan(focus: bool, delta: egui::Vec2, modifiers: egui::Modifiers) -> (f32, [f32; 2]) {
let mut h = harness();
if focus {
field(&h, "10").click();
field(&h, "10 %").click();
h.run();
}
let canvas = egui::pos2(640.0, 500.0);
@@ -85,7 +85,7 @@ fn canvas_pan(focus: bool, delta: egui::Vec2, modifiers: egui::Modifiers) -> (f3
modifiers,
});
h.run_steps(TAIL_STEPS);
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("10")), "focus {focus}: the field wasn't stepped");
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.value().as_deref() == Some("10 %")), "focus {focus}: the field wasn't stepped");
let after = view(&h);
(after.0 / before.0, [after.1[0] - before.1[0], after.1[1] - before.1[1]])
}
+17 -7
View File
@@ -99,7 +99,7 @@ pub(crate) struct Pending {
/// The error of a cancelled dialog: not reported, since backing out is the user's choice.
pub(crate) const CANCELLED: &str = "cancelled";
const UNEXPECTED: &str = "the file dialog gave an unexpected answer";
pub(crate) const UNEXPECTED: &str = "the file dialog gave an unexpected answer";
/// The text of a chosen path. [`PhotocraftApp::ask_file`] has refused a path that is not valid
/// Unicode by the time an action sees it.
@@ -113,6 +113,7 @@ fn path_string(path: &Path) -> String {
fn path_strings(picked: &Picked) -> Vec<String> {
match picked {
Picked::Paths(paths) => paths.iter().map(|p| path_string(p)).collect(),
Picked::Saved { path, .. } => vec![path_string(path)],
Picked::Contents(_) | Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => Vec::new(),
}
}
@@ -125,7 +126,7 @@ impl PhotocraftApp {
/// Show a file dialog; `then` continues with the user's choice on a later frame (see the
/// module docs). Returns at once with `{"fileDialog": "open" | "folder" | "save"}`; `Err` while
/// one is open. `then` gets [`Picked::Paths`] (every path valid Unicode) or
/// one is open. `then` gets [`Picked::Paths`] or [`Picked::Saved`] (every path valid Unicode) or
/// [`Picked::Contents`]; Cancel ends the action with [`CANCELLED`] and an unavailable dialog
/// with its reason, neither reaching `then`.
pub(crate) fn ask_file(&mut self, request: PickRequest, then: impl FnOnce(&mut Self, Picked) -> Result<Value, String> + 'static) -> Result<Value, String> {
@@ -148,6 +149,10 @@ impl PhotocraftApp {
}
then(app, Picked::Paths(paths))
}
Picked::Saved { path, file_type } => {
path_text(&path, saving)?;
then(app, Picked::Saved { path, file_type })
}
picked @ Picked::Contents(_) => then(app, picked),
});
self.file_dialog = Some(self.start_pick(request, then)?);
@@ -343,7 +348,7 @@ impl PhotocraftApp {
app.open_paths_in_order(&path_strings(&picked));
}
Picked::Contents(files) => app.open_contents(files),
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(UNEXPECTED.into()),
Picked::Saved { .. } | Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(UNEXPECTED.into()),
}
Ok(Value::Null)
})
@@ -438,7 +443,11 @@ impl PhotocraftApp {
/// always add the suggested extension to a bare name (the format follows the extension).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn pump_files(&mut self, parent: &eframe::Frame) {
let policy = craft::dialogs::service::ExtensionPolicy { lowercase: self.session.prefs().file_handling.lowercase_extension, add_suggested: true };
let policy = craft::dialogs::service::ExtensionPolicy {
lowercase: self.session.prefs().file_handling.lowercase_extension,
add_suggested: true,
picked_type: true,
};
// PLAN: `Services::file_panels: Option<craft::dialogs::FilePanels>` is dialogs-w59's field.
let Some(panels) = self.services.file_panels.as_mut() else { return };
panels.set_extension_policy(policy);
@@ -492,7 +501,8 @@ fn web_picked(answer: Option<FileDialogAnswer>) -> Picked {
match answer {
None => Picked::Cancelled,
Some(FileDialogAnswer::Paths(paths)) => Picked::Paths(paths.into_iter().map(PathBuf::from).collect()),
Some(FileDialogAnswer::SaveTo(path) | FileDialogAnswer::FolderTo(path)) => Picked::Paths(vec![PathBuf::from(path)]),
Some(FileDialogAnswer::SaveTo(path)) => Picked::Saved { path: PathBuf::from(path), file_type: None },
Some(FileDialogAnswer::FolderTo(path)) => Picked::Paths(vec![PathBuf::from(path)]),
Some(FileDialogAnswer::Contents(name, bytes)) => Picked::Contents(vec![(name, bytes)]),
Some(FileDialogAnswer::ContentsMany(files)) => Picked::Contents(files),
Some(FileDialogAnswer::Unavailable(why)) => Picked::Unavailable(why),
@@ -528,7 +538,7 @@ fn read_picked(picked: Picked) -> Result<(String, Vec<u8>), String> {
match picked {
Picked::Contents(files) => files.into_iter().next().ok_or_else(|| CANCELLED.into()),
Picked::Paths(paths) => read_path(path_string(paths.first().ok_or(CANCELLED)?)),
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => Err(UNEXPECTED.into()),
Picked::Saved { .. } | Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => Err(UNEXPECTED.into()),
}
}
@@ -563,7 +573,7 @@ fn picked_files(picked: Picked) -> Result<Vec<PickedFile>, String> {
let files: Vec<PickedFile> = match picked {
Picked::Paths(paths) => paths.iter().map(|p| PickedFile::Path(path_string(p))).collect(),
Picked::Contents(files) => files.into_iter().map(|(name, bytes)| PickedFile::Contents(name, bytes)).collect(),
Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(UNEXPECTED.into()),
Picked::Saved { .. } | Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) | Picked::Downloaded(_) => return Err(UNEXPECTED.into()),
};
if files.is_empty() {
return Err(CANCELLED.into());
+9 -10
View File
@@ -27,11 +27,10 @@ fn saved_language(files: &MemoryFiles) -> Value {
toml::from_str::<Value>(&text).expect("saved TOML")["interface"]["language"].clone()
}
/// The File menu's title as the menu bar draws it in `lang`: the translation, plus the English access key where it
/// has no Latin letter of its own ("文件(F)", #5863). Read from the drawn bar, whose rule spans all its titles.
/// The File menu's translated title in `lang`, as a bare menu bar draws it (its first text). The app's own bar may
/// follow it with the English access key where the language shows one ("ファイル(F)", #5863), so the tests look for
/// a drawn text that starts with it.
fn file_title(lang: Lang) -> String {
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
with_language(lang, || {
let app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
let mut h = egui_kittest::Harness::builder()
@@ -39,7 +38,7 @@ fn file_title(lang: Lang) -> String {
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::menus::menu_bar(app, ui), app);
h.run_steps(2);
h.query_all_by_role(Role::MenuItem).next().and_then(|node| node.accesskit_node().label()).expect("the bar's first title")
drawn_text(&h).into_iter().next().expect("the bar's first title")
})
}
@@ -90,7 +89,7 @@ fn azerbaijani_draw_after_switching_and_restore_after_restart() {
h.run_steps(4);
assert_eq!(current(), lang(code));
assert_eq!(tr(current(), "File"), file);
assert!(drawn_text(&h).iter().any(|text| *text == file_title(lang(code))));
assert!(drawn_text(&h).iter().any(|text| text.starts_with(&file_title(lang(code)))));
assert_eq!(saved_language(&files), code);
h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": "en"})).expect("switch back");
h.run_steps(4);
@@ -105,7 +104,7 @@ fn azerbaijani_draw_after_switching_and_restore_after_restart() {
let restarted = harness_with_services(services_on(&files));
assert_eq!(restarted.state().session.prefs().interface.language, code);
assert_eq!(current(), lang(code));
assert!(drawn_text(&restarted).iter().any(|text| *text == file_title(lang(code))));
assert!(drawn_text(&restarted).iter().any(|text| text.starts_with(&file_title(lang(code)))));
});
}
@@ -239,7 +238,7 @@ fn first_launch_renders_the_system_language_without_overwriting_auto() {
let h = harness();
assert_eq!(h.state().session.prefs().interface.language, "auto");
assert_eq!(current(), lang(code), "{tags:?}");
assert!(drawn_text(&h).iter().any(|text| *text == file_title(lang(code))), "first-launch menu: {tags:?}");
assert!(drawn_text(&h).iter().any(|text| text.starts_with(&file_title(lang(code)))), "first-launch menu: {tags:?}");
});
});
}
@@ -267,7 +266,7 @@ fn an_explicit_language_survives_restart_on_a_different_system_language() {
let h = harness_with_services(services_on(&files));
assert_eq!(h.state().session.prefs().interface.language, "ko");
assert_eq!(current(), lang("ko"));
assert!(drawn_text(&h).iter().any(|text| *text == file_title(lang("ko"))));
assert!(drawn_text(&h).iter().any(|text| text.starts_with(&file_title(lang("ko")))));
});
});
}
@@ -289,7 +288,7 @@ fn a_control_request_changes_the_drawing_language_in_the_same_frame() {
h.step();
assert_eq!(reply.try_recv().expect("response")["ok"], true);
assert_eq!(current(), lang(code));
assert!(drawn_text(&h).iter().any(|text| *text == file_title(lang(code))), "the menu must change in this frame: {code}");
assert!(drawn_text(&h).iter().any(|text| text.starts_with(&file_title(lang(code)))), "the menu must change in this frame: {code}");
assert!(std::sync::Arc::ptr_eq(&document, &h.state().session.active().expect("document").doc), "switching language must preserve the document");
}
assert!(h.state_mut().run("prefs.set", json!({"path": "interface.language", "value": []})).is_err());
+1 -1
View File
@@ -25,7 +25,7 @@ fn zoom(h: &Harness<'static, Box<PhotocraftApp>>) -> f32 {
/// The highest zoom the ladder allows.
fn max_zoom() -> f32 {
craft::behavior::canvas::ZoomLadder::MAX as f32
craft::behavior::canvas::ZoomScheme::PHOTOSHOP.max as f32
}
/// The values of the dialog opened last, as automation lists them (`ui.inspect`).
@@ -1,4 +1,4 @@
use craft::behavior::canvas::ZoomLadder;
use craft::behavior::canvas::ZoomScheme;
use craft::ui::docking::{ArrangeCommands, ArrangeSpace, Arranged, arrange as run_arrange};
use photocraft_doc::DocId;
@@ -137,7 +137,7 @@ fn match_views(app: &mut PhotocraftApp, zoom: bool, loc: bool, rot: bool) -> Res
if zoom {
let [w, h] = sizes.get(d).copied().unwrap_or(v.doc_size);
v.request_zoom_animation(animated_zoom);
v.zoom = ZoomLadder::clamp(f64::from(src.zoom), craft::behavior::kurbo::Size::new(f64::from(w), f64::from(h))) as f32;
v.zoom = ZoomScheme::PHOTOSHOP.clamp(f64::from(src.zoom), craft::behavior::kurbo::Size::new(f64::from(w), f64::from(h))) as f32;
}
if loc {
v.center = src.center;
+1 -1
View File
@@ -352,7 +352,7 @@ fn arrange_layouts_floating_windows_and_matching() {
/// below the zoom at which its shorter side is 2 px, even when the source view is lower.
#[test]
fn match_zoom_clamps_to_each_documents_zoom_range() {
let lowest = craft::behavior::canvas::ZoomLadder::min(craft::behavior::kurbo::Size::new(10.0, 10.0)) as f32;
let lowest = craft::behavior::canvas::ZoomScheme::PHOTOSHOP.min(craft::behavior::kurbo::Size::new(10.0, 10.0)) as f32;
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 10, "height": 10})).unwrap();
app.run("file.new", json!({"width": 2000, "height": 2000})).unwrap();
@@ -1,5 +1,5 @@
//! The Mixer Brush's Load Solid Colors Only (#11952). On, ⌥-click loads the one colour under the
//! hotspot (red/green edge at 200,300 → 30,180,60), the swatch shows it and the next stroke paints
//! hotspot (the first green pixel, 200,300 → 30,180,60), the swatch shows it and the next stroke paints
//! it; off, ⌥-click loads the tip image as before.
use egui::Modifiers;
@@ -42,7 +42,8 @@ fn level(c: [f32; 4]) -> [i32; 4] {
fn with_it_on_alt_click_loads_the_colour_under_the_hotspot_and_the_next_stroke_paints_it() {
let mut app = app();
app.run("tools.setBrush", json!({"brush": {"mixer": {"solidColorsOnly": true, "wet": 0.0}, "size": 20, "hardness": 1.0}})).unwrap();
alt_click(&mut app, 200.0, 300.0);
// The middle of the first green pixel: a click right on the edge can map back a hair short of it.
alt_click(&mut app, 200.5, 300.0);
let mixer = &app.session.tools.mixer;
assert_eq!(mixer.reservoir.map(level), Some(level(GREEN)), "{mixer:?}");
assert!(mixer.spatial.is_none(), "a plain colour, not the tip image");
+2
View File
@@ -46,6 +46,8 @@ mod library_tests;
#[cfg(test)]
mod menu_tests;
#[cfg(test)]
mod missing_layer_tests;
#[cfg(test)]
mod panel_menu_tests;
#[cfg(test)]
mod playback_tests;
@@ -72,6 +72,7 @@ pub(super) fn load_dialog(app: &mut PhotocraftApp) -> Result<Value, String> {
let files: Vec<(String, Option<Vec<u8>>)> = match picked {
Picked::Paths(paths) => paths.into_iter().map(|path| (path.to_string_lossy().into_owned(), None)).collect(),
Picked::Contents(files) => files.into_iter().map(|(name, bytes)| (name, Some(bytes))).collect(),
Picked::Saved { .. } => return Err(crate::file_dialog::UNEXPECTED.into()),
Picked::Cancelled | Picked::Downloaded(_) => return Err(crate::file_dialog::CANCELLED.into()),
Picked::Unavailable(why) | Picked::Failed(why) => return Err(why),
};
@@ -125,6 +125,7 @@ pub(super) fn replace(app: &mut PhotocraftApp) -> Result<Value, String> {
let (name, bytes) = files.into_iter().next().ok_or(crate::file_dialog::CANCELLED)?;
(name, bytes, None)
}
Picked::Saved { .. } => return Err(crate::file_dialog::UNEXPECTED.into()),
Picked::Cancelled | Picked::Downloaded(_) => return Err(crate::file_dialog::CANCELLED.into()),
Picked::Unavailable(why) | Picked::Failed(why) => return Err(why),
};
@@ -0,0 +1,326 @@
//! #10769 "Playing on another document": a step that names a layer the playing document does not
//! have stops with a message asked of the person: Continue skips the step, Stop ends the playback,
//! and nothing done so far is undone. Measured in the reference application
//! (docs/atn.md › Playing on another document).
use super::stop_tests::{answer, assert_idle, count, stop_prompt};
use super::*;
use craft::ui::dialog::StandardPrompt;
use photocraft_engine::actions_cmds::ActionStep;
/// A document with layers X, Y and Z: none of the names a recording made over A, B, C refers to.
fn missing_name_app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 8, "height": 6, "background": "white"})).unwrap();
for name in ["X", "Y", "Z"] {
app.run("layer.new.layer", json!({"name": name})).unwrap();
}
app
}
/// `On B`: Prefix, a Select of the absent layer B, Suffix.
fn named_select_action(app: &mut PhotocraftApp) {
app.session
.actions_mut()
.list
.push(Action::new(
"On B",
vec![
ActionStep::new("layer.new.layer", json!({"name": "Prefix"})),
ActionStep::new("layer.select", json!({"name": "B"})),
ActionStep::new("layer.new.layer", json!({"name": "Suffix"})),
],
))
.unwrap();
}
/// How many standard prompts the app holds open.
fn prompts_open(app: &PhotocraftApp) -> usize {
let host = &app.framework.dialogs;
host.stack().ids().filter(|id| host.get_by_id::<StandardPrompt>(*id).is_some()).count()
}
#[test]
fn a_step_naming_a_missing_layer_asks_continue_or_stop() {
let mut app = missing_name_app();
named_select_action(&mut app);
let v = play(&mut app, &json!({"action": "On B"})).unwrap();
assert_eq!(v["failed"]["step"], 1, "{v}");
assert_eq!(prompts_open(&app), 1, "the stopped step shows its message with the choice");
assert_eq!(count(&app, "Prefix"), 1, "the step already applied stays applied");
assert_eq!(count(&app, "Suffix"), 0, "playback stops at the step naming B");
let dialog = stop_prompt(&app);
answer(&mut app, dialog, true).unwrap();
assert_eq!(count(&app, "Suffix"), 1, "Continue skips the missing layer's step and finishes the action");
assert!(!app.ui.status_error, "{}", app.ui.status);
assert_idle(&app);
// The whole Play, across the message, stays one history state (as a Stop message's does).
assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Action: On B"), "{}", app.ui.status);
app.session.undo();
assert_eq!(count(&app, "Prefix"), 0, "one undo takes back the whole play");
assert_eq!(count(&app, "Suffix"), 0);
}
#[test]
fn stop_on_the_message_ends_the_playback_with_nothing_undone() {
let mut app = missing_name_app();
named_select_action(&mut app);
let v = play(&mut app, &json!({"action": "On B"})).unwrap();
assert_eq!(v["failed"]["step"], 1, "{v}");
let dialog = stop_prompt(&app);
answer(&mut app, dialog, false).unwrap();
assert_eq!(count(&app, "Prefix"), 1, "Stop undoes nothing");
assert_eq!(count(&app, "Suffix"), 0);
assert_idle(&app);
// The edits so far stay one history state behind the message, as Continue's do: Stop undoes
// nothing itself, and one undo takes the whole play back (as a Stop message's does).
assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Action: On B"), "{}", app.ui.status);
assert!(app.session.undo(), "one undo takes back the whole play");
assert_eq!(count(&app, "Prefix"), 0);
}
/// A Play over a set of actions: Continue finishes the failed action, then the set goes on.
#[test]
fn continue_carries_the_rest_of_a_set_play() {
let mut app = missing_name_app();
named_select_action(&mut app);
app.session.actions_mut().list.push(Action::new("Next", vec![ActionStep::new("layer.new.layer", json!({"name": "Next layer"}))])).unwrap();
let v = play_targets(&mut app, &[0, 1], 0, 0).unwrap().unwrap();
assert_eq!(v["failed"]["step"], 1, "{v}");
assert_eq!(prompts_open(&app), 1);
let dialog = stop_prompt(&app);
answer(&mut app, dialog, true).unwrap();
assert_eq!(count(&app, "Suffix"), 1);
assert_eq!(count(&app, "Next layer"), 1, "the actions Play queued after it still play");
assert_idle(&app);
}
/// A person's Play of an action that calls another: the called action's step naming a missing
/// layer asks its message, and Continue ends the child there and lets the caller go on
/// (the pause carries its callers, as a Stop message's does).
#[test]
fn a_called_actions_missing_layer_step_asks_and_continues_into_its_caller() {
let mut app = missing_name_app();
app.session
.actions_mut()
.list
.push(Action::new("Child B", vec![ActionStep::new("layer.select", json!({"name": "B"})), ActionStep::new("layer.new.layer", json!({"name": "Tail"}))]))
.unwrap();
app.session
.actions_mut()
.list
.push(Action::new(
"Caller",
vec![ActionStep::new("actions.play", json!({"action": "Child B"})), ActionStep::new("layer.new.layer", json!({"name": "After"}))],
))
.unwrap();
let v = play(&mut app, &json!({"action": "Caller"})).unwrap();
assert!(v.get("failed").is_none(), "the caller waits at its child's message: {v}");
assert_eq!(prompts_open(&app), 1);
let dialog = stop_prompt(&app);
answer(&mut app, dialog, true).unwrap();
assert_eq!(count(&app, "Tail"), 1, "Continue skips the failed step inside the child");
assert_eq!(count(&app, "After"), 1, "and the caller goes on");
assert_idle(&app);
}
/// Agent Play stays headless: no message opens; the failed step is reported as it is today. Both
/// non-interactive flags are tested, not just claimed: `automation_input` for synthetic input, and
/// `programmatic_playback`, which the control channel's `engine.execute` sets around its call.
#[test]
fn automation_playback_keeps_the_headless_failure() {
for automated in ["automation_input", "programmatic_playback"] {
let mut app = missing_name_app();
named_select_action(&mut app);
match automated {
"automation_input" => app.automation_input = true,
_ => app.programmatic_playback = true,
}
let v = play(&mut app, &json!({"action": "On B"})).unwrap();
assert_eq!(v["failed"]["step"], 1, "{automated}: {v}");
assert_eq!(prompts_open(&app), 0, "{automated}: the agent gets the failure, not the message");
assert_eq!(count(&app, "Suffix"), 0, "{automated}");
assert_idle(&app);
}
}
/// The messages, as measured: the reference reports a Select of a missing layer as the command
/// being unavailable, and other named steps as the layer object being unavailable.
#[test]
fn the_message_names_the_command_or_the_missing_layer() {
let app = missing_name_app();
let action = Action::new(
"Forms",
vec![
ActionStep::new("layer.select", json!({"name": "B"})),
ActionStep::new("layer.select", json!({"layer": "B"})),
ActionStep::new("layer.setProps", json!({"visible": false, "_actionLayer": {"name": "B", "ordinal": 0}})),
ActionStep::new("layer.translate", json!({"dx": 3.0, "dy": 10.0, "layer": "B"})),
ActionStep::new("select.loadSelection", json!({"channel": "transparency", "layer": {"name": "B"}})),
],
);
let message =
|step: usize| runner::missing_layer_prompt(&app, &action, &json!({"step": step, "id": action.steps[step].command, "error": "x"})).map(|(m, _)| m);
assert_eq!(message(0).as_deref(), Some("The command 'Select' is not currently available"));
assert_eq!(message(1).as_deref(), Some("The command 'Select' is not currently available"));
let object = || Some("The object 'Layer \"B\"' is not currently available".to_string());
assert_eq!(message(2), object());
assert_eq!(message(3), object());
assert_eq!(message(4), object(), "a source layer named as an object");
}
/// Neighbours keep today's status-bar failure: steps naming no layer (a target step, a numeric id
/// kept for an ambiguous name, a rename's new name, a layer-id list), a name the document has, and
/// a step index the action does not have.
#[test]
fn a_failure_that_names_no_layer_keeps_the_plain_report() {
let mut app = missing_name_app();
let plain = Action::new(
"Plain",
vec![
ActionStep::new("layer.setProps", json!({"opacity": 0.5})),
ActionStep::new("layer.delete", json!({"layer": 99})),
ActionStep::new("layer.setProps", json!({"name": "Fresh"})),
ActionStep::new("layer.select", json!({"layers": [1, 2]})),
ActionStep::new("layer.select", json!({"name": "Z"})),
],
);
for step in 0..5 {
assert_eq!(runner::missing_layer_prompt(&app, &plain, &json!({"step": step, "id": plain.steps[step].command, "error": "x"})), None, "step {step}");
}
assert_eq!(runner::missing_layer_prompt(&app, &plain, &json!({"step": 9, "id": "layer.select", "error": "x"})), None, "no such step");
app.session.actions_mut().list.push(plain).unwrap();
let v = play(&mut app, &json!({"action": "Plain"})).unwrap();
report_play(&mut app, &v);
assert_eq!(v["failed"]["step"], 1, "{v}");
assert_eq!(prompts_open(&app), 0, "the numeric id of an ambiguous name keeps today's failure report");
assert!(app.ui.status_error, "the status bar still shows the failure: {}", app.ui.status);
assert_idle(&app);
}
/// The presence test mirrors how the engine resolves a layer param: exact name, else the same name
/// whatever its case (engine `explicit_layer`). A step naming "background" over a document whose
/// layer is "Background" does find that layer, so a failure there is unrelated to a missing layer
/// and keeps today's plain failure: no message, no skip on Continue.
#[test]
fn a_name_the_document_has_in_another_case_is_not_missing() {
let mut app = missing_name_app();
let action = Action::new("Pass Through", vec![ActionStep::new("layer.setProps", json!({"layer": "background", "blend": "Pass Through"}))]);
let failed = json!({"step": 0, "id": "layer.setProps", "error": "Pass Through applies to groups only; layer 0 isn't one"});
assert_eq!(
runner::missing_layer_prompt(&app, &action, &failed),
None,
"the engine finds Background for `background`, so the ask would skip a step that can never pass"
);
app.session.actions_mut().list.push(action).unwrap();
let v = play(&mut app, &json!({"action": "Pass Through"})).unwrap();
report_play(&mut app, &v);
assert_eq!(v["failed"]["step"], 0, "{v}");
assert_eq!(prompts_open(&app), 0, "the setProps failure takes today's plain-failure path");
assert!(v["failed"]["error"].as_str().is_some_and(|error| error.contains("Pass Through")), "{v}");
assert!(app.ui.status_error, "the status bar shows the failure: {}", app.ui.status);
assert_idle(&app);
}
/// The other direction: the step records the exact-case name of a differently cased document.
#[test]
fn an_exact_case_name_on_a_lowercase_layer_is_not_missing() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 8, "height": 6})).unwrap();
app.run("layer.new.layer", json!({"name": "ink"})).unwrap();
let action = Action::new("Hide Ink", vec![ActionStep::new("layer.setProps", json!({"visible": false, "layer": "Ink"}))]);
let failed = json!({"step": 0, "id": "layer.setProps", "error": "x"});
assert_eq!(runner::missing_layer_prompt(&app, &action, &failed), None, "the engine finds `ink` for `Ink` by case");
}
/// The other two forms a recorded step can name its layer by are matched EXACTLY by the engine, so
/// a name differing only in case is a layer the playing document does not have: the visibility
/// step's `_actionLayer` goes through `playback_params`, at the recorded ordinal. Over a document
/// with layer `b` the step naming `B` stops there, and the person is asked rather than getting
/// today's plain failure (#10769 review).
#[test]
fn a_recorded_visibility_step_naming_the_layer_in_another_case_still_asks() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 8, "height": 6, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({"name": "b"})).unwrap();
let hide = ActionStep::new("layer.setProps", json!({"visible": false, "_actionLayer": {"name": "B", "ordinal": 0}}));
let suffix = ActionStep::new("layer.new.layer", json!({"name": "Suffix"}));
app.session.actions_mut().list.push(Action::new("Hide B", vec![hide, suffix])).unwrap();
let v = play(&mut app, &json!({"action": "Hide B"})).unwrap();
assert_eq!(v["failed"]["step"], 0, "{v}");
assert!(v["failed"]["error"].as_str().is_some_and(|error| error.contains("recorded layer `B`")), "the engine's exact lookup is what fails: {v}");
assert_eq!(prompts_open(&app), 1, "the name is missing for this step's kind, so the play asks");
let dialog = stop_prompt(&app);
answer(&mut app, dialog, true).unwrap();
assert_eq!(count(&app, "Suffix"), 1, "Continue skips the step and finishes the action");
let doc = app.session.active().unwrap().doc.clone();
assert!(doc.walk().into_iter().any(|(_, _, layer)| layer.name == "b" && layer.visible), "the step never hid the differently cased layer");
assert_idle(&app);
}
/// The same for a Select step: its `name` goes through `selection_target`, which matches the exact
/// name at `occurrence`, so over a document with `b` the step naming `B` asks with the Select
/// message instead of keeping a plain failure.
#[test]
fn a_select_step_naming_the_layer_in_another_case_still_asks() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 8, "height": 6, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({"name": "b"})).unwrap();
let select = ActionStep::new("layer.select", json!({"name": "B"}));
let suffix = ActionStep::new("layer.new.layer", json!({"name": "Suffix"}));
app.session.actions_mut().list.push(Action::new("On B", vec![select, suffix])).unwrap();
let v = play(&mut app, &json!({"action": "On B"})).unwrap();
assert_eq!(v["failed"]["step"], 0, "{v}");
assert_eq!(prompts_open(&app), 1, "the engine finds no `B` in this document, so the play asks");
let dialog = stop_prompt(&app);
answer(&mut app, dialog, true).unwrap();
assert_eq!(count(&app, "Suffix"), 1, "Continue skips the Select and finishes the action");
assert_idle(&app);
}
/// The ask stays a test of the NAME and its case, not of the recorded occurrence: a visibility step
/// naming a name the document has, at an ordinal past its last layer of that name, still fails in
/// the engine and keeps today's plain report. A pin, green before and after this change.
#[test]
fn a_name_the_document_has_at_another_occurrence_keeps_the_plain_report() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 8, "height": 6, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({"name": "B"})).unwrap();
let action = Action::new("Hide second B", vec![ActionStep::new("layer.setProps", json!({"visible": false, "_actionLayer": {"name": "B", "ordinal": 1}}))]);
let failed = json!({"step": 0, "id": "layer.setProps", "error": "recorded layer `B` does not exist"});
assert_eq!(runner::missing_layer_prompt(&app, &action, &failed), None, "the document has the name, only the recorded occurrence is missing");
app.session.actions_mut().list.push(action).unwrap();
let v = play(&mut app, &json!({"action": "Hide second B"})).unwrap();
assert_eq!(v["failed"]["step"], 0, "{v}");
assert_eq!(prompts_open(&app), 0, "an ordinal past the last layer of that name keeps today's plain failure");
assert_idle(&app);
}
/// A player refusal is reported at the step Play starts at, under the Play label — not under the
/// refused step's own command. When that starting step is one that names a layer, the report must
/// not be read as a missing layer: the ask only follows a failure whose id is the step's command,
/// so a refusal keeps its plain failure report and Continue is never offered on it. (The engine's
/// `playback_plan` pre-refuses a recursion or a 17th level at the calling step, so this report
/// shape is pinned at the ask rather than reproduced through a playback.)
#[test]
fn a_refusal_report_at_a_layer_naming_start_step_is_not_the_ask() {
let mut app = missing_name_app();
app.session
.actions_mut()
.list
.push(Action::new(
"Starts on B",
vec![ActionStep::new("layer.select", json!({"name": "B"})), ActionStep::new("layer.new.layer", json!({"name": "Suffix"}))],
))
.unwrap();
let action = app.session.actions().list.action(0).unwrap().clone();
let refused = json!({"step": 0, "id": "actions.play", "error": "action nesting exceeds 16 levels"});
assert_eq!(
runner::missing_layer_prompt(&app, &action, &refused),
None,
"a refusal must not be reported as a missing layer, and Continue must not skip from it"
);
// The step's own failure, same index, does ask: only the id changed.
let own = json!({"step": 0, "id": "layer.select", "error": "no layer named \"B\""});
assert_eq!(runner::missing_layer_prompt(&app, &action, &own).as_ref().map(|(m, _)| m.as_str()), Some("The command 'Select' is not currently available"));
}
+125 -8
View File
@@ -35,7 +35,7 @@ pub(crate) fn play_targets(app: &mut PhotocraftApp, targets: &[usize], from: usi
o.insert("ran".into(), json!(ran));
}
last = Some(v);
if let Some(dialog) = paused.filter(|_| !failed) {
if let Some(dialog) = paused {
// As they are now, not by index: the list can be reordered while the dialog is open
// (`actions.move`), and one deleted and made again under its name isn't the same action.
let list = &app.session.actions().list;
@@ -287,10 +287,9 @@ enum Called {
/// paused playback's [`PausedPlayback::callers`], so it continues after the called action) or a
/// silent stop end the caller there.
fn called(app: &mut PhotocraftApp, caller: &str, i: usize, id: &str, value: &Value, target: Option<photocraft_doc::DocId>) -> Called {
if let Some(error) = actions_cmds::nested_failure(id, value).or_else(|| actions_cmds::save_target_closed(&app.session, id, target)) {
// Keep the same child-result detail as headless Actions and Scripts.
return Called::Failed(error, Some(value.clone()));
}
// A child that waits at a dialog carries its caller, even when its result also reports the
// failure that opened the Continue / Stop message (#10769): the pause is checked first so the
// caller goes on after the answer instead of failing here.
if let Some(inner) = value.get("paused").filter(|p| p.is_object()) {
if let Some(token) = waiting_dialog(inner).and_then(|dialog| paused_token(app, dialog))
&& let Some(entry) = app.paused_playbacks.paused.get_mut(&token)
@@ -302,6 +301,10 @@ fn called(app: &mut PhotocraftApp, caller: &str, i: usize, id: &str, value: &Val
}
return Called::Paused(inner.clone());
}
if let Some(error) = actions_cmds::nested_failure(id, value).or_else(|| actions_cmds::save_target_closed(&app.session, id, target)) {
// Keep the same child-result detail as headless Actions and Scripts.
return Called::Failed(error, Some(value.clone()));
}
if matches!(id, "actions.play" | "actions.conditional")
&& let Some(stop) = value.get("stopped").filter(|s| s.is_object())
{
@@ -320,6 +323,92 @@ fn failure(step: usize, id: &str, error: &str, result: Option<Value>) -> Value {
failed
}
/// The message and resume step for a failed step of `action` that names a layer the playing
/// document does not have: the Continue / Stop the reference application shows when an action
/// plays on a document without the recorded names (#10769, docs/atn.md › Playing on another
/// document). It reports a Select of a missing layer as the command being unavailable, and steps
/// that name a layer as the layer object being unavailable. The ask also fires when the layer was
/// deleted from the original document: the test is against the playing document as it stands, not
/// against names it never had. `None` keeps today's plain failure: steps naming no layer (target
/// steps, numeric ids kept for ambiguous names, a rename's new name), names the playing document
/// can resolve for that step's own selector kind, as the engine's lookup for that form does (the
/// step failed for another reason), failures
/// reported for a step other than the one named in them (a player refusal), and step indexes the
/// action does not have.
pub(super) fn missing_layer_prompt(app: &PhotocraftApp, action: &Action, failed: &Value) -> Option<(String, usize)> {
let index = failed.get("step").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok())?;
let step = action.steps.get(index)?;
// Only a failure reported for this step itself: the player's refusals come back at the step
// Play starts at, under the Play label (`actions.play`), and must not be read as an ask.
if failed.get("id").and_then(Value::as_str) != Some(step.command.as_str()) {
return None;
}
let selector = named_step_layer(&step.command, &step.params)?;
let name = selector.name();
let doc = &app.session.active()?.doc;
// The presence test follows the lookup THIS kind uses in the engine. A `layer` param goes
// through `explicit_layer`: the exact name, else the same name whatever its case, so a step
// naming "background" finds a "Background" layer and its failure is unrelated to a missing
// layer. A Select step's `name` (`selection_target`) and a recorded visibility step's
// `_actionLayer` (`playback_params`) are matched exactly, so over a document holding "b" the
// step naming "B" is a layer that document does not have and the ask follows the failure.
let exact = |want: &str| doc.walk().into_iter().any(|(_, _, layer)| layer.name == want);
let resolved = exact(name) || selector.folds_case() && doc.walk().into_iter().any(|(_, _, layer)| layer.name.to_lowercase() == name.to_lowercase());
if resolved {
return None;
}
let message = if step.command == "layer.select" {
tl!("The command 'Select' is not currently available").to_string()
} else {
crate::i18n::fmt(tl!("The object 'Layer \"{name}\"' is not currently available"), &[("name", name)])
};
Some((message, index.saturating_add(1)))
}
/// The layer a recorded step names, as the kind of selector it is: a `layer` the recorder made
/// into a name or a source layer's `{"name": …}` object, a Select step's `name`, and a visibility
/// step's recorded target. A numeric `layer` names no layer: the recorder kept that id for an
/// ambiguous name.
fn named_step_layer<'a>(id: &str, params: &'a Value) -> Option<StepLayer<'a>> {
if let Some(layer) = params.get("layer")
&& let Some(name) = layer.as_str().or_else(|| layer.get("name").and_then(Value::as_str))
{
return Some(StepLayer::Param(name));
}
if id == "layer.select" {
return params.get("name").and_then(Value::as_str).map(StepLayer::SelectName);
}
params.get("_actionLayer").and_then(|target| target.get("name")).and_then(Value::as_str).map(StepLayer::Recorded)
}
/// The kind of layer selector a recorded step carries. Each form is resolved by its own engine
/// lookup, and only some of those lookups fall back to a case-insensitive name match, so the
/// missing-layer ask tests presence per kind rather than with one rule for every name.
enum StepLayer<'a> {
/// A `layer` param: a name string or a source layer's `{"name": …}` object, resolved by
/// `explicit_layer` (the exact name, else the same name whatever its case).
Param(&'a str),
/// A Select step's `name`, resolved by `selection_target`: the exact name, at `occurrence`.
SelectName(&'a str),
/// A recorded visibility step's `_actionLayer`, resolved by `playback_params`: the exact name,
/// at the recorded ordinal.
Recorded(&'a str),
}
impl<'a> StepLayer<'a> {
/// The name the step gives its layer, whatever its kind.
fn name(&self) -> &'a str {
match self {
Self::Param(name) | Self::SelectName(name) | Self::Recorded(name) => name,
}
}
/// Whether this kind's engine lookup also accepts the name in another case.
fn folds_case(&self) -> bool {
matches!(self, Self::Param(_))
}
}
/// How long Step by Step or Pause For waits after step `i` of `action`, or `None` when it goes on at
/// once: no pacing is set, or no enabled step follows.
fn wait_after(app: &PhotocraftApp, action: &Action, i: usize) -> Option<Duration> {
@@ -564,6 +653,10 @@ fn play_steps(
if let Some(f) = report.failed {
failed = Some(failure(f.step, &f.command, &f.message, detail));
} else if let Some(refusal) = &report.refused {
// A refusal is the whole call's, not one step's: it is reported at the step Play
// starts at, under the Play label. `playback_plan` pre-refuses a recursion or a 17th
// level at the calling step (which fails as the call's own step, with that label), so
// the player's refusal is what a resumed or rebased playback reports.
failed = Some(failure(from, "actions.play", &refusal_text(refusal), None));
} else if report.waiting {
if let (Some(at), Some(wait)) = (report.paused_at, wait) {
@@ -576,11 +669,30 @@ fn play_steps(
stopped = ending;
}
}
let history = if failed.is_none() && paused.is_some() { actions_cmds::suspend_history(&mut app.session) } else { None };
// "Playing on another document": when a step that names a layer fails because the playing
// document does not have it, the playback stops there and asks a person Continue (skip the
// step, play on from the next) or Stop (#10769). The edits so far stay applied. Agents and
// paced failures that name no missing layer keep today's plain failure report.
let mut prompted = false;
if let Some(f) = failed.as_ref().filter(|_| interactive && paused.is_none() && stopped.is_none())
&& let Some((message, from)) = missing_layer_prompt(app, &action, f)
{
let token = app.paused_playbacks.pause(action.name.clone(), from, app.session.authorize);
let dialog = dialogs::open_stop_message(app, &message, true, token);
if let Some(entry) = app.paused_playbacks.paused.get_mut(&token) {
entry.allow_continue = true;
entry.dialog = Some(dialog);
// Continue skips the failed step: the pause's own step never ran and is not counted.
entry.timed = true;
}
paused = Some(json!({"step": f.get("step"), "id": f.get("id"), "dialog": dialog.value()}));
prompted = true;
}
let history = if (failed.is_none() || prompted) && paused.is_some() { actions_cmds::suspend_history(&mut app.session) } else { None };
actions_cmds::finish_playback(&mut app.session, None, &action, from);
match paused.as_ref().and_then(waiting_dialog).cloned() {
// Paused for a dialog: the call goes on after it, so recording stays suspended.
Some(dialog) if failed.is_none() => {
Some(dialog) if failed.is_none() || prompted => {
let token = paused_token(app, &dialog);
let entry = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t));
match entry {
@@ -603,6 +715,9 @@ fn play_steps(
}
}
Ok(match (failed, paused, stopped) {
// The report of a Continue / Stop ask keeps both: the failed step and the message the
// playback waits at, so `play_targets` carries the rest of a set like a dialog pause does.
(Some(f), Some(p), _) if prompted => json!({"action": action.name, "ran": ran, "failed": f, "paused": p}),
(Some(f), _, _) => json!({"action": action.name, "ran": ran, "failed": f}),
(None, Some(p), _) => json!({"action": action.name, "ran": ran, "paused": p}),
(None, None, Some(s)) => json!({"action": action.name, "ran": ran, "stopped": s}),
@@ -636,7 +751,9 @@ pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) {
app.ui.status_error = false;
return;
}
if let Some(paused) = v.get("paused").filter(|p| p.is_object()) {
// A Continue / Stop ask carries `paused` for its message but reports the failed step below:
// the failure line, not "waiting for its dialog", stands behind the message.
if let Some(paused) = v.get("paused").filter(|p| p.is_object() && v.get("failed").is_none()) {
if paused.get("dialog").and_then(Value::as_str) == Some(playback::PLAYBACK_TIMER) {
// Step by Step or Pause For between two steps: the last report comes at the end.
return;
@@ -514,7 +514,7 @@ fn view_menu_commands_record_append_and_replay_after_resize() {
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 100.0));
let mut camera = app.ui.views[idx].canvas_view(rect, 1.0, false, 1.0);
for request in &app.ui.views[idx].pending {
request.command().apply(&mut camera, &target, None, 1.0);
request.command().apply(&mut camera, &target, None, 1.0, &craft::behavior::canvas::ZoomScheme::PHOTOSHOP);
}
app.ui.views[idx].set_from(&camera, 1.0);
assert_eq!(app.ui.views[idx].zoom, 0.75);
@@ -10,8 +10,8 @@ use craft::draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushRowPaint, B
use craft::keymap::Mods;
use craft::ui::contract::{Bind, MemoProps, MemoView, Outbox, PlainData, ReorderMove, Tracked, bind_tracked};
use craft::ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetView};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::primitives::textures::TextureCache;
use craft::ui::primitives::{ContentPainterCx, FacePaint};
use craft::ui::runtime::env::Env;
use egui::{ColorImage, Pos2, Rect, pos2};
use photocraft_engine::BrushSettings;
@@ -89,22 +89,23 @@ fn picture(cx: &ContentPainterCx, rect: Rect, key: impl Hash + 'static, image: i
fn paint_of(b: &BrushSettings) -> BrushRowPaint {
let brush = b.clone();
let stroke_sig = brush_preview::preview_sig(b);
BrushRowPaint::new(tip_paint(&b.tip, (b.hardness, b.angle, b.roundness)), move |cx, rect| {
let stroke = FacePaint::new(stroke_sig, move |cx, rect| {
let color = Tokens::get(cx.painter.ctx()).text;
let size = [rect.width().round().clamp(1.0, 1024.0) as usize, rect.height().round().clamp(1.0, 1024.0) as usize];
picture(cx, rect, ("brushes-stroke", stroke_sig, size, color), || brush_preview::stroke_image(&brush, size, color));
})
});
BrushRowPaint::new(tip_paint(&b.tip, (b.hardness, b.angle, b.roundness)), stroke)
}
/// How the engine draws `tip` with the falloff, angle and roundness `shape` (a sampled tip's shape) in the theme's text
/// colour: a preset's thumbnail and the Brush Preset chip's current tip.
pub(crate) fn tip_paint(tip: &TipShape, shape: (f32, f32, f32)) -> impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static {
pub(crate) fn tip_paint(tip: &TipShape, shape: (f32, f32, f32)) -> FacePaint {
let tip = tip.clone();
let tip_key = brush_preview::tip_sig(&tip, shape.0, shape.1, shape.2, (false, false));
move |cx, rect| {
FacePaint::new(tip_key, move |cx, rect| {
let color = Tokens::get(cx.painter.ctx()).text;
picture(cx, rect, ("brushes-tip", tip_key, color), || brush_preview::tip_image(&tip, shape, 36, color));
}
})
}
/// The presets of the brush lists: every preset of `presets` in the engine's panel order, each row showing the card
+2 -2
View File
@@ -5,7 +5,7 @@
use std::ops::RangeInclusive;
use craft::behavior::EditEvents;
use craft::behavior::{EditEvents, Selection};
use craft::draw::ui::brush_presets::{BrushCardPart, BrushCardParts};
use craft::draw::ui::brush_settings::{BrushSizeField, DynamicControl, DynamicControlRow, TipAngle, TipEllipse};
use craft::ui::choice::Checkbox;
@@ -202,7 +202,7 @@ impl Pane<'_> {
.toolbar(false)
.room_height(GRID_HEIGHT);
if let Some(key) = selected {
browser = browser.selected(key);
browser = browser.selection(Bind::given(Selection::single(key)));
}
browser.show(ui).events.into_iter().find_map(|event| match event {
PresetEvent::Select { key: BrushKey::Preset(name), .. } => Some(name),
+7 -2
View File
@@ -2,7 +2,7 @@
//! `tools.setColors` (one history step per gesture) and recolour what is selected (`apply_color`).
use craft::behavior::EditEvent;
use craft::color_ui::ui::{ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelState, PanelTarget, PickedColor};
use craft::color_ui::ui::{ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelMenu, ColorPanelState, PanelTarget, PickedColor};
use craft::theme::Srgba;
use craft::ui::contract::{Bind, MemoProps, MemoView, Outbox};
use serde_json::json;
@@ -119,5 +119,10 @@ pub(crate) fn srgba(c: [f32; 4]) -> Srgba {
pub(crate) fn run_menu_command(app: &mut PhotocraftApp, command: ColorPanelCommand) -> Option<String> {
let tools = &app.session.tools;
let edited = srgba(if app.ui.color_panel.panel.background { tools.background } else { tools.foreground });
ColorPanelMenu::run_command(&mut app.ui.color_panel.panel, command, edited)
// Photoshop's layout has no Invert, Complement or Create New Swatch rows, and a mode is set on the state itself:
// only the copy commands leave the host something to do.
match ColorPanelMenu::run_command(&mut app.ui.color_panel.panel, command, edited)? {
ColorPanelAction::Copy(text) => Some(text),
_ => None,
}
}
+2 -2
View File
@@ -8,7 +8,7 @@ use craft::behavior::{ColumnWidth, EditEvent, EditEvents, Mixed, RulerUnits, Tic
use craft::draw::ui::{SizeUnit, TransformFields, TransformGroups, TransformRow};
use craft::ui::bars::AlignBar;
use craft::ui::buttons::Button;
use craft::ui::canvas::RulerText;
use craft::ui::canvas::{CanvasRulers, RulerText};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing};
use craft::ui::layout_components::Grid;
use craft::ui::runtime::commands::CommandRef;
@@ -169,7 +169,7 @@ fn transform_section(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer,
TransformFields::new(tl!("Transform"), Bind::given(row), rect, Bind::bound(&mut app.ui.properties_linked))
.groups(groups)
.document(Size::new(dw, dh))
.units(x_text, y_text)
.rulers(CanvasRulers::new(x_text, y_text, Point::ZERO))
.size_unit(SizeUnit::length(x_text, y_text))
.show(ui)
});
+2 -1
View File
@@ -1,5 +1,6 @@
use craft::theme::variant::Tone;
use craft::ui::contract::Show as _;
use craft::ui::menu::MenuRow;
use craft::ui::notices::{Notice, NoticeLayout};
use super::{BlendMode, LayerId, PhotocraftApp};
@@ -46,7 +47,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
.settings(settings)
.thumbnails(&thumbs, &source)
.filter(Bind::bound(&mut filter))
.row_menu(|target| layers_tree::row_menu(app, tree, target))
.row_menu(|target| layers_tree::row_menu(app, tree, target).into_iter().map(MenuRow::from).collect())
.document(st.doc.id);
if let Some((id, groups)) = reveal {
panel = panel.reveal(id, groups);
+2 -1
View File
@@ -335,7 +335,8 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, panels_hidden: bo
}
// Files dropped on a floating panel's own window open as documents, and the main window comes forward.
if !window_files.is_empty() {
app.open_dropped(&ctx, window_files, crate::file_open::DropTo::Window);
let files = window_files.into_iter().flat_map(|dropped| dropped.files).collect();
app.open_dropped(&ctx, files, crate::file_open::DropTo::Window);
}
}
@@ -240,7 +240,8 @@ fn a_menu_key_typed_in_a_panel_windows_text_field_goes_to_the_field() {
}
/// PhotoCraft's dialogs are framework layers, so the runtime's modal blocking reaches the panel windows:
/// under a dialog the window takes no click and no key, and once it is closed the window works again.
/// under a dialog the window takes no click and no key and is hidden, so a click cannot bring it over the dialog,
/// also while the app is in the background; once the dialog is closed the window shows and works again.
#[test]
fn a_dialog_blocks_the_panel_windows() {
for name in ["About", "Gaussian Blur"] {
@@ -263,12 +264,13 @@ fn a_dialog_blocks_the_panel_windows() {
assert_eq!(desktop.h.state().ui.tool, crate::state::Tool::Move, "{name}: nor do the shortcuts get its keys");
desktop.host.borrow_mut().focus = Some(ViewportId::from_hash_of("another app"));
desktop.steps(30);
assert!(!desktop.host.borrow().windows[&viewport].hidden, "{name}: the panel window stays shown while the app is in the background");
assert!(desktop.host.borrow().windows[&viewport].hidden, "{name}: the panel window stays hidden under the dialog while the app is in the background");
desktop.host.borrow_mut().focus = Some(viewport);
crate::dialogs::testing::cancel(desktop.h.state_mut(), id).unwrap();
desktop.steps(3);
assert!(!desktop.h.state().dialog_open(), "{name}");
assert!(!desktop.host.borrow().windows[&viewport].hidden, "{name}: the panel window shows again once the dialog is gone");
desktop.click(viewport, close);
assert!(!is_shown(desktop.h.state(), "layers"), "{name}: the × closes the panel once the dialog is gone");
}
+13 -10
View File
@@ -2,6 +2,7 @@
//! framework's `PresetBrowser` and `PresetPicker`. Rows come from a panel's groups in the panel's folder order; the
//! browser's events run as the panel's engine commands, through one mapping for every preset panel (`events`).
use craft::behavior::Selection;
use craft::color_ui::ui::gradient::GradientRamp;
use craft::keymap::CommandRef;
use craft::theme::Srgba;
@@ -13,8 +14,8 @@ use craft::ui::patterns::presets::{
CellShape, DefaultOpen, PresetBrowser, PresetCommands, PresetEvent, PresetExport, PresetFileRequest, PresetFiles, PresetFns, PresetFooterEvent,
PresetFooterOptions, PresetMenuAction, PresetPanelMenu, PresetPicker, PresetReorder, PresetRow, PresetSource, PresetState, PresetView, ThumbFn, ThumbInfo,
};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::primitives::textures::TextureCache;
use craft::ui::primitives::{ContentPainterCx, FacePaint};
use craft::ui::runtime::commands::{CommandSet as _, CommandState};
use craft::ui::runtime::env::Env;
use craft::ui::tile_grid::TileZoom;
@@ -142,6 +143,14 @@ impl Swatch {
fn paint(&self, cx: &ContentPainterCx, rect: Rect) {
paint_texture(cx, rect, self.texture(cx.painter.ctx()));
}
/// The swatch's picture as a face keyed by its texture key, inset by `inset` points on every side.
fn face(&self, inset: f32) -> FacePaint {
let mut key = std::collections::hash_map::DefaultHasher::new();
std::hash::Hash::hash(&self.picture, &mut key);
let swatch = self.clone();
FacePaint::new(std::hash::Hasher::finish(&key), move |cx, rect| swatch.paint(cx, rect.shrink(inset)))
}
}
/// The patterns and styles the preset views draw from, held while the library and the presets are unchanged, so a
@@ -247,7 +256,7 @@ fn show(
}
let mut browser = PresetBrowser::new(tl!(panel.label), Bind::bound(&mut state), source);
if let Some(key) = selected.clone() {
browser = browser.selected(key);
browser = browser.selection(Bind::given(Selection::single(key)));
}
if let Some(height) = look.room_height {
browser = browser.room_height(height);
@@ -746,10 +755,7 @@ fn shape_rows(groups: &Vec<(String, Vec<Swatch>)>, _: &Env) -> Vec<PresetRow<Str
for (group, shapes) in groups {
rows.push(PresetRow::group(format!("{SHAPE_GROUP}{group}"), group.clone(), 0));
for shape in shapes {
let swatch = shape.clone();
rows.push(PresetRow::item(shape.key.clone(), shape.name.clone(), 1).tooltip(shape.name.clone()).preview(ThumbAspect::SQUARE, move |cx, rect| {
swatch.paint(cx, rect.shrink(2.0));
}));
rows.push(PresetRow::item(shape.key.clone(), shape.name.clone(), 1).tooltip(shape.name.clone()).preview_face(ThumbAspect::SQUARE, shape.face(2.0)));
}
}
rows
@@ -982,10 +988,7 @@ fn swatch_rows(swatches: &[Swatch], _: &Env) -> Vec<PresetRow<String>> {
swatches
.iter()
.map(|swatch| {
let picture = swatch.clone();
PresetRow::item(swatch.key.clone(), swatch.name.clone(), 0)
.tooltip(swatch.name.clone())
.preview(ThumbAspect::SQUARE, move |cx, rect| picture.paint(cx, rect))
PresetRow::item(swatch.key.clone(), swatch.name.clone(), 0).tooltip(swatch.name.clone()).preview_face(ThumbAspect::SQUARE, swatch.face(0.0))
})
.collect()
}
+8 -3
View File
@@ -7,7 +7,7 @@
use craft::behavior::Axis;
use craft::behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace};
use craft::color_ui::ui::{ColorPanelCommand, ColorPanelMenu};
use craft::color_ui::ui::{ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelShown};
use craft::ui::contract::{Scroll, ShowContainer as _};
use craft::ui::docking::DockHeights;
use craft::ui::layout_components::Stack;
@@ -105,7 +105,7 @@ pub(crate) static PANELS: &[PanelEntry] = &[
// The Color panel sizes its field to the group and scrolls its slider modes itself (#6000).
PanelEntry {
heights: Some(COLOR_HEIGHTS),
rows: |_| ColorPanelMenu::rows(),
rows: |_| ColorPanelMenu::rows(ColorPanelLayout::ForegroundBackground),
states: color_source_states,
run: color_run,
..panel("color", || tl!("Color").to_string(), "palette", LEAST, super::color::panel)
@@ -228,7 +228,12 @@ pub(crate) static PANELS: &[PanelEntry] = &[
/// The Color panel menu's states, from the panel's own state.
fn color_states(app: &PhotocraftApp) -> SourceStates {
ColorPanelMenu::states(&app.ui.color_panel.panel).into_iter().map(|(command, state)| (command.into(), state)).collect()
let state = &app.ui.color_panel.panel;
// Photoshop's layout: the views follow the state's mode, and the foreground and background always hold a colour.
ColorPanelMenu::states(ColorPanelLayout::ForegroundBackground, state, &ColorPanelShown::Mode(state.mode), true)
.into_iter()
.map(|(command, state)| (command.into(), state))
.collect()
}
/// [`color_states`], derived from the panel's state.
+25 -12
View File
@@ -14,8 +14,9 @@ use std::ffi::OsStr;
use serde_json::{Value, json};
use craft::behavior::Selection;
use craft::cms::convert::CmykConverter;
use craft::color_ui::palette::SwatchColor;
use craft::color_ui::palette::{SwatchColor, SwatchPaint};
use craft::color_ui::ui::PickedColor;
use craft::color_ui::ui::{SwatchAt, SwatchEdit, SwatchKey, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesWords};
use craft::theme::Srgba;
@@ -88,7 +89,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
pub(crate) fn apply_used(app: &mut PhotocraftApp, at: SwatchAt, background: bool) {
let name = app.session.presets().swatches.get(at.group).and_then(|g| g.entries.get(at.index)).map(|e| e.name.clone());
if let Some(name) = name {
app.ui.swatches.selected = Some(SwatchKey::Swatch(name.clone()));
app.ui.swatches.selection = Selection::single(SwatchKey::Swatch(name.clone()));
use_swatch(app, &name, background);
}
}
@@ -108,19 +109,31 @@ fn color_param(color: &SwatchColor, converter: Option<&CmykConverter>) -> Value
/// Runs one edit the panel resolved.
pub(crate) fn apply_edit(app: &mut PhotocraftApp, edit: SwatchEdit) {
match edit {
SwatchEdit::Add { group, name, color, .. } => new_swatch(app, group, name, &color),
// PhotoCraft's swatches hold colours: the panel offers no gradient, pattern or None swatch to add.
SwatchEdit::Add { group, name, paint: SwatchPaint::Color(color), .. } => new_swatch(app, group, name, &color),
SwatchEdit::NewGroup { name, .. } => new_group(app, name),
SwatchEdit::Rename { swatch, name, .. } => {
if run(app, "swatches.rename", json!({"swatch": swatch, "name": name})).is_some() && app.ui.swatches.selected == Some(SwatchKey::Swatch(swatch)) {
app.ui.swatches.selected = Some(SwatchKey::Swatch(name));
if run(app, "swatches.rename", json!({"swatch": swatch, "name": name})).is_some() {
// The renamed swatch stays selected under its new name.
let (old, new) = (SwatchKey::Swatch(swatch), SwatchKey::Swatch(name));
let selection = &mut app.ui.swatches.selection;
for key in selection.items.iter_mut().chain(selection.lead.as_mut()).chain(selection.anchor.as_mut()) {
if *key == old {
*key = new.clone();
}
}
}
}
SwatchEdit::RenameGroup { group, name, .. } => {
run(app, "swatches.renameGroup", json!({"group": group, "name": name}));
}
SwatchEdit::Delete { swatch, .. } => {
if run(app, "swatches.delete", json!({"swatch": swatch})).is_some() && app.ui.swatches.selected == Some(SwatchKey::Swatch(swatch)) {
app.ui.swatches.selected = None;
if run(app, "swatches.delete", json!({"swatch": swatch})).is_some() {
let gone = SwatchKey::Swatch(swatch);
let selection = &mut app.ui.swatches.selection;
selection.items.retain(|key| *key != gone);
selection.lead = selection.lead.take().filter(|key| *key != gone);
selection.anchor = selection.anchor.take().filter(|key| *key != gone);
}
}
SwatchEdit::DeleteGroup { group, .. } => {
@@ -149,7 +162,7 @@ fn new_swatch(app: &mut PhotocraftApp, group: Option<String>, name: String, colo
}
if let Some(r) = run(app, "swatches.add", params) {
let name = r["name"].as_str().unwrap_or_default().to_string();
app.ui.swatches.selected = Some(SwatchKey::Swatch(name.clone()));
app.ui.swatches.selection = Selection::single(SwatchKey::Swatch(name.clone()));
app.ui.swatches.rename = Some(SwatchKey::Swatch(name));
}
}
@@ -281,7 +294,7 @@ pub fn add_from_picker(app: &mut PhotocraftApp, picked: PickedColor) {
app.ui.status_error = false;
let template = "Added swatch {name}";
app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]);
app.ui.swatches.selected = Some(SwatchKey::Swatch(name));
app.ui.swatches.selection = Selection::single(SwatchKey::Swatch(name));
}
}
@@ -359,12 +372,12 @@ mod tests {
apply_used(&mut app, SwatchAt::new(0, 0), true);
assert_eq!(app.session.tools.background, [0.0, 0.0, 0.0, 1.0], "Black");
assert_eq!(app.session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "foreground untouched (default black)");
assert_eq!(app.ui.swatches.selected, Some(SwatchKey::Swatch("Black".into())));
assert_eq!(app.ui.swatches.selection, Selection::single(SwatchKey::Swatch("Black".into())));
// The footer's trash deletes the selection.
let n = app.session.presets().swatches[0].entries.len();
apply_edit(&mut app, SwatchEdit::delete("Black".into()));
assert_eq!(app.session.presets().swatches[0].entries.len(), n - 1);
assert_eq!(app.ui.swatches.selected, None);
assert_eq!(app.ui.swatches.selection, Selection::default());
}
#[test]
@@ -378,7 +391,7 @@ mod tests {
assert_eq!(app.ui.swatches.rename, Some(SwatchKey::Swatch("Color Swatch 1".into())), "renamed in place");
add_from_picker(&mut app, PickedColor::cmyk(Srgba::rgb(0.0, 1.0, 1.0), [100.0, 0.0, 0.0, 0.0]));
let s = app.session.presets().swatches[0].entries.last().unwrap();
assert_eq!(s.color, photocraft_engine::presets::swatches::SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0]));
assert_eq!(s.color(), Some(&photocraft_engine::presets::swatches::SwatchColor::Cmyk([1.0, 0.0, 0.0, 0.0])));
}
/// The menu's file requests go to the host file service: a read imports (a group named by the file, or a
@@ -2,7 +2,7 @@
use std::hash::{Hash, Hasher};
use craft::font_manager::glyphs::{GlyphSource, GlyphsPanel};
use craft::font_manager::glyphs::{CATEGORIES, GlyphCell, GlyphSource, GlyphsPanel};
use craft::ui::contract::Bind;
use serde_json::json;
@@ -20,13 +20,29 @@ fn char_style_for(family: &str, style: &str) -> photocraft_doc::text::CharStyle
st
}
/// Whether `c` belongs to the panel's `category` (a [`CATEGORIES`] id).
fn in_category(c: char, category: &str) -> bool {
let u = c as u32;
match category {
"Latin" => ["Basic Latin", "Latin 1", "Latin Extended-A", "Latin Extended-B"].iter().any(|name| photocraft_text::glyphs::in_category(c, name)),
"Letterlike Symbols" => (0x2100..=0x214F).contains(&u),
"Superscripts and Subscripts" => (0x2070..=0x209F).contains(&u) || matches!(u, 0xB9 | 0xB2 | 0xB3),
// Alternates belong to a text selection's glyph, which the engine does not list per face.
"Alternates for Selection" => false,
other => photocraft_text::glyphs::in_category(c, other),
}
}
impl GlyphSource for PhotoGlyphs {
fn charmap(&self, family: &str, style: &str) -> Vec<char> {
/// The face's mapped characters in the category; the engine lists no unencoded glyphs.
fn cells(&self, family: &str, style: &str, category: &str) -> Vec<GlyphCell> {
let st = char_style_for(family, style);
photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.charmap_for_style(&st)
let charmap = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.charmap_for_style(&st);
charmap.into_iter().filter(|c| category == CATEGORIES[0] || in_category(*c, category)).map(GlyphCell::Char).collect()
}
fn glyph(&self, family: &str, style: &str, c: char, px: u32) -> Option<egui::ColorImage> {
fn glyph(&self, family: &str, style: &str, cell: GlyphCell, px: u32) -> Option<egui::ColorImage> {
let GlyphCell::Char(c) = cell else { return None };
let st = char_style_for(family, style);
let (n, alpha) = {
let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());
@@ -39,19 +55,6 @@ impl GlyphSource for PhotoGlyphs {
Some(egui::ColorImage::from_rgba_unmultiplied([n as usize, n as usize], &pixels))
}
fn in_category(&self, c: char, category: &str) -> bool {
use photocraft_text::glyphs::in_category;
let u = c as u32;
match category {
"Latin" => ["Basic Latin", "Latin 1", "Latin Extended-A", "Latin Extended-B"].iter().any(|name| in_category(c, name)),
"Letterlike Symbols" => (0x2100..=0x214F).contains(&u),
"Superscripts and Subscripts" => (0x2070..=0x209F).contains(&u) || matches!(u, 0xB9 | 0xB2 | 0xB3),
// Alternates belong to a text selection's glyph, which the engine does not list per face.
"Alternates for Selection" => false,
other => in_category(c, other),
}
}
fn ready(&self) -> bool {
photocraft_text::try_shared().is_some()
}
@@ -109,8 +112,8 @@ pub(crate) fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
type_tool::finish_font_state(app, fonts);
app.ui.type_panels.glyph_face = Some((family, style));
}
if let Some(g) = out.insert
&& !insert(app, &g)
if let Some(GlyphCell::Char(c)) = out.activated
&& !insert(app, &c.to_string())
{
app.ui.status = tl!("Select a type layer or click into text to insert glyphs").into();
}
@@ -64,8 +64,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool) {
Some(TextStyleAction::ClearOverride) => {
super::run(app, &format!("{prefix}.clearOverride"), tgt.clone());
}
Some(TextStyleAction::Redefine) => {
super::run(app, &format!("{prefix}.redefine"), tgt.clone());
Some(TextStyleAction::Redefine(id)) => {
let mut p = tgt.clone();
p["id"] = json!(id);
super::run(app, &format!("{prefix}.redefine"), p);
}
Some(TextStyleAction::New { from_selection, .. }) => {
let mut p = tgt.clone();
+1 -1
View File
@@ -393,7 +393,7 @@ impl StackDialog for VariablesDialog {
.shown(page)
.show_items(ui, &Pages, &mut |key, _| Tab::new(label(if *key == 0 { tl!("Define") } else { tl!("Data Sets") })));
for event in strip.response.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(key) = keys.into_iter().last()
{
page = key.min(1);
@@ -81,8 +81,9 @@ impl PrefsCustom {
}
}
// Every custom row and page writes the draft only: none has state of its own to report changed.
impl CustomSettings<PrefPages> for PrefsCustom {
fn row(&mut self, ui: &mut egui::Ui, key: &str, draft: &mut SettingsDraft) {
fn row(&mut self, ui: &mut egui::Ui, key: &str, draft: &mut SettingsDraft) -> bool {
match key {
MEMORY_PERCENT => memory_percent_row(ui, draft),
MEMORY_MB => self.memory_mb_row(ui, draft),
@@ -95,13 +96,15 @@ impl CustomSettings<PrefPages> for PrefsCustom {
APPEARANCE_MODE => self.appearance_row(ui, draft),
_ => {}
}
false
}
#[cfg(not(target_arch = "wasm32"))]
fn page(&mut self, ui: &mut egui::Ui, page: &str, draft: &mut SettingsDraft) {
fn page(&mut self, ui: &mut egui::Ui, page: &str, draft: &mut SettingsDraft) -> bool {
if page == AGENTS_PAGE {
craft::automation::ui::agents::AgentsPage::new(AGENTS_PAGE, draft, &self.agent_status).mcp_flag(self.mcp_flag).show(ui);
}
false
}
fn nested_open(&self) -> bool {
+23 -6
View File
@@ -50,7 +50,15 @@ pub(crate) struct ShortcutsSession {
/// the same frame finds nothing to review.
pub(crate) pending_import: Option<String>,
/// The user's answers to earlier import questions, for the next import of this session.
pub(crate) remembered: BTreeMap<String, CommandRef>,
pub(crate) remembered: ImportAnswers,
}
/// The user's answers to an import's questions: the command of each foreign entry and the chord text of each key or
/// modifier code, `None` for "No equivalent".
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct ImportAnswers {
pub(crate) targets: BTreeMap<String, Option<CommandRef>>,
pub(crate) codes: BTreeMap<String, Option<String>>,
}
/// What the Menus tab edits: the hidden items and the colour of each item, by command id.
@@ -94,8 +102,14 @@ pub(crate) fn draft_keymap(app: &PhotocraftApp) -> Keymap {
/// How a `.kys` set is read for review and for the offer: rows without a key leave their command
/// alone, and the user's earlier answers come first.
pub(crate) fn import_options(remembered: &BTreeMap<String, CommandRef>) -> ImportOptions {
ImportOptions { remembered: remembered.clone(), none_defined: NoneDefined::Keep, suggest: true, ..ImportOptions::default() }
pub(crate) fn import_options(answers: &ImportAnswers) -> ImportOptions {
ImportOptions {
remembered: answers.targets.clone(),
codes: answers.codes.clone(),
none_defined: NoneDefined::Keep,
suggest: true,
..ImportOptions::default()
}
}
/// The text of a set file's bytes, or why it is not one.
@@ -115,7 +129,7 @@ pub fn open(app: &mut PhotocraftApp, tab: u64) {
keymap: draft_keymap(app),
menus: MenusDraft::of(&prefs.menus),
pending_import: None,
remembered: BTreeMap::new(),
remembered: ImportAnswers::default(),
};
app.prefs_rt.shortcuts = Some(session);
}
@@ -214,7 +228,10 @@ fn pass(app: &mut PhotocraftApp, ui: &mut egui::Ui, press_ok: bool) {
save_text(app, state, &format!("{name}.kys"), kys::write(&name, &exported));
}
Some(Outcome::Summary { name, html, .. }) => save_text(app, state, &format!("{name}.html"), html),
Some(Outcome::Remembered(answers)) => remembered.extend(answers),
Some(Outcome::Remembered { targets, codes, .. }) => {
remembered.targets.extend(targets);
remembered.codes.extend(codes);
}
_ => {}
}
if state.is_open() {
@@ -224,7 +241,7 @@ fn pass(app: &mut PhotocraftApp, ui: &mut egui::Ui, press_ok: bool) {
/// Opens the review of the set `text` holds (a `.kys` file, or craft-keymap JSON), or shows why it
/// cannot be read.
fn review(ui: &egui::Ui, state: &mut DialogState, dialog: ShortcutsDialog<'_>, text: &str, remembered: &BTreeMap<String, CommandRef>) {
fn review(ui: &egui::Ui, state: &mut DialogState, dialog: ShortcutsDialog<'_>, text: &str, remembered: &ImportAnswers) {
if text.trim_start().starts_with(['{', '[']) {
if let Err(e) = dialog.import_json(ui, state, text) {
state.show_error(e.to_string());
+6 -1
View File
@@ -9,6 +9,7 @@ use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::requests::PathKind;
use craft::ui::sections::{DialogRole, FooterButton};
use photocraft_doc::{DocId, LayerContent, LayerId, SmartSource};
use serde_json::{Value, json};
@@ -284,7 +285,11 @@ fn dialog(ctx: &egui::Context, pending: &Pending, running: bool) -> HostedParamD
HostedParamDialog::new(ctx, KEY, fields, move |fields| {
let title = tr(if svg { "Edit SVG Smart Object" } else { "Edit Vector Smart Object" });
let dialog = ParamDialog::new(KEY, Label::from(title), params(svg)).values(Bind::bound(fields));
if running { dialog.extra_buttons(vec![(STOP_SYNC.to_owned(), Label::from(tr("Stop syncing this Smart Object")))]) } else { dialog }
if running {
dialog.extra_buttons(vec![(STOP_SYNC.to_owned(), FooterButton::new(tr("Stop syncing this Smart Object"), DialogRole::Other))])
} else {
dialog
}
})
}
+4
View File
@@ -331,6 +331,9 @@ pub struct UiState {
/// Slice and Slice Select tools (see `slice_ui`).
#[serde(default)]
pub slices: crate::slice_ui::SliceUi,
/// The open Save for Web dialog's colour table shifts (see `file_ui::web`).
#[serde(skip)]
pub web_table: crate::dialogs::file_ui::WebTable,
/// Frame tool (see `frame_tool`).
#[serde(default)]
pub frame_tool: crate::frame_tool::FrameToolUi,
@@ -503,6 +506,7 @@ impl Default for UiState {
analysis: Default::default(),
timeline: Default::default(),
slices: Default::default(),
web_table: Default::default(),
frame_tool: Default::default(),
task_bar_shown: None,
artboard_tool: Default::default(),
+1 -1
View File
@@ -72,7 +72,7 @@ impl<'a> PickerInput<'a> {
.import()
.gear_rows(gear_rows)
.resizable(SaveKey::new("photocraft.brush_picker"))
.tip(Arc::new(tip_paint(self.tip, (self.face.hardness, self.face.angle, self.face.roundness))))
.tip(tip_paint(self.tip, (self.face.hardness, self.face.angle, self.face.roundness)))
}
}
@@ -149,7 +149,8 @@ fn the_magnetic_lasso_cursor_follows_other_cursors_and_caps_lock() {
let shown = cursor::current(&h.ctx);
let matches = match (radius, &shown) {
(Some(expected), Some(Cursor::Painted(PaintedCursor::Circle { radius, .. }))) => (*radius - expected).abs() < 1e-3,
(None, Some(Cursor::Painted(PaintedCursor::Tool { icon, .. }))) => *icon == lasso,
// The arrow with the lasso icon beside it (#16671).
(None, Some(Cursor::Painted(PaintedCursor::PointerTool { icon, .. }))) => *icon == lasso,
_ => false,
};
assert!(matches, "{preference}, Caps Lock {caps_lock}, zoom {zoom}: expected radius {radius:?} or a lasso icon, got {shown:?}");
+1 -1
View File
@@ -121,7 +121,7 @@ pub fn abandon(app: &mut PhotocraftApp) {
/// The document pixels one plain arrow press moves layers by with the Move tool: one screen
/// pixel, as in Photoshop (#9511). Zoomed out that is several document pixels (2 at 50 %, 4 at
/// 25 %; 1 at 66.7 %: whole pixels only), zoomed in still one. No cap: the zoom bottoms out
/// with the document's shorter side 2 px on screen (`ZoomLadder::min`), so a step is at most
/// with the document's shorter side 2 px on screen (`ZoomScheme::min`), so a step is at most
/// half that side. ⇧'s 10 px don't scale.
fn screen_pixel_step(app: &PhotocraftApp) -> f64 {
let zoom = f64::from(app.current_zoom());
+1 -1
View File
@@ -472,7 +472,7 @@ fn arrow_keys_ignored_during_text_edit() {
/// 100 % and above, up to 1600 %); ⇧ is 10 document pixels at any zoom.
#[test]
fn a_nudge_is_one_screen_pixel() {
let lowest = craft::behavior::canvas::ZoomLadder::min(craft::behavior::kurbo::Size::new(12_000.0, 12_000.0));
let lowest = craft::behavior::canvas::ZoomScheme::PHOTOSHOP.min(craft::behavior::kurbo::Size::new(12_000.0, 12_000.0));
// Below 0.1 % a large document still nudges one screen pixel: 6000 document pixels at a
// 12,000 × 12,000 px document's lowest zoom, and the ladder's f32 rungs (0.1 %, 0.2 %) give
// whole steps (1000, not 999). 0.3333334 is just above a third, off the ladder (pinch, Zoom
@@ -76,6 +76,28 @@ fn box_shows(app: &PhotocraftApp) -> bool {
&& matches!(app.ui.tool, Tool::PathSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line)
}
/// The shape layers the box or a corner widget is editing: the selected shape layers while one of them holds a press.
/// They are not snap targets, so a handle does not snap to the starting edges and centres of the shapes it scales.
pub(crate) fn pressed_layers(app: &PhotocraftApp) -> Vec<LayerId> {
if !editing(app) {
return Vec::new();
}
let mut layers: Vec<LayerId> = if box_shows(app) {
selection(app, live_line(app).is_some()).map(|(layers, _)| layers.into_iter().map(LayerId).collect()).unwrap_or_default()
} else {
Vec::new()
};
// The corner widgets show without the box (Target Path hidden, the Move tool) and beside other layers in a mixed
// selection: the shapes they round are not targets either.
for target in corner_targets(app) {
let id = LayerId(target.key);
if !layers.contains(&id) {
layers.push(id);
}
}
layers
}
/// The selected shape layers and the box round their paths `[x0, y0, x1, y1]`. `None` unless at least
/// one layer is selected and all are shape layers. A box with no extent along one axis counts only
/// when `flat_ok` (a level or upright live line).
@@ -190,3 +190,19 @@ fn a_star_shows_widgets_at_its_outer_points_only() {
assert_eq!((corner.vertex.x, corner.vertex.y), (v.x, v.y), "corner {i} is outer point {i}");
}
}
/// A held corner widget keeps its shape out of the snap targets with Target Path hidden, where the widgets show
/// without the scale box: the drag does not snap to the rectangle's own starting edges.
#[test]
fn a_held_corner_widget_is_no_snap_target_without_the_box() {
let mut app = app(Tool::Rectangle);
app.ui.view.show.target_path = false;
testing::frame(&mut app);
let id = active(&app);
assert!(!corner_targets(&app).is_empty(), "the widgets show with Target Path hidden");
testing::press(&mut app, [60.0, 60.0], NONE);
testing::move_to(&mut app, [64.0, 64.0], NONE);
assert!(super::pressed_layers(&app).contains(&id), "the rounded rectangle is no snap target while its widget is held");
testing::release(&mut app, [64.0, 64.0], NONE);
assert!(super::pressed_layers(&app).is_empty(), "nothing is held after the release");
}
+96 -3
View File
@@ -1,14 +1,16 @@
//! Shape toolbar edits share the engine commands used by the Properties panel.
use craft::behavior::{EditEvent, Mixed};
use craft::color_ui::ui::{Paint, PaintChip};
use craft::draw::stroke::StrokeStyle;
use craft::draw::ui::RADIUS_RANGE;
use craft::draw::ui::shape::{ShapeAppearance, ShapeBar, ShapeChange, ShapePaint, ShapeToolSettings};
use craft::draw::ui::shape::{ShapeAppearance, ShapeBar, ShapeChange, ShapePaint, ShapeToolSettings, ShapeWords};
use craft::draw::ui::shape_drag::ShapeKind;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{Alert, HostedAlert};
use craft::ui::display::Divider;
use craft::ui::runtime::env::Env;
use craft::ui::form::Field;
use craft::ui::runtime::env::{Env, Label};
use photocraft_doc::{Fill, LayerContent};
use photocraft_engine::presets::PresetsExt;
use serde_json::{Value, json};
@@ -358,6 +360,97 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
}
}
/// The value a chip event proposes: like [`proposal`], for the paint a `PaintChip` reports.
fn paint_proposal(event: &EditEvent<Paint>) -> Option<&Paint> {
match event {
EditEvent::Update { value, .. } => Some(value),
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => Some(after),
EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => Some(value),
_ => None,
}
}
/// The Pen family's Shape-mode Fill and Stroke swatches (#12907): the shape tools' chips with the
/// same popups (Recently Used Colors, the Swatches list, the Gradient tab and Color Picker…),
/// under the reference's "Fill:" and "Stroke:" labels. A pick writes the tool's shape fill and
/// stroke defaults — the paints `vector_ui::shapes` gives the next Pen shape — and runs no
/// document command: as in the Shape tools' bar with no shape layer selected, only the tool
/// changes.
pub(crate) fn pen_paint_swatches(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);
let o = &app.ui.tool_options;
// The same tool-default paints the Shape tools' bar shows when no shape layer is selected.
let fill = o.shape_fill_gradient.clone().unwrap_or_else(|| solid(fg));
let stroke_paint = o.shape_stroke_gradient.clone().unwrap_or_else(|| solid(bg));
let (fill, stroke) = (o.shape_fill.then_some(fill), (o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, stroke_paint)));
let width = stroke.as_ref().map_or(0.0, |s| f64::from(s.width));
let appearance = ShapeAppearance::new(paint_of(fill.as_ref()), paint_of(stroke.as_ref().map(|s| &s.paint)), width).stroke_style((&o.shape_stroke).into());
let sampled = [ShapePaint::Fill, ShapePaint::Stroke].into_iter().find_map(|p| crate::screen_picker::take(app, ("pen-bar", p)).map(|c| (p, c)));
let recent_colors: Vec<craft::theme::Srgba> =
crate::paint_picker::recent_colors(&app.session).into_iter().map(|c| srgba([c[0], c[1], c[2], 1.0])).collect();
let groups = ShapeGradients::groups_of(&app.session.presets().gradients, fg, bg);
let gradients = ShapeGradients { groups, current: &app.session.presets().gradient, recent: &mut app.ui.recent_gradients, fg, bg };
let current = [fill.clone(), stroke.as_ref().map(|s| s.paint.clone())];
let mut library =
ChipLibrary::new(&recent_colors, &app.session.presets().swatches, &mut app.ui.paint_folders, gradients, &mut app.ui.shape_gradient_state, current);
let words = Env::of(ui).words::<ShapeWords>();
// The Field's label is the control's accessible name, so the swatches answer to the
// reference's "Fill:" and "Stroke:"; inside, the chips keep the shape tools' names and tips.
let fill_out = Field::new(Label::from(tl!("Fill:").to_owned())).id_salt("pen-fill").show(ui, |ui, _| {
let mut chip = PaintChip::new(words.fill_color.clone(), Bind::given(appearance.fill.clone()), srgba(fg)).tooltip(words.set_fill_type.clone());
if let Some((_, color)) = sampled.filter(|(target, _)| *target == ShapePaint::Fill) {
chip = chip.sampled(color);
}
decorate_chip(chip, ShapePaint::Fill, &mut library, ui)
});
let stroke_out = Field::new(Label::from(tl!("Stroke:").to_owned())).id_salt("pen-stroke").show(ui, |ui, _| {
let mut chip = PaintChip::new(words.stroke_color.clone(), Bind::given(appearance.stroke.clone()), srgba(bg)).tooltip(words.set_stroke_type.clone());
if let Some((_, color)) = sampled.filter(|(target, _)| *target == ShapePaint::Stroke) {
chip = chip.sampled(color);
}
decorate_chip(chip, ShapePaint::Stroke, &mut library, ui)
});
let (fill_gradient, stroke_gradient) = (library.gradient(ShapePaint::Fill), library.gradient(ShapePaint::Stroke));
let mut recent: Option<[f32; 3]> = None;
let mut remembered: Vec<Fill> = Vec::new();
for (is_stroke, gradient, out) in [(false, fill_gradient, fill_out.inner), (true, stroke_gradient, stroke_out.inner)] {
let Some(out) = out else { continue };
let which = if is_stroke { ShapePaint::Stroke } else { ShapePaint::Fill };
let shown = if is_stroke { &appearance.stroke } else { &appearance.fill };
for event in &out.edit.events {
let Some(paint) = paint_proposal(event) else { continue };
// A cancelled gesture restoring what the chip already shows reached no edit: run nothing.
if matches!(event, EditEvent::Cancel { .. }) && shown == paint {
continue;
}
let Some(change) = paint_change(paint, &gradient) else { continue };
let applied = apply_tool_paint(app, is_stroke, &change);
if applied && !matches!(event, EditEvent::Update { .. } | EditEvent::Cancel { .. }) {
match &change {
PaintChange::Color(c) => recent = Some([c[0], c[1], c[2]]),
PaintChange::Gradient(g) => remembered.push(g.clone()),
PaintChange::None => {}
}
}
}
if let Some(gesture) = out.screen_pick {
crate::screen_picker::hold(app, ui.ctx(), ("pen-bar", which), gesture);
}
if out.pick_color.is_some() {
// The full Color Picker starts from the tool's paint; no layer is edited.
if let Some((which, fallback)) = paint_dialog_target(which, fg, bg) {
crate::shape_fill_ui::open_paint(app, which, None, true, fallback);
}
}
}
if let Some(rgb) = recent {
crate::paint_picker::remember(app, rgb);
}
for g in &remembered {
shape_gradient::remember_recent(&mut app.ui.recent_gradients, g);
}
}
/// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead.
pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> {
set_tool_paint_with_inks(app, stroke, change, None)
+13 -12
View File
@@ -7,13 +7,13 @@ use craft::behavior::EditEvent;
use craft::behavior::geometry::Constraint;
use craft::behavior::kurbo::Rect as DocRect;
use craft::draw::ui::slice::{
DivideBy, DivideSlices, DivideSlicesDialog, SliceBar, SliceCommand, SliceEvent, SliceItem, SliceKind, SliceMode, SliceOptions, SliceOptionsDialog,
SliceOrigin as ItemOrigin, SliceOverlay, SliceRules, SliceTool, SliceToolSettings,
DivideBy, DivideSlices, DivideSlicesDialog, SliceBackground, SliceBar, SliceCommand, SliceEvent, SliceItem, SliceKind, SliceMode, SliceOptions,
SliceOptionsDialog, SliceOrigin as ItemOrigin, SliceOverlay, SliceRules, SliceTool, SliceToolSettings,
};
use craft::theme::Srgba;
use craft::ui::canvas::ToolHostResponse;
use craft::ui::contract::Show as _;
use craft::ui::dialog::{DialogId, DialogResult};
use craft::ui::dialog::{DialogId, DialogResult, StackDialog as _};
use craft::ui::runtime::commands::{CommandRef, CommandSet as _, CommandState};
use photocraft_doc::SliceOrigin;
use photocraft_doc::slices::{self, ResolvedSlice};
@@ -388,8 +388,7 @@ pub(crate) fn open_options(app: &mut PhotocraftApp) -> Result<DialogId, String>
options.message = text("message");
options.alt = text("alt");
options.cell_text = text("cellText");
options.background_row = true;
options.background = v["background"].as_str().and_then(Srgba::from_hex);
options.background = v["background"].as_str().and_then(Srgba::from_hex).map_or(SliceBackground::None, SliceBackground::Color);
let target = r.id.map_or(SliceTarget::Auto(n), SliceTarget::Stored);
// HTML Text is offered only for a Table slice, so its value shows.
let mut kinds = vec![SliceKind::Image, SliceKind::NoImage];
@@ -418,13 +417,13 @@ pub(crate) fn take(app: &mut PhotocraftApp, _ctx: &egui::Context) {
fn take_options(app: &mut PhotocraftApp) {
let Some((id, target)) = app.ui.slices.options else { return };
if let Some(request) = app.framework.dialogs.get_mut_by_id::<SliceOptionsDialog>(id).and_then(SliceOptionsDialog::pick_color) {
if let Some(request) = app.framework.dialogs.get_mut_by_id::<SliceOptionsDialog>(id).and_then(|dialog| dialog.take_color_request()) {
crate::color_picker_ui::open_for_request(app, id, request);
}
if let Some((key, color)) = crate::color_picker_ui::answer_for(app, id)
&& let Some(dialog) = app.framework.dialogs.get_mut_by_id::<SliceOptionsDialog>(id)
{
dialog.set_color(&key, color);
dialog.answer_color(&key, color);
}
match app.framework.dialogs.take_by_id::<SliceOptionsDialog>(id) {
Some(DialogResult::Ok(options)) => {
@@ -441,13 +440,15 @@ fn take_options(app: &mut PhotocraftApp) {
] {
params[k] = json!(v);
}
params["background"] = match options.background {
Some(c) => {
// The engine stores no colour or a colour: Matte (the export's matte) leaves the stored background as it was.
match options.background {
SliceBackground::Color(c) => {
let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
json!(format!("#{:02x}{:02x}{:02x}", byte(c.r), byte(c.g), byte(c.b)))
params["background"] = json!(format!("#{:02x}{:02x}{:02x}", byte(c.r), byte(c.g), byte(c.b)));
}
None => json!("none"),
};
SliceBackground::None => params["background"] = json!("none"),
_ => {}
}
match app.run("slice.set", params) {
Ok(v) => app.ui.slices.selected = v.get("number").and_then(Value::as_u64).map(|n| n as usize),
Err(e) => report(app, e),
@@ -2204,7 +2204,8 @@ fn ending_the_transform_brings_back_the_tools_options_bar() {
}
}
/// #15548: Free Transform on an unturned, unskewed box shows the horizontal skew as "0", not "-0".
/// #15548: Free Transform on an unturned, unskewed box shows the horizontal skew as "0", not "-0". The field's value
/// reads the unit it draws after the number.
#[test]
fn an_unskewed_box_shows_its_horizontal_skew_as_zero() {
use egui_kittest::kittest::Queryable as _;
@@ -2213,7 +2214,7 @@ fn an_unskewed_box_shows_its_horizontal_skew_as_zero() {
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap();
h.run_steps(2);
assert_eq!(h.get_by_label("Horizontal skew").value().as_deref(), Some("0"));
assert_eq!(h.get_by_label("Horizontal skew").value().as_deref(), Some("0 °"));
}
#[path = "warp_remove_split_tests.rs"]
+1 -1
View File
@@ -131,7 +131,7 @@ impl FontSourceState {
/// The picker's source over this state.
pub(crate) fn source(&mut self) -> FontPickerSource<'_> {
let catalog = photocraft_text::fonts::catalog();
let mut source = FontPickerSource::new(catalog, Bind::bound(&mut self.settings), Bind::bound(&mut self.filters)).served(&self.served);
let mut source = FontPickerSource::new(catalog).settings(Bind::bound(&mut self.settings)).filters(Bind::bound(&mut self.filters)).served(&self.served);
if let Some(text) = self.preview_text.as_deref() {
source = source.preview_text(text);
}
+3 -2
View File
@@ -63,10 +63,11 @@ impl TextEditorHost for LayerHost<'_> {
self.app.session.active().and_then(|st| text_layer(&st.doc, self.layer)).map_or("", |t| t.text.as_str())
}
fn replace(&mut self, range: Range<usize>, text: &str, kind: EditKind) -> bool {
fn replace(&mut self, range: Range<usize>, text: &str, kind: EditKind) -> Option<usize> {
// A free transform in progress commits before the text changes under it.
crate::type_transform::finish(self.app);
insertion_style::replace(self.app, range.start, range.end, text, kind)
// The engine inserts the whole text, its line breaks as `\n`.
insertion_style::replace(self.app, range.start, range.end, text, kind).then(|| insertion_style::stored_chars(text))
}
fn hit(&mut self, at: Point) -> (usize, usize) {
@@ -49,11 +49,17 @@ pub(super) fn set_font(app: &mut PhotocraftApp, props: &serde_json::Value) -> bo
true
}
/// How many characters `text` adds once the engine stores it: a CRLF pair becomes one `\n` (a lone CR is one
/// character either way), so a pasted Windows line break moves the caret by one, not two.
pub(super) fn stored_chars(text: &str) -> usize {
text.chars().count().saturating_sub(text.matches("\r\n").count())
}
/// Replace and style the inserted characters atomically, including paste and a composition's marked text.
pub(super) fn replace(app: &mut PhotocraftApp, start: usize, end: usize, text: &str, kind: EditKind) -> bool {
let Some(ed) = app.ui.text_edit.clone() else { return false };
let pending = pending(app).cloned().or_else(|| pending_across_deletion(app, start, end, kind));
let caret = start.saturating_add(text.chars().count());
let caret = start.saturating_add(stored_chars(text));
let mut params = json!({"layer": ed.layer, "replace": {"start": start, "end": end, "text": text}, "coalesce": ed.session});
if let Some(p) = &pending
&& !text.is_empty()
@@ -374,3 +374,17 @@ fn closed_path_aligned_selection_highlights_every_visible_cluster() {
assert_eq!(quads, visible, "{align}: the selection highlights every visible cluster");
}
}
/// A pasted CRLF is stored as one line break, so the editor's count and the caret stop at the end of what was
/// inserted, not one past it per pair.
#[test]
fn a_crlf_paste_counts_and_places_the_caret_as_stored() {
let mut app = app();
click(&mut app, 100.0, 100.0, Modifiers::NONE);
let layer = LayerId(app.ui.text_edit.as_ref().expect("editing").layer);
let added = LayerHost::new(&mut app, layer).replace(0..0, "A\r\nB\rC", craft::text::ui::editor::EditKind::Pasted);
// A new layer holds its placeholder after the insertion point.
assert!(layer_text(&app).starts_with("A\nB\nC"), "{:?}", layer_text(&app));
assert_eq!(added, Some(5), "five characters were stored");
assert_eq!(app.ui.text_edit.as_ref().expect("editing").caret, 5, "the caret ends after the C");
}
+3
View File
@@ -186,6 +186,9 @@ mod pen_path_ops_tests;
#[cfg(test)]
mod pen_indexed_shape_tests;
#[cfg(test)]
mod pen_shape_mode_options_tests;
#[cfg(test)]
mod pen_rubber_band_tests;
+51 -1
View File
@@ -1,11 +1,13 @@
use craft::behavior::EditEvent;
use craft::behavior::geometry::OutlineDraft;
use craft::behavior::kurbo::Rect;
use craft::color_ui::ui::Paint;
use craft::draw::ui::pen::PathOptionsPopover;
use craft::draw::ui::shape::{self as fw, Arrowheads, ArrowheadsPopover, ShapePanel, StrokeCells, VectorMode, VectorModeSelect};
use craft::theme::Srgba;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, SideLabel, clicked};
use craft::ui::display::{Divider, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
@@ -181,6 +183,9 @@ fn pen_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut Ba
}
Divider::vertical().show(ui);
if app.ui.tool_options.vector_mode == VectorMode::Shape {
// #12907: the row leads with the Fill and Stroke swatches, the shape tools' chips with
// their popups; a pick sets the tool defaults the next Pen shape is painted with.
crate::shape_options::pen_paint_swatches(app, ui);
let ppi = document_ppi(app);
let o = &mut app.ui.tool_options;
let look = fw::ShapeAppearance::new(Paint::None, Paint::None, f64::from(o.stroke_width)).stroke_style((&o.shape_stroke).into());
@@ -200,6 +205,22 @@ fn pen_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut Ba
if let Some(alert) = out.out_of_range {
crate::option_cells::range_alert(app, ui, &alert);
}
// W and H (#12907): 0 px with no shape and the live size of the shape being drawn. What
// typing into them does was not measured, so it keeps today's behaviour — there was no
// field and no effect: these fields apply no edit (the Shape tools have no size fields
// yet either, #2496).
let (w, h) = pen_shape_size(app, tool);
// The Field shows the "W:" / "H:" caption, as the reference's row prints them; in a bar a
// Field already takes its content width. The fields are views: their output applies nothing,
// so their label offers no scrub handle either (scrub(false), unlike the editing fields).
let _ = Field::new(label(tl!("W:")))
.id_salt("pen-w")
.side(SideLabel::new().scrub(false))
.show(ui, |ui, _| NumberField::new(label(tl!("W:")), Bind::given(Some(w))).unit_kind(UnitKind::Pixels).show(ui));
let _ = Field::new(label(tl!("H:")))
.id_salt("pen-h")
.side(SideLabel::new().scrub(false))
.show(ui, |ui, _| NumberField::new(label(tl!("H:")), Bind::given(Some(h))).unit_kind(UnitKind::Pixels).show(ui));
}
// Align Edges, enabled in Shape mode only (greyed in Path mode).
super::alignment::pen_option(app, ui);
@@ -252,6 +273,35 @@ fn pen_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut Ba
}
}
/// The W / H the Pen Shape-mode bar shows (#12907): the size of the shape being drawn, 0 px when
/// there is none. The Pen and the Curvature Pen draw into `app.ui.pen`, measured with the crate's
/// one finite-guarded path bounds helper (`photocraft_text::area::path_bounds`, anchors and
/// handles): the measured shapes are straight (200 × 200 px), and what a handle beyond the anchors
/// or a typed size does was not measured and changes nothing today. A Freeform Pen trace is not a
/// path while the pointer is down: the tool keeps its live points in its own outline draft and fits
/// them into a path only when the pass ends, so that tool's row measures the draft's points and
/// falls back to `app.ui.pen` (the fitted path of a trace whose commit failed) once no trace is in
/// progress.
fn pen_shape_size(app: &PhotocraftApp, tool: Tool) -> (f64, f64) {
if tool == Tool::FreeformPen
&& let Some(size) = freeform_trace_size(&app.canvas_tools.vector.freeform.draft)
{
return size;
}
let Some(pen) = app.ui.pen.as_ref().filter(|p| !p.draft.knots.is_empty()) else { return (0.0, 0.0) };
photocraft_text::area::path_bounds(&super::pen_path(pen)).map_or((0.0, 0.0), |(x0, y0, x1, y1)| (x1 - x0, y1 - y0))
}
/// The box the Freeform Pen's live trace covers, from the points the tool paints between presses
/// (document units); `None` with no trace in progress. One point is the flat 0 x 0 the pen drafts
/// show. The draft never holds a non-finite point — a non-finite sample is dropped where it comes
/// in — so this needs no guard of its own.
fn freeform_trace_size(draft: &OutlineDraft) -> Option<(f64, f64)> {
let first = *draft.points().first()?;
let box_ = draft.points().iter().fold(Rect::from_points(first, first), |box_, &at| box_.union_pt(at));
Some((box_.width(), box_.height()))
}
/// Path mode's "Make:" row, as in Photoshop's options bar: Selection…, Mask and Shape, from the
/// path being drawn or the active path; all greyed without one.
fn make_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
@@ -0,0 +1,393 @@
//! #12907: the Pen (and Freeform / Curvature Pen) Shape-mode options bar shows Fill and Stroke
//! swatches with the shape tools' popups, stroke width and type, W / H, and Align Edges, in the
//! reference's order: Fill: swatch, Stroke: swatch, width, type, W:, H:, Align Edges (on).
//! W and H read 0 px with no shape and the live size of the shape being drawn (200 x 200 for a
//! 200 x 200 triangle); a one-anchor or a flat (line) draft keeps 0 px on its flat axis, and a
//! Freeform Pen trace still under the pointer is measured from that tool's own outline points. The
//! not-measured cases (the stroke default, typing into W / H) keep today's behaviour.
use egui::Modifiers;
use egui::accesskit::{Role, Toggled};
use egui::vec2;
use egui_kittest::{
Harness,
kittest::{NodeT, Queryable},
};
use photocraft_doc::{LayerContent, ShapeLayer};
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::testing;
use crate::state::Tool;
/// The options bar of `tool` (the bar follows `app.ui.tool`) on a 400 x 300 RGB document,
/// with the dialogs the chip popups open drawn as the app draws them.
fn bar(tool: Tool) -> Harness<'static, Box<PhotocraftApp>> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.ui.tool = tool;
let ctx = app.ctx().clone();
let mut h = Harness::builder().with_size(vec2(1800.0, 700.0)).with_step_dt(0.25).with_context(ctx).build_ui_state(
move |ui, app: &mut Box<PhotocraftApp>| {
crate::screen_picker::tick(app, ui.ctx());
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
let tool = app.ui.tool;
ui.horizontal(|ui| super::options_bar(app, ui, tool));
crate::dialogs::run(app, ui);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro());
h.run_steps(4);
h
}
/// The Pen options bar switched to Shape mode through its mode dropdown.
fn shape_bar() -> Harness<'static, Box<PhotocraftApp>> {
let mut h = bar(Tool::Pen);
pick_mode(&mut h, "Shape");
h
}
/// The Pen-family mode dropdown: the one showing a Pen mode.
fn dropdown<'a>(h: &'a Harness<'static, Box<PhotocraftApp>>) -> egui_kittest::Node<'a> {
let modes = ["Shape", "Path"];
h.query_all_by_role(Role::ComboBox).find(|n| n.value().is_some_and(|v| modes.contains(&v.as_str()))).expect("the mode dropdown")
}
/// Clicks the mode dropdown and picks its `entry`, as a hand does.
fn pick_mode(h: &mut Harness<'static, Box<PhotocraftApp>>, entry: &str) {
let at = dropdown(h).rect().center();
crate::layers_panel_nodes::click(h, at, Modifiers::NONE);
h.get_by_role_and_label(Role::ListBoxOption, entry).click();
h.run_steps(2);
}
/// The chip of the paint named `label` (a colour well, as in the shape tools' bar).
fn chip<'h>(h: &'h Harness<'static, Box<PhotocraftApp>>, label: &'h str) -> egui_kittest::Node<'h> {
h.get_by_role_and_label(Role::ColorWell, label)
}
/// Opens the chip `label` and picks its kind button `kind` ("No Color", "Solid").
fn pick_kind(h: &mut Harness<'static, Box<PhotocraftApp>>, label: &str, kind: &str) {
chip(h, label).click();
h.run_steps(3);
h.get_by_role_and_label(Role::RadioButton, kind).click();
h.run_steps(2);
h.key_press(egui::Key::Escape);
h.run_steps(2);
}
/// Clicks the popover's swatch named `name` (a list item "<name>, <hex>" in the Swatches list).
/// The list is the Solid paint's, and a group's rows show once its header is open.
fn click_swatch(h: &mut Harness<'static, Box<PhotocraftApp>>, name: &str) {
let prefix = format!("{name}, #");
let found = |h: &Harness<'static, Box<PhotocraftApp>>| {
h.query_all_by_role(Role::ListItem).any(|n| n.accesskit_node().label().as_deref().is_some_and(|l| l.starts_with(&prefix)))
};
if !found(h) {
let group = name.split(' ').next().unwrap_or(name);
if h.query_by_role_and_label(Role::Button, group).is_none() {
h.get_by_role_and_label(Role::RadioButton, "Solid").click();
h.run_steps(2);
}
if !found(h) {
h.get_by_role_and_label(Role::Button, group).click();
h.run_steps(2);
}
}
h.query_all_by_role(Role::ListItem)
.find(|n| n.accesskit_node().label().as_deref().is_some_and(|l| l.starts_with(&prefix)))
.unwrap_or_else(|| panic!("the swatch {name}"))
.click();
h.run_steps(2);
h.key_press(egui::Key::Escape);
h.run_steps(2);
}
/// The SpinButton field labelled `label`.
fn field<'h>(h: &'h Harness<'static, Box<PhotocraftApp>>, label: &'h str) -> egui_kittest::Node<'h> {
h.get_by_role_and_label(Role::SpinButton, label)
}
/// The number the field labelled `label` shows: its accessible value without the unit after it ("200 px" reads
/// "200").
fn field_text(h: &Harness<'static, Box<PhotocraftApp>>, label: &str) -> String {
let value = field(h, label).value().unwrap_or_else(|| panic!("the {label} field shows a value"));
value.split(' ').next().unwrap_or_default().to_owned()
}
/// The number the view field labelled `label` shows, as a `f64` for the cases whose size comes
/// back through the document's screen mapping and is not a round integer. The parse is deliberately
/// dot-based: the harness runs with the built-in (en) locale, so the field shows `0.5`; a locale
/// switch in the framework would show `0,5` and this would need a locale pin, not a new parser.
fn field_number(h: &Harness<'static, Box<PhotocraftApp>>, label: &str) -> f64 {
let shown = field_text(h, label);
shown.parse().unwrap_or_else(|e| panic!("the {label} field shows a number, not {shown:?} ({e})"))
}
/// Clicks a closed square with the Pen: four corners and the click back on the first anchor.
fn square(h: &mut Harness<'static, Box<PhotocraftApp>>) {
let app = h.state_mut();
for (x, y) in [(20.0, 20.0), (220.0, 20.0), (220.0, 220.0), (20.0, 220.0)] {
testing::click(app, [x, y], Modifiers::NONE);
}
testing::click(app, [20.5, 20.5], Modifiers::NONE); // close
h.run_steps(3);
}
/// The document's only shape layer; panics unless there is exactly one.
fn the_shape(h: &Harness<'static, Box<PhotocraftApp>>) -> ShapeLayer {
let st = h.state().session.active().unwrap();
let shapes: Vec<&ShapeLayer> = st
.doc
.walk()
.iter()
.filter_map(|(_, _, l)| match &l.content {
LayerContent::Shape(sh) => Some(sh),
_ => None,
})
.collect();
assert_eq!(shapes.len(), 1, "exactly one shape layer");
shapes[0].clone()
}
fn color_of(f: &photocraft_doc::Fill) -> [f32; 4] {
let photocraft_doc::Fill::Solid(c) = f else { panic!("a solid fill") };
let [r, g, b] = c.to_rgb();
[r, g, b, c.alpha]
}
// ---------------------------------------------------------------------------------------------
// Done when 1, 2 and 3 together: the measured row of the Shape-mode bar
/// The measured row: Fill swatch, Stroke swatch, stroke width, stroke type, W, H, Align Edges —
/// all present and left to right in that order.
#[test]
fn shape_mode_bar_shows_fill_stroke_wh_and_align_edges_in_measured_order() {
let h = shape_bar();
let fill = chip(&h, "Fill:").rect();
let stroke = chip(&h, "Stroke:").rect();
let width = field(&h, "Stroke width").rect();
let style = h.get_by_role_and_label(Role::Button, "Stroke style").rect();
let w = field(&h, "W:").rect();
let hh = field(&h, "H:").rect();
let align = h.get_by_label("Align Edges");
assert!(!align.accesskit_node().is_disabled(), "Align Edges is enabled in Shape mode");
assert_eq!(align.accesskit_node().toggled(), Some(Toggled::True), "Align Edges is on in Shape mode");
let left = [fill, stroke, width, style, w, hh, align.rect()];
for pair in left.windows(2) {
assert!(pair[0].min.x < pair[1].min.x, "the row order puts {:?} left of {:?}", pair[0], pair[1]);
}
}
// ---------------------------------------------------------------------------------------------
// Done when 1: a fill picked in the Pen bar paints the next Pen shape, whatever the foreground
/// The reference (#12907): with the foreground set to #3366CC, a fill picked in the Pen bar's Fill
/// swatch fills the next Pen shape; the foreground colour does not win.
#[test]
fn a_fill_picked_in_the_pen_bar_paints_the_next_pen_shape() {
let mut h = shape_bar();
h.state_mut().run("tools.setColors", json!({"foreground": [0.2, 0.4, 0.8, 1.0]})).unwrap();
h.run_steps(2);
chip(&h, "Fill:").click();
h.run_steps(4);
click_swatch(&mut h, "RGB Green");
square(&mut h);
let sh = the_shape(&h);
assert_eq!(sh.fill.as_ref().map(color_of), Some([0.0, 1.0, 0.0, 1.0]), "the picked swatch fills the Pen shape");
}
/// No Color in the Fill swatch leaves the next Pen shape unfilled; Solid brings the fill back
/// (the popup works both ways on the Pen bar, not only on the shape tools').
#[test]
fn no_colour_in_the_pen_fill_swatch_leaves_the_next_pen_shape_unfilled() {
let mut h = shape_bar();
pick_kind(&mut h, "Fill:", "No Color");
square(&mut h);
assert!(the_shape(&h).fill.is_none(), "No Color: the Pen shape has no fill");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(2);
pick_kind(&mut h, "Fill:", "Solid");
square(&mut h);
assert!(the_shape(&h).fill.is_some(), "Solid: the next Pen shape is filled again");
}
/// A Pen-bar pick edits the tool defaults, never the shape layer that happens to be active: the
/// layer keeps its own paint and no History step is added (the Pen row is the next shape's, as
/// the Shape tools' bar without a selection; Properties remains the way to edit a layer).
#[test]
fn a_pen_bar_pick_leaves_the_active_shape_layer_alone() {
let mut h = shape_bar();
h.state_mut().run("shape.create", json!({"kind": "rect", "rect": [20, 20, 60, 40], "fill": "#336699"})).unwrap();
h.run_steps(2);
let before = h.state().session.active().unwrap().history.past_len();
chip(&h, "Fill:").click();
h.run_steps(4);
click_swatch(&mut h, "RGB Green");
let app = h.state();
assert_eq!(color_of(the_shape(&h).fill.as_ref().expect("a fill")), [0.2, 0.4, 0.6, 1.0], "the active layer keeps its own fill");
assert_eq!(app.session.active().unwrap().history.past_len(), before, "no document edit");
assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0], "the pick reached the tool, as the shape tools' bar does");
}
// ---------------------------------------------------------------------------------------------
// Done when 2: W and H show 0 px with no shape and the live size while drawing
/// The measured 200 x 200: W and H read 0 before the first click and the triangle's live size
/// while it is being drawn.
#[test]
fn w_and_h_show_zero_for_no_shape_and_the_live_size_while_drawing() {
let mut h = shape_bar();
assert_eq!(field_text(&h, "W:"), "0", "no shape: 0 px");
assert_eq!(field_text(&h, "H:"), "0", "no shape: 0 px");
let app = h.state_mut();
for (x, y) in [(20.0, 20.0), (220.0, 20.0), (120.0, 220.0)] {
testing::click(app, [x, y], Modifiers::NONE);
}
h.run_steps(3);
assert_eq!(field_text(&h, "W:"), "200", "the 200 x 200 triangle: W");
assert_eq!(field_text(&h, "H:"), "200", "the 200 x 200 triangle: H");
}
/// Degenerate drafts stay 0 px rather than a negative or missing number: one anchor shows 0 x 0,
/// and a straight line (two clicks at the same y) shows 200 x 0. `pen_shape_size` guards the empty
/// draft and `path_bounds` the flat box; the pin holds before and after this PR's change, since
/// the guard is part of the code the PR adds.
#[test]
fn degenerate_drafts_show_zero_on_the_flat_axis() {
let mut h = shape_bar();
testing::click(h.state_mut(), [20.0, 120.0], Modifiers::NONE);
h.run_steps(2);
assert_eq!(field_text(&h, "W:"), "0", "one anchor: 0 px wide");
assert_eq!(field_text(&h, "H:"), "0", "one anchor: 0 px tall");
testing::click(h.state_mut(), [220.0, 120.0], Modifiers::NONE);
h.run_steps(2);
assert_eq!(field_text(&h, "W:"), "200", "the line draft: 200 px wide");
assert_eq!(field_text(&h, "H:"), "0", "the line draft: 0 px tall, not a negative height");
}
/// A Freeform Pen trace that is still under the pointer (#12907 review): while a trace is being
/// dragged its points live in the Freeform tool's own outline draft, and the shared pen draft holds
/// nothing until the pass ends, so the row measures the trace being drawn. The number itself is not
/// a measured case (the issue's measured live size is the click-drawn 200 x 200 triangle above, and
/// a freehand run has no reference number), so this pins the one thing the row must do here: follow
/// the trace instead of reading 0 px while it is still under the pointer.
#[test]
fn w_and_h_follow_a_freeform_trace_still_under_the_pointer() {
let mut h = bar(Tool::FreeformPen);
pick_mode(&mut h, "Shape");
assert_eq!(field_number(&h, "W:"), 0.0, "no trace: 0 px");
assert_eq!(field_number(&h, "H:"), 0.0, "no trace: 0 px");
let app = h.state_mut();
testing::press(app, [20.0, 20.0], Modifiers::NONE);
for at in [[120.0, 20.0], [220.0, 20.0], [220.0, 120.0], [220.0, 220.0]] {
testing::move_to(app, at, Modifiers::NONE);
}
assert!(app.canvas_tools.vector.freeform.draft.is_open(), "the trace is still being dragged");
assert!(app.ui.pen.is_none(), "and the shared pen draft holds nothing yet");
h.run_steps(2);
assert!((field_number(&h, "W:") - 200.0).abs() < 1.0, "the trace in progress is 200 px wide, not 0");
assert!((field_number(&h, "H:") - 200.0).abs() < 1.0, "the trace in progress is 200 px tall, not 0");
}
/// Not measured: what typing into W / H does. It keeps today's behaviour — the field shows the
/// live size and an edit changes neither the tool options nor the document.
#[test]
fn typing_into_w_and_h_changes_nothing() {
let mut h = shape_bar();
let before = h.state().session.active().unwrap().history.past_len();
let w_before = h.state().ui.tool_options.clone();
field(&h, "W:").click();
h.run_steps(1);
h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("123".into()));
h.key_press(egui::Key::Tab);
h.run_steps(3);
let app = h.state();
assert_eq!(app.ui.tool_options, w_before, "not measured: the fields are read-only views today");
assert_eq!(app.session.active().unwrap().history.past_len(), before, "no edit");
assert_eq!(field_text(&h, "W:"), "0", "the field keeps showing the live size");
}
// ---------------------------------------------------------------------------------------------
// Done when 3: Align Edges on in Shape mode, greyed in Path mode
/// The checkbox is on and toggles in Shape mode; Path mode has no Fill / Stroke swatch, no W / H,
/// and its Align Edges is greyed rather than hidden (main's #11756 model; the issue allows
/// "absent or greyed").
#[test]
fn align_edges_is_on_in_shape_mode_and_greyed_in_path_mode() {
let mut h = shape_bar();
h.get_by_label("Align Edges").click();
h.run_steps(3);
assert!(!h.state().ui.tool_options.align_edges, "clicking toggles the option");
assert_eq!(h.get_by_label("Align Edges").accesskit_node().toggled(), Some(Toggled::False));
pick_mode(&mut h, "Path");
assert!(h.query_by_label("Align Edges").is_some_and(|n| n.accesskit_node().is_disabled()), "Path mode: Align Edges greyed");
assert!(h.query_by_role_and_label(Role::ColorWell, "Fill:").is_none(), "Path mode: no Fill swatch");
assert!(h.query_by_role_and_label(Role::ColorWell, "Stroke:").is_none(), "Path mode: no Stroke swatch");
assert!(h.query_by_label("W:").is_none(), "Path mode: no W");
assert!(h.query_by_label("H:").is_none(), "Path mode: no H");
}
// ---------------------------------------------------------------------------------------------
// Done when 4: the stroke stays as it is today (not measured until the default is settled)
/// The stroke width field still starts at 0 px and its edit still reaches the tool options; the
/// Stroke style button is still there. The reference's 1 px default is not taken.
#[test]
fn the_stroke_width_and_type_stay_as_they_are_today() {
assert_eq!(crate::state::ToolOptions::default().stroke_width, 0.0, "today's default");
let mut h = shape_bar();
assert_eq!(h.state().ui.tool_options.stroke_width, 0.0, "the bar opens without changing the width");
assert_eq!(field_text(&h, "Stroke width"), "0", "the width field reads 0 px");
field(&h, "Stroke width").click();
h.run_steps(1);
h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("5".into()));
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert_eq!(h.state().ui.tool_options.stroke_width, 5.0, "the width field still edits the tool option");
assert!(h.query_by_role_and_label(Role::Button, "Stroke style").is_some(), "the stroke type button stays");
}
// ---------------------------------------------------------------------------------------------
// Neighbour cases: the shape tools' bar and the Pen's other modes
/// The Shape tools' bar is unchanged: Rectangle has Fill and Stroke chips and, since main merged
/// #11756, its one Align Edges (not a second one from this PR); no W / H fields (#2496); the
/// Triangle keeps its checkbox.
#[test]
fn the_shape_tools_keep_their_own_bars() {
let h = bar(Tool::Rectangle);
assert!(h.query_by_role_and_label(Role::ColorWell, "Fill color").is_some(), "the Rectangle bar keeps its Fill swatch");
assert!(h.query_by_role_and_label(Role::ColorWell, "Stroke").is_some(), "the Rectangle bar keeps its Stroke swatch");
assert!(h.query_by_label("W:").is_none(), "the Rectangle bar still has no W field (#2496)");
assert!(h.query_by_label("H:").is_none(), "the Rectangle bar still has no H field (#2496)");
let _ = h.get_by_label("Align Edges"); // exactly one, main's #11756 checkbox, not a duplicate of ours
let h = bar(Tool::Triangle);
assert!(h.query_by_label("Align Edges").is_some(), "the Triangle keeps its Align Edges (#13370)");
}
/// The Freeform Pen's and the Curvature Pen's Shape-mode branch of the same bar gains the same
/// row (the issue's Where covers all three pens); Path mode keeps its Make: row and gains nothing.
#[test]
fn the_freeform_pen_shape_bar_gains_the_same_row() {
for tool in [Tool::FreeformPen, Tool::CurvaturePen] {
let mut h = bar(tool);
pick_mode(&mut h, "Shape");
assert!(h.query_by_role_and_label(Role::ColorWell, "Fill:").is_some(), "{tool:?} Shape mode: the Fill swatch");
assert!(h.query_by_role_and_label(Role::ColorWell, "Stroke:").is_some(), "{tool:?} Shape mode: the Stroke swatch");
assert!(h.query_by_label("W:").is_some(), "{tool:?} Shape mode: W");
assert!(h.query_by_label("H:").is_some(), "{tool:?} Shape mode: H");
assert!(h.query_by_label("Align Edges").is_some(), "{tool:?} Shape mode: Align Edges");
pick_mode(&mut h, "Path");
let align = h.query_by_label("Align Edges");
assert!(align.is_none() || align.unwrap().accesskit_node().is_disabled(), "{tool:?} Path mode: Align Edges greyed or absent");
assert!(h.query_by_role_and_label(Role::Button, "Shape").is_some(), "{tool:?} Path mode: Make: Shape stays");
}
}
@@ -472,7 +472,8 @@ fn drag_task_bar_grip(h: &mut AppHarness) -> Rect {
let grip = h.get_by_label("Move bar").rect();
assert!(grip.is_positive(), "the named shared grip has real positive bounds: {grip:?}");
assert!(before.contains_rect(grip), "the pointer must hit the grip inside the visible bar");
assert!(h.state().ui.panels.task_bar.at.is_none(), "a fresh bar follows its frame before the drag");
let fresh = h.state().ui.panels.task_bar;
assert!(fresh.at.is_none() && fresh.offset.is_none(), "a fresh bar follows its frame before the drag");
let area = view(h.state()).rect;
let from = grip.center();
let delta = egui::vec2(40.0, -24.0);
@@ -485,10 +486,12 @@ fn drag_task_bar_grip(h: &mut AppHarness) -> Rect {
assert_eq!(after.size(), before.size(), "a grip drag moves the bar without resizing it");
let movement = after.min - before.min;
assert!(movement.length() > 12.0 && movement.dot(delta) > 0.0, "the grip must move the bar: {before:?} -> {after:?}");
// An unpinned bar keeps the drop as its offset from its unmoved place and goes on following the frame.
let place = h.state().ui.panels.task_bar;
let [x, y] = place.at.expect("a grip drag stores the canvas-relative bar position");
assert!((after.min - (area.min + egui::vec2(x, y))).length() <= 1.0, "the displayed bar must use the saved position");
assert_eq!(bar(h)["at"], json!([x, y]));
assert!(place.at.is_none(), "an unpinned bar keeps no fixed position: {place:?}");
let [x, y] = place.offset.expect("a grip drag stores the bar's offset from its unmoved place");
assert!((movement - egui::vec2(x, y)).length() <= 1.0, "the displayed bar must use the saved offset: {movement:?} vs {place:?}");
assert_eq!(bar(h)["offset"], json!([x, y]));
// This is the same serialized panel-layout field used across restarts, not a transient Area rect.
let restored: crate::state::TaskBarPlace = serde_json::from_value(serde_json::to_value(place).unwrap()).unwrap();
assert_eq!(restored, place);
+3 -3
View File
@@ -1,7 +1,7 @@
//! The Zoom tool on the whole app: the GPU canvas keeps its composite while a zoom eases, and the
//! temporary and spring zooms ignore the Zoom Out mode of the options bar.
use craft::behavior::canvas::ZoomLadder;
use craft::behavior::canvas::ZoomScheme;
use craft::behavior::kurbo::Size;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
@@ -82,7 +82,7 @@ fn temporary_and_spring_zooms_ignore_the_zoom_out_mode() {
key(&mut h, held, false, Modifiers::NONE);
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(2);
let want = ZoomLadder::step(f64::from(start), dir, doc_size()) as f32;
let want = ZoomScheme::PHOTOSHOP.step(f64::from(start), dir, doc_size()) as f32;
assert!((h.state().current_zoom() - want).abs() < 1e-5, "{name}: {} vs {want}", h.state().current_zoom());
assert_eq!(h.state().ui.tool, Tool::Brush, "{name}: the selected tool is unchanged");
assert!(!h.state().ui.tool_options.zoom_in, "{name}: Zoom Out stays selected");
@@ -124,7 +124,7 @@ mod gpu_tests {
}
h.state_mut().run("view.zoomIn", json!({})).unwrap();
// The canvas runs the command in its next pass: the zoom it asks for is the rung after 100 %.
let target = craft::behavior::canvas::ZoomLadder::step(1.0, 1, craft::behavior::kurbo::Size::new(400.0, 300.0)) as f32;
let target = craft::behavior::canvas::ZoomScheme::PHOTOSHOP.step(1.0, 1, craft::behavior::kurbo::Size::new(400.0, 300.0)) as f32;
// The ease's length belongs to the framework's motion settings, so the steps are short and the test looks for a
// frame between the start and the target zoom rather than naming a time for it.
let mut midway = false;
+8 -5
View File
@@ -141,21 +141,24 @@ fn ui_set_changes_only_the_place_fields_it_names() {
draw_frame(&mut h, [40.0, 30.0], [260.0, 200.0]);
drag_grip(&mut h, vec2(-60.0, -120.0));
let dropped = bar(&h).expect("bar");
let at = h.state().ui.panels.task_bar.at;
// Pinning keeps the dragged place: the bar doesn't jump back under the frame.
// Unpinned, the drop is an offset from the bar's place under the frame.
let place = h.state().ui.panels.task_bar;
assert!(place.at.is_none() && place.offset.is_some(), "{place:?}");
// Pinning keeps the dragged place: the bar doesn't jump back under the frame, and stays where it shows.
control(&mut h, "ui.set", json!({"panels": {"task_bar": {"pinned": true}}}));
assert_eq!(h.state().ui.panels.task_bar.at, at);
assert!(h.state().ui.panels.task_bar.pinned);
assert!(h.state().ui.panels.task_bar.at.is_some(), "a pinned bar holds its position");
assert_eq!(bar(&h).expect("bar").left_top(), dropped.left_top());
// Placing it keeps the pin.
control(&mut h, "ui.set", json!({"panels": {"task_bar": {"at": [12.0, 34.0]}}}));
assert_eq!(h.state().ui.panels.task_bar, photocraft_ui_egui::state::TaskBarPlace::new(true, Some([12.0, 34.0])));
assert!(h.state().ui.panels.task_bar.pinned);
assert_eq!(h.state().ui.panels.task_bar.at, Some([12.0, 34.0]));
// A field the bar doesn't have is refused, and nothing changes.
let v = request(&mut h, "ui.set", json!({"panels": {"task_bar": {"pinned": false, "nope": 1}}}));
assert_eq!(v["ok"], false, "{v}");
assert!(h.state().ui.panels.task_bar.pinned);
// Reset bar position over the control channel.
control(&mut h, "ui.set", json!({"panels": {"task_bar": {"pinned": false, "at": null}}}));
control(&mut h, "ui.set", json!({"panels": {"task_bar": {"pinned": false, "at": null, "offset": null}}}));
assert_eq!(h.state().ui.panels.task_bar, Default::default());
let v = request(&mut h, "ui.inspect", json!({}));
assert_eq!(v["result"]["taskBar"]["at"], Value::Null, "after the reset the bar follows the frame again");
+5 -3
View File
@@ -342,12 +342,14 @@ mod gpu_tests {
};
h.run_steps(4);
assert!(h.state_mut().destroy_window_device());
for _ in 0..120 {
// wgpu reports the loss from its own thread: poll for it, often, for up to 30 s.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
loop {
h.run_steps(1);
if h.state().window_lost() {
if h.state().window_lost() || std::time::Instant::now() >= deadline {
break;
}
std::thread::sleep(std::time::Duration::from_millis(250));
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(h.state().window_lost(), "the loss was noticed");
let tries = || attempts.load(std::sync::atomic::Ordering::SeqCst);