Merge pull request #16691 from davidmann4/batch/16665-16598

PhotoCraft 0.24 on craft-libs next, with the RAW Develop window fix (#16665 + #16598)
This commit is contained in:
aiongg authored and GitHub committed 2026-11-24 22:06:45 -05:00
commit 8a3ff6c089
71 files changed
+810 -449

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"
+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 }
@@ -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);
+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() {
+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");
@@ -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),
};
@@ -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");
}
+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");
}
@@ -112,9 +112,11 @@ fn field<'h>(h: &'h Harness<'static, Box<PhotocraftApp>>, label: &'h str) -> egu
h.get_by_role_and_label(Role::SpinButton, label)
}
/// The text the field labelled `label` shows (its accessible value: the bare number).
/// 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 {
field(h, label).value().unwrap_or_else(|| panic!("the {label} field shows a value"))
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
@@ -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");