Merge origin/main (d06ad7327, #12403 RAW Develop) into craft-i18n-cutover

Keeps the TSV deletions. The Hindi and RAW Develop catalog tests read the
embedded craft-i18n catalogs behind needs_catalogs(); display_names scans
CRAFT_I18N_DIR's locales/*/photocraft.tsv instead of the deleted src/i18n.
Pins craft-i18n 31d158f (storytold/craft-i18n#216 head, the #12403 top-up)
until #216 merges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Martin BallandClaude Opus 5.5 committed 2026-11-09 07:38:51 +00:00
commit 8d8fb69d6d
72 files changed
+2905 -233

No files matched your search

Generated
+14 -27
View File
@@ -1406,17 +1406,17 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1439,7 +1439,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"thiserror 2.0.21",
]
@@ -1457,7 +1457,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"bytemuck",
"hayro",
@@ -1469,7 +1469,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1483,7 +1483,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1504,7 +1504,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -1530,7 +1530,7 @@ dependencies = [
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f"
dependencies = [
"windows-sys 0.61.2",
]
@@ -2964,7 +2964,7 @@ dependencies = [
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"bytemuck",
"hayro-interpret",
@@ -2994,7 +2994,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3012,7 +3012,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3036,7 +3036,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -9474,7 +9474,7 @@ dependencies = [
[[package]]
name = "winprint"
version = "0.2.1"
source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49"
source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4"
dependencies = [
"flate2",
"fmt-derive",
@@ -10008,7 +10008,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -10023,18 +10022,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.4.12"
+10 -10
View File
@@ -10,7 +10,7 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
@@ -39,17 +39,17 @@ photocraft-tablet = { path = "crates/tablet" }
photocraft-ipp = { path = "crates/ipp" }
# external
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["raster"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" }
# 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-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
# 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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
@@ -209,7 +209,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
+2 -1
View File
@@ -68,7 +68,7 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[
("DPX and Cineon", &["dpx", "cin"]),
("Amiga IFF", &["iff", "lbm", "ilbm"]),
("DICOM", &["dcm", "dicom", "dc3"]),
("Camera Raw", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("Brushes", &["abr"]),
("Gradients", &["grd"]),
("Styles", &["asl"]),
@@ -763,6 +763,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))),
beep: Some(platform_beep),
check_updates: Some(crate::updates::service()),
last_update: Some(crate::updates::last_update),
clipboard_set_image: Some({
let clip = clip.clone();
guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| {
+3 -1
View File
@@ -218,7 +218,9 @@ fn open_filters_keep_literal_extensions_on_windows_and_macos() {
#[test]
fn native_services_provide_update_transport() {
assert!(native(None).check_updates.is_some());
let services = native(None);
assert!(services.check_updates.is_some());
assert!(services.last_update.is_some());
}
#[test]
+13
View File
@@ -20,6 +20,19 @@ pub fn service() -> CheckFn {
})
}
/// What the last self-update came to, once: `craft-update` removes its records as it reads them.
pub fn last_update() -> Option<Result<String, String>> {
use craft_update::self_update::{Outcome, current_version, take_outcome};
let app = &photocraft_ui_egui::UPDATE_APP;
let paths = craft_update::Paths::for_app(app).ok()?;
let version = photocraft_engine::build_info::VERSION;
let running = current_version(app, version).map_or_else(|| version.to_string(), |v| v.to_string());
match take_outcome(&paths, &running)? {
Outcome::Installed(installed) => Some(Ok(installed.to_string())),
Outcome::Failed(reason) => Some(Err(reason)),
}
}
fn check() -> CheckResult {
let http = craft_update::Http::new("PhotoCraft/Update")?;
let found = craft_update::check_for_update(&photocraft_ui_egui::UPDATE_APP, &http, photocraft_engine::build_info::VERSION)?;
+1 -1
View File
@@ -1 +1 @@
723a3b49ca26899acc838262478f65d59ac1bc26
31d158f9ee077086e3bb446909e8129bc8092d3b
+12 -3
View File
@@ -71,6 +71,8 @@ pub mod contour_lib_cmds;
mod count_delete_group_tests;
#[cfg(test)]
mod count_history_names_tests;
#[cfg(test)]
mod count_record_label_tests;
pub mod cutout_cmds;
pub mod distort_cmds;
pub mod document_preset_cmds;
@@ -100,6 +102,7 @@ pub mod history_select_cmds;
pub mod history_source_cmds;
pub mod image_cmds;
pub mod layer_copy_cmds;
pub mod layer_css_cmds;
pub mod layer_label_cmds;
pub mod layer_list_cmds;
pub mod layer_mask_props_cmds;
@@ -205,9 +208,14 @@ pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option<String>) -> Value
/// Other names a command is looked for by, beyond its id and label: the Photoshop tools and
/// options it stands for (#5060). `select.rect` is also the Elliptical and Single Row/Column
/// Marquee, which an agent searches for as "ellipse" or "marquee".
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] =
&[("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")")];
/// Marquee, which an agent searches for as "ellipse" or "marquee". The RAW Develop filter and
/// RAW Defaults keep Photoshop's "Camera Raw" name as a search alias only: the menus and windows
/// say "RAW Develop" (#12403).
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = &[
("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")"),
("filter.cameraRaw", "Camera Raw Filter"),
("edit.preferences.rawDefaults", "Camera Raw Defaults"),
];
/// [`SEARCH_KEYWORDS`] of command `id`, if it has any.
pub fn search_keywords(id: &str) -> Option<&'static str> {
@@ -1395,6 +1403,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::adjust_cmds::specs());
v.extend(crate::layer_menu_cmds::specs());
v.extend(crate::layer_label_cmds::specs());
v.extend(crate::layer_css_cmds::specs());
v.extend(crate::layer_xmp_cmds::specs());
v.extend(crate::mode_cmds::specs());
v.extend(crate::multichannel_cmds::specs());
+3 -1
View File
@@ -1099,7 +1099,9 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
other => return Err(bad(CMD, format!("unknown source `{other}` (auto|selection|ruler|count)"))),
};
// Numbered only once the rows exist, so a failed measurement does not use up a label.
let label = format!("Measurement {}", s.analysis.next_measurement + 1);
// A count's row is "Count N" (#11775); the number is the shared one.
let word = if source == "count" { "Count" } else { "Measurement" };
let label = format!("{word} {}", s.analysis.next_measurement + 1);
let now = p.get("dateTime").and_then(Value::as_str).map(str::to_string).unwrap_or_else(now_iso);
let factor = d.measurement.scale.factor();
let mut rows: Vec<Map<String, Value>> = Vec::new();
+3
View File
@@ -616,6 +616,9 @@ pub(super) const EVENTS: &[Event] = &[
Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to },
// What Photoshop needs in a written step (process version, the full settings set) is
// unverified, so only an imported step saves back, as its recorded descriptor while unedited.
// The label is interchange data, not a display name: Save Actions writes it into the step's
// dictionary (convert.rs), so it stays Photoshop's wording and a loaded step round-trips. The
// menu item and window title come from `lens_cmds` and read "RAW Develop Filter".
Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[crate::lens_cmds::RAW], from: camera_raw_from, to: camera_raw_to },
// Video, Other, Average and matting (#10607).
Event {
+6 -3
View File
@@ -3832,13 +3832,16 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() {
assert_eq!(s.actions.list[0].steps[0].0, "filter.cameraRaw");
let saved_step = |r: &Value| {
let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
saved.actions[0].items.first().map(|i| (i.event.clone(), i.descriptor.clone()))
saved.actions[0].items.first().map(|i| (i.event.clone(), i.dictionary.clone(), i.descriptor.clone()))
};
// Strict save, and the Actions panel's save (which skips what can't be written).
// Strict save, and the Actions panel's save (which skips what can't be written). The step's
// dictionary is stored action data, so it keeps Photoshop's wording and not the menu label
// ("RAW Develop Filter"): a loaded step reads the same in Photoshop's Actions panel.
for skip in [false, true] {
let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": skip})).unwrap();
assert_eq!(r["skipped"], json!([]), "{r}");
assert_eq!(saved_step(&r), Some((AtnEvent::name("Adobe Camera Raw Filter"), Some(recorded.clone()))));
let expected = (AtnEvent::name("Adobe Camera Raw Filter"), b"Camera Raw Filter".to_vec(), Some(recorded.clone()));
assert_eq!(saved_step(&r), Some(expected));
}
// It plays.
s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
@@ -0,0 +1,132 @@
//! The Background Eraser on a layer with Lock transparent pixels on (#11905): the reference
//! application erases to transparency exactly as on an unlocked layer, leaves the lock on and shows
//! no alert. Lock image pixels and Lock all still refuse; the Eraser and the Magic Eraser keep their
//! own lock behaviour (they paint the background colour).
use super::*;
/// White Background plus a normal layer "Target" with a solid red band across it (y 10..30).
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 40, "depth": depth})).unwrap();
s.execute("layer.new.layer", json!({"name": "Target"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 10, "width": 64, "height": 20, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s
}
fn target(s: &Session) -> &Layer {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap()
}
fn alphas(s: &Session) -> Vec<f32> {
let surf = target(s).surface().unwrap();
(0..40).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)[3]).collect()
}
fn click() -> Value {
json!({"points": [[32, 20]], "size": 20, "hardness": 1, "tolerance": 50})
}
#[test]
fn a_click_on_a_transparency_locked_layer_erases_as_on_an_unlocked_one() {
for depth in [8, 16, 32] {
let mut free = session(depth);
free.execute("paint.backgroundEraser", click()).unwrap();
let want = alphas(&free);
let mut s = session(depth);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
let h = s.active().unwrap().history.past_len();
s.execute("paint.backgroundEraser", click()).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), h + 1, "{depth}-bit: one History step");
assert_eq!(target(&s).surface().unwrap().rgba(32, 20)[3], 0.0, "{depth}-bit: erased to transparency");
assert_eq!(alphas(&s), want, "{depth}-bit: the same alpha as on an unlocked layer");
assert!(target(&s).locks.transparency, "{depth}-bit: the lock stays on");
assert_eq!(target(&s).name, "Target", "{depth}-bit: the same layer");
}
}
#[test]
fn a_drag_and_the_live_preview_erase_a_transparency_locked_layer_too() {
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 12, "hardness": 1});
let all = [[8.0, 20.0], [32.0, 20.0], [56.0, 20.0]];
let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
for q in &all[1..] {
live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
}
let id = s.active().unwrap().active_layer.unwrap();
let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
s.execute("paint.backgroundEraser", opts(&all)).unwrap();
let surf = target(&s).surface().unwrap();
for x in [8, 32, 56] {
assert_eq!(surf.rgba(x, 20)[3], 0.0, "({x}, 20) erased");
assert_eq!(shown.rgba(x, 20)[3], 0.0, "the preview shows ({x}, 20) erased");
}
assert_eq!(surf.rgba(32, 5)[3], 0.0, "transparent pixels stay transparent");
assert!(target(&s).locks.transparency);
}
#[test]
fn with_a_colour_channel_target_the_preview_matches_the_commit_on_a_locked_layer() {
// A channel target erases colour channels only (towards the background colour) and never
// changes alpha. The commit mixes back without the lock, so the preview must too: at 32 bits
// a lock-keeping mix rounds partly transparent pixels differently. The stroke crosses the
// band's edge and a half-transparent strip, at half opacity, so every mix case is under the tip.
for depth in [8, 16, 32] {
let mut s = session(depth);
s.execute("select.rect", json!({"x": 0, "y": 4, "width": 64, "height": 6, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": "#3a7fd0", "opacity": 37})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 16, "hardness": 0.5, "opacity": 0.53, "target": {"colors": [1]}});
let all = [[8.0, 9.0], [32.0, 10.0], [56.0, 11.0]];
let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
for q in &all[1..] {
live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
}
let id = s.active().unwrap().active_layer.unwrap();
let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
let before = alphas(&s);
s.execute("paint.backgroundEraser", opts(&all)).unwrap();
let surf = target(&s).surface().unwrap();
assert!(surf.rgba(32, 12)[1] > 0.0, "{depth}-bit: the green channel moved towards the white background");
for (x, y) in (0..40).flat_map(|y| (0..64).map(move |x| (x, y))) {
assert_eq!(shown.rgba(x, y), surf.rgba(x, y), "{depth}-bit ({x}, {y}): preview = commit");
}
assert_eq!(alphas(&s), before, "{depth}-bit: alpha untouched");
}
}
#[test]
fn locked_pixels_and_lock_all_still_refuse() {
for locks in [json!({"pixels": true}), json!({"all": true})] {
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": locks})).unwrap();
let before = alphas(&s);
let h = s.active().unwrap().history.past_len();
let err = s.execute("paint.backgroundEraser", click()).unwrap_err().to_string();
assert!(err.contains("Could not complete your request because the layer \"Target\" is locked"), "{locks}: {err}");
assert!(live_background_eraser(&s, &click()).is_err(), "{locks}: the preview refuses too");
assert_eq!(alphas(&s), before, "{locks}: nothing erased");
assert_eq!(s.active().unwrap().history.past_len(), h, "{locks}: no History step");
}
}
#[test]
fn the_eraser_and_the_magic_eraser_keep_painting_the_background_colour() {
// Magic Eraser: the background colour (white by default), still opaque.
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
s.execute("paint.magicEraser", json!({"x": 32, "y": 20})).unwrap();
assert_eq!(target(&s).surface().unwrap().rgba(32, 20), [1.0, 1.0, 1.0, 1.0]);
// Eraser: the same.
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
s.execute("paint.stroke", json!({"erase": true, "points": [[8, 20], [56, 20]], "size": 8, "hardness": 1.0})).unwrap();
assert_eq!(target(&s).surface().unwrap().rgba(32, 20), [1.0, 1.0, 1.0, 1.0]);
}
@@ -0,0 +1,52 @@
//! #11775: Record Measurements labels a Count tool row "Count N"; selection and ruler rows keep
//! their labels, and N is the number the row gets today (the shared counter).
use serde_json::{Value, json};
use crate::Session;
fn five_counts() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
for i in 0..5 {
s.execute("count.add", json!({"x": 10 + 10 * i, "y": 10})).unwrap();
}
s
}
fn record(s: &mut Session, source: &str) -> Value {
let r = s.execute("image.analysis.recordMeasurements", json!({"source": source})).unwrap();
let rows = r["rows"].as_array().unwrap();
assert_eq!(rows.len(), 1, "{source}: {r}");
rows[0]["values"].clone()
}
#[test]
fn a_count_row_is_labelled_count_n() {
for source in ["count", "auto"] {
let mut s = five_counts();
let row = record(&mut s, source);
assert_eq!(row["label"], json!("Count 1"), "{source}: {row}");
assert_eq!(row["count"], json!(5), "{source}: {row}");
assert_eq!(row["source"], json!("Count Tool"), "{source}: {row}");
}
}
#[test]
fn other_rows_keep_their_labels_and_the_counter_is_shared() {
let mut s = five_counts();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
let selection = record(&mut s, "selection");
assert_eq!(selection["label"], json!("Measurement 1"), "{selection}");
let count = record(&mut s, "count");
assert_eq!(count["label"], json!("Count 2"), "{count}");
// `auto` picks the selection over the counts, and keeps its label.
let auto = record(&mut s, "auto");
assert_eq!(auto["source"], json!("Selection"), "{auto}");
assert_eq!(auto["label"], json!("Measurement 3"), "{auto}");
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [3, 4]})).unwrap();
let ruler = record(&mut s, "ruler");
assert_eq!(ruler["label"], json!("Measurement 4"), "{ruler}");
let count = record(&mut s, "count");
assert_eq!(count["label"], json!("Count 5"), "{count}");
}
+21 -10
View File
@@ -4,8 +4,9 @@
//!
//! Like Photoshop, both turn a Background layer into a normal layer ("Layer 0") first, since the
//! Background can't hold transparency. The Magic Eraser paints the background colour on other
//! layers with locked transparency; the Background Eraser refuses them. Both respect the selection,
//! work in the layer's own colour model and depth, and are one undo step per click / stroke.
//! layers with locked transparency; the Background Eraser erases them to transparency and leaves
//! the lock on. Both respect the selection, work in the layer's own colour model and depth, and are
//! one undo step per click / stroke.
use photocraft_algo::selection as sel;
use photocraft_doc::{Document, Layer, LayerContent, LayerId};
@@ -148,12 +149,11 @@ fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSet
let id = active_pixel_layer(s, p, CMD)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
// Lock transparent pixels is no refusal: the reference application erases to transparency
// anyway and leaves the lock on.
if let Some(e) = pixels_locked(&d.doc, l) {
return Err(e);
}
if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) && crate::color_channels::target(s, p)?.is_none() {
return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
}
Ok((Stroke { brush, points: pts }, bs, id))
}
@@ -234,19 +234,27 @@ pub fn live_background_eraser(s: &Session, p: &Value) -> Result<crate::retouch_c
if colors.is_none() {
crate::extra_cmds::background_to_layer(&mut doc, id);
}
let stroke = background_eraser_stroke(&stroke);
let mut stroke = background_eraser_stroke(&stroke);
// The commit mixes back without the transparency lock (a locked layer is erased too, and a
// channel target leaves alpha alone), so the preview does as well; the points go in once the
// lock is off.
let points = std::mem::take(&mut stroke.points);
if let Some(colors) = colors {
return crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({"target":colors.params()}), stroke, Some(id), 0, |pre| {
let mut live = crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({"target":colors.params()}), stroke, Some(id), 0, |pre| {
selected_background_effect(pre, &bs, colors, bg)
})?
.with_tail_preview();
.unlocked();
live.push(&points)?;
return live.with_tail_preview();
}
crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &bs) {
let mut live = crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &bs) {
Some(effect) => Box::new(effect),
// No alpha: the commit erases nothing either.
None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}),
})?
.with_tail_preview()
.unlocked();
live.push(&points)?;
live.with_tail_preview()
}
/// Eraser-group command specs.
@@ -277,3 +285,6 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "background_eraser_transparency_lock_tests.rs"]
mod transparency_lock_tests;
+3 -3
View File
@@ -230,11 +230,11 @@ fn background_eraser_fails_gracefully() {
] {
assert!(s.execute("paint.backgroundEraser", p.clone()).is_err(), "{p}");
}
// A normal layer with locked transparency is refused.
// A layer with locked pixels is refused.
s.execute("layer.new.layer", json!({})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
s.edit("lock", |doc, _| {
doc.layer_mut(id).unwrap().locks.transparency = true;
doc.layer_mut(id).unwrap().locks.pixels = true;
Ok(())
})
.unwrap();
@@ -319,7 +319,7 @@ fn live_background_eraser_matches_the_commit() {
fn live_background_eraser_refuses_what_the_command_refuses() {
let mut s = session("rgb", 8);
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();
let p = json!({"points": [[20, 20]]});
assert!(live_background_eraser(&s, &p).is_err());
assert!(s.execute("paint.backgroundEraser", p).is_err());
+376
View File
@@ -0,0 +1,376 @@
//! Layer › Copy CSS (#9372): CSS for the selected layers, in the form Photoshop writes. The
//! command returns the text; the shell puts it on the clipboard.
//!
//! Each layer is a class named after it (punctuation and spaces become `_`, and a leading digit
//! gets a `_` in front). What is written, in this order:
//! - a type layer: `font-size`, `font-family`, `color`, `line-height` and `text-align`, from its
//! first run and first paragraph;
//! - a live rounded rectangle: `border-radius`; a live ellipse: `border-radius: 50%`;
//! - a shape or fill layer with a solid colour: `background-color`; any other layer (pixels,
//! gradient or pattern fills, smart objects): `background-image`, an image named after it;
//! - `opacity` when it isn't 100 %;
//! - `position: absolute`, `left` and `top`, and `width` and `height` except for point type;
//! - `z-index`, its place in the stack counted from the bottom layer as 1, where a group takes
//! two places (its own, and one below its layers for the group's end).
//!
//! A group writes only its box (the canvas, or its artboard) and z-index, followed by the rule
//! of every layer in it, top first. A fill layer without a vector mask and an adjustment layer
//! have no rule, and Copy CSS is off when no selected layer has one. Point type is placed as
//! Photoshop places it (see [`place_point_text`]).
//!
//! Not written: strokes (`border`), layer effects (`box-shadow`, `text-shadow`), gradients as
//! CSS gradients, blend modes (`mix-blend-mode`), fill opacity, the styles of later runs and
//! paragraphs, the corners of a rounded rectangle scaled unequally (elliptical, while it keeps
//! one radius per corner), and the geometry of other shapes (live polygons, stars and lines, and
//! custom paths), which get the rule of their box.
use std::collections::HashMap;
use std::sync::PoisonError;
use photocraft_doc::text::{Orientation, TextAlign, TextShape};
use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerId, LiveShape, Path, TextLayer};
use photocraft_geom::{Point, Rect};
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
pub const ID: &str = "layer.copyCSS";
fn bad(message: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: ID.into(), msg: message.into() }
}
/// Deepest group nesting followed; deeper layers are left out rather than recursing without end.
const MAX_DEPTH: usize = 256;
fn enabled(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
let ids = st.selected_layers();
if ids.is_empty() {
return Err("no layer selected".into());
}
// Photoshop greys Copy CSS out for a fill layer without a shape (measured), and for an
// adjustment layer, which has nothing to place either.
if st.doc.walk().iter().any(|(_, _, l)| ids.contains(&l.id) && has_css(l)) { Ok(()) } else { Err("no selected layer has CSS".into()) }
}
/// Whether a layer can have a rule (one with nothing to place still gets none).
fn has_css(l: &Layer) -> bool {
match &l.content {
LayerContent::Adjustment(_) => false,
LayerContent::Fill(_) => l.vector_mask.is_some(),
_ => true,
}
}
/// A number as Photoshop writes it in CSS: at most three decimals, no trailing zeros.
pub fn number(v: f64) -> String {
let v = if v.is_finite() { (v * 1000.0).round() / 1000.0 } else { 0.0 };
decimals(v)
}
/// A `left` or `top` as Photoshop writes it: cut after three decimals, not rounded (measured:
/// 49.8125 is `49.812px`, 176.5668 is `176.566px`). The nudge keeps 127.1, computed as
/// 127.0999…, at `127.1`.
pub fn position(v: f64) -> String {
let v = if v.is_finite() { (v * 1000.0 + 1e-6).floor() / 1000.0 } else { 0.0 };
decimals(v)
}
fn decimals(v: f64) -> String {
let s = format!("{v:.3}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".into() } else { s.to_string() }
}
/// The class name for a layer: its name with every character other than a letter, digit or `_`
/// as `_` (a hyphen too, as Photoshop does), and a `_` in front when it starts with a digit,
/// which a class selector can't.
pub fn class_name(name: &str) -> String {
let s: String = name.chars().map(|c| if c.is_alphanumeric() || c == '_' { c } else { '_' }).collect();
if s.is_empty() {
"layer".into()
} else if s.starts_with(|c: char| c.is_ascii_digit()) {
format!("_{s}")
} else {
s
}
}
/// `s` as a double-quoted CSS string, escaped as CSSOM serializes one: `"` and `\` get a
/// backslash, control characters (line breaks among them) become hex escapes, NUL becomes U+FFFD.
pub fn quoted(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'\0' => out.push('\u{FFFD}'),
'\u{1}'..='\u{1F}' | '\u{7F}' => out.push_str(&format!("\\{:x} ", u32::from(c))),
'"' | '\\' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
out.push('"');
out
}
/// The image Photoshop names after a layer, as a `url()`.
fn image(l: &Layer) -> String {
format!("url({})", quoted(&format!("{}.png", l.name)))
}
fn rgb(c: &photocraft_color::Color) -> String {
let [r, g, b] = c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
format!("rgb({r}, {g}, {b})")
}
/// Whether `path` is the outline `live` draws: every anchor of one is an anchor of the other,
/// within a hundredth of a pixel, in any order or direction (a flipped shape runs the other way).
/// A live rectangle scaled unequally keeps one radius per corner, but its path keeps the corners
/// it was drawn with, now elliptical, so the two differ.
fn draws(live: &LiveShape, path: &Path) -> bool {
let anchors = |p: &Path| p.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor)).collect::<Vec<_>>();
let (have, want) = (anchors(path), anchors(&photocraft_vector::shapes::live_path(live)));
let among = |p: &Point, q: &[Point]| q.iter().any(|q| (p.x - q.x).abs() < 0.01 && (p.y - q.y).abs() < 0.01);
have.iter().all(|p| among(p, &want)) && want.iter().all(|p| among(p, &have))
}
/// Where Photoshop places point type, from its pixel bounds `pix`, its ink `ink` (`[x0, y0, x1,
/// y1]` from its origin, unrounded), its first baseline `baseline` in the same space, the cap
/// height `cap` of its font and its size and line height in px. Measured on Arial and Times New
/// Roman at 24 and 48 px, with auto and explicit leading:
/// - `left` is the pixel left less the ink's offset from the origin ("Hello": 52 − 1.875 =
/// `50.125`);
/// - without a descender, the line box is centred on the pixels ("Hello", pixels 132–151, line
/// 28.8: 141.5 − 14.4 = `127.1`);
/// - with one, on half the cap height above the baseline the pixels give ("xyz" in Arial, top
/// pixel 187, ink top −12.5625, cap 17.19: 199.5625 − (28.8 + 17.19) / 2 = `176.566`).
pub fn place_point_text(pix: Rect, ink: [f64; 4], baseline: f64, cap: f64, size_px: f64, line_height_px: f64) -> Point {
let left = f64::from(pix.x0) - ink[0];
// An "o" overshoots the baseline by a hair, a "g" by a fifth of the size.
let top = if ink[3] - baseline > 0.05 * size_px {
f64::from(pix.y0) - (ink[1] - baseline) - (line_height_px + cap) / 2.0
} else {
(f64::from(pix.y0) + f64::from(pix.y1)) / 2.0 - line_height_px / 2.0
};
Point::new(left, top)
}
/// [`place_point_text`] for a type layer, from its layout; `None` (placed at its pixels) when
/// there is nothing to measure: no pixels or ink, no font, or type that is turned, scaled,
/// warped or vertical.
fn point_text_origin(t: &TextLayer, pix: Rect, dpi: f32, family: &str, size_pt: f32, line_height: f64) -> Option<Point> {
let [a, b, c, d, _, _] = t.transform.m;
if pix.is_empty() || a != 1.0 || b != 0.0 || c != 0.0 || d != 1.0 || t.warp.is_some() || t.orientation != Orientation::Horizontal {
return None;
}
let size_px = f64::from(size_pt) * f64::from(dpi) / 72.0;
let cap_layer = TextLayer { text: "H".into(), font_family: family.into(), size_pt, ..Default::default() };
let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner);
let layout = eng.layout(t, dpi);
let ink = photocraft_text::render::ink_bounds(&layout)?;
let baseline = f64::from(layout.lines.first()?.baseline);
let cap_layout = eng.layout(&cap_layer, dpi);
let cap = f64::from(cap_layout.lines.first()?.baseline) - photocraft_text::render::ink_bounds(&cap_layout)?[1];
// Photoshop works with the line height it writes, three decimals of the size.
let line_height_px = (line_height * 1000.0).round() / 1000.0 * size_px;
let at = place_point_text(pix, ink, baseline, cap, size_px, line_height_px);
(at.x.is_finite() && at.y.is_finite()).then_some(at)
}
/// The box of a group's rule: its artboard, else the canvas (measured: a group holding a 50 × 30
/// layer writes the 400 × 300 canvas).
fn group_bounds(doc: &Document, l: &Layer) -> Rect {
let r = photocraft_doc::comps::position_bounds(l);
if r.is_empty() { doc.bounds() } else { r }
}
/// The rule for one layer, `z` its place in the stack from the bottom (1-based); `None` for a
/// layer CSS can't describe (adjustments, fill layers without a shape) or one with nothing to
/// place. A group's rule is its box alone; [`copy_css`] adds the rules of its layers.
pub fn rule(doc: &Document, z: usize, l: &Layer) -> Option<String> {
let px_per_pt = f64::from(doc.resolution_dpi.max(1.0)) / 72.0;
let mut props: Vec<(&str, String)> = Vec::new();
let mut sized = true;
let mut bounds = photocraft_doc::comps::position_bounds(l);
// Where the rule starts when it isn't where the layer's pixels start.
let mut origin: Option<Point> = None;
if !has_css(l) {
return None;
}
match &l.content {
LayerContent::Adjustment(_) => return None,
LayerContent::Group(_) => bounds = group_bounds(doc, l),
LayerContent::Text(t) => {
let style = t.runs.first().map(|r| &r.style);
let size_pt = style.map_or(t.size_pt, |s| s.size_pt);
let family = style.map(|s| s.font_family.as_str()).filter(|f| !f.is_empty()).unwrap_or(&t.font_family);
let color = style.map_or(t.color, |s| s.color);
let paragraph = t.paragraphs.first().map(|p| p.style.clone()).unwrap_or_default();
// Auto leading is the paragraph's multiple of the size (1.2 by default).
let line_height = match style.and_then(|s| s.leading_pt) {
Some(leading) if size_pt > 0.0 => f64::from(leading / size_pt),
_ => f64::from(paragraph.auto_leading),
};
let align = match paragraph.align {
TextAlign::Left => "left",
TextAlign::Center => "center",
TextAlign::Right => "right",
_ => "justify",
};
props.push(("font-size", format!("{}px", number(f64::from(size_pt) * px_per_pt))));
props.push(("font-family", quoted(family)));
props.push(("color", rgb(&color)));
props.push(("line-height", number(line_height)));
props.push(("text-align", align.into()));
match t.shape {
// Photoshop places paragraph text at its box, moved down by an explicit leading,
// and sizes it by its text, not the box.
TextShape::Box { x, y, .. } => {
let at = t.transform.apply(Point::new(f64::from(x), f64::from(y)));
let leading = style.and_then(|s| s.leading_pt).map_or(0.0, |v| f64::from(v) * px_per_pt);
origin = Some(Point::new(at.x, at.y + leading));
}
// Point text has no box of its own: only its position.
_ => {
sized = false;
origin = point_text_origin(t, bounds, doc.resolution_dpi.max(1.0), family, size_pt, line_height);
}
}
}
LayerContent::Shape(sh) => {
// A live rounded rectangle's corners, before the fill as Photoshop writes them: one
// value when all four are equal, else top-left, top-right, bottom-right, bottom-left.
// Scaled unequally, its corners are elliptical though it keeps one radius each: none.
// A live ellipse fills its box, which half the box's size on each axis rounds to.
match &sh.live {
Some(live @ LiveShape::Rect { radii, .. }) if radii.iter().any(|&r| r > 0.0) && draws(live, &sh.path) => {
let px = |r: f64| format!("{}px", number(r.max(0.0)));
let all = if radii.iter().all(|&r| r == radii[0]) { px(radii[0]) } else { radii.map(px).join(" ") };
props.push(("border-radius", all));
}
Some(LiveShape::Ellipse { .. }) => props.push(("border-radius", "50%".into())),
_ => {}
}
match &sh.fill {
Some(Fill::Solid(c)) => props.push(("background-color", rgb(c))),
_ => props.push(("background-image", image(l))),
}
}
LayerContent::Fill(f) => {
// Only a fill layer with a vector mask (a shape) gets here: placed at its outline.
if bounds.is_empty() {
let outline = l.vector_mask.as_ref().and_then(|m| m.path.control_bounds());
bounds = outline.map_or(Rect::EMPTY, |(x0, y0, x1, y1)| {
Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&doc.bounds())
});
}
match f {
Fill::Solid(c) => props.push(("background-color", rgb(c))),
_ => props.push(("background-image", image(l))),
}
}
_ => props.push(("background-image", image(l))),
}
if bounds.is_empty() {
return None;
}
if l.opacity < 1.0 {
props.push(("opacity", number(f64::from(l.opacity.max(0.0)))));
}
props.push(("position", "absolute".into()));
let at = origin.unwrap_or(Point::new(f64::from(bounds.x0), f64::from(bounds.y0)));
props.push(("left", format!("{}px", position(at.x))));
props.push(("top", format!("{}px", position(at.y))));
if sized {
props.push(("width", format!("{}px", number(f64::from(bounds.width())))));
props.push(("height", format!("{}px", number(f64::from(bounds.height())))));
}
props.push(("z-index", z.to_string()));
let mut out = format!(".{} {{\n", class_name(&l.name));
for (k, v) in props {
out.push_str(&format!(" {k}: {v};\n"));
}
out.push_str("}\n");
Some(out)
}
fn copy_css(s: &mut Session, p: &Value) -> Result<Value> {
let p = p.as_object().ok_or_else(|| bad("expected an object"))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let ids = match p.get("layer") {
None | Some(Value::Null) => st.selected_layers(),
Some(v) => vec![LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?)],
};
if ids.is_empty() {
return Err(bad("no layer selected"));
}
let walk = st.doc.walk();
for id in &ids {
if !walk.iter().any(|(_, _, l)| l.id == *id) {
return Err(EngineError::NoLayer(*id));
}
}
let mut z = HashMap::new();
stack_places(&st.doc.layers, &mut 0, &mut z, 0);
// In Layers panel order, top first: a group, then its layers (measured).
let mut picked = Vec::new();
panel_order(&st.doc.layers, false, &ids, &mut picked, 0);
let rules: Vec<(u64, String)> = picked.into_iter().filter_map(|l| z.get(&l.id).and_then(|&z| rule(&st.doc, z, l)).map(|r| (l.id.0, r))).collect();
if rules.is_empty() {
return Err(EngineError::Other("Copy CSS needs a pixel, type, shape or group layer with content".into()));
}
// Photoshop writes a group's rules one after another, with no blank line between them.
let css: String = rules.iter().map(|(_, r)| r.as_str()).collect();
Ok(json!({"css": css, "layers": rules.iter().map(|(id, _)| id).collect::<Vec<_>>()}))
}
/// Every layer's `z-index`, counted from the bottom: a group's layers come first, after one place
/// for the group's end, then the group (measured: Background 1, group end 2, its layer 3, the
/// group 4, the layer above it 5).
fn stack_places(layers: &[Layer], n: &mut usize, out: &mut HashMap<LayerId, usize>, depth: usize) {
for l in layers {
if let Some(children) = l.children() {
*n += 1;
if depth < MAX_DEPTH {
stack_places(children, n, out, depth + 1);
}
}
*n += 1;
out.insert(l.id, *n);
}
}
/// The layers whose rules are copied, top first: the selected ones and everything inside a
/// selected group, each once.
fn panel_order<'a>(layers: &'a [Layer], inside_picked: bool, ids: &[LayerId], out: &mut Vec<&'a Layer>, depth: usize) {
for l in layers.iter().rev() {
let take = inside_picked || ids.contains(&l.id);
if take {
out.push(l);
}
if let Some(children) = l.children().filter(|_| depth < MAX_DEPTH) {
panel_order(children, take, ids, out, depth + 1);
}
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: ID,
label: "Copy CSS",
menu: &["Layer"],
shortcut: None,
params: r#"{"layer":id?} (no layer: the selected layers) → {"css": text, "layers": [id…]}; the app puts the text on the clipboard"#,
enabled,
run: copy_css,
journal: false,
}]
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,346 @@
use super::*;
use photocraft_doc::Layer;
use photocraft_geom::Rect;
/// A 400 × 300 document at 72 ppi with a 200 × 140 pixel layer at (100, 80) named `name`.
fn session(name: &str) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({"name": name})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 80, 300, 220), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
s
}
/// Photoshop 2025 copies this for a 200 × 140 pixel layer at (100, 80), second from the bottom.
#[test]
fn a_pixel_layer_copies_as_photoshop_writes_it() {
let mut s = session("Box");
let r = s.execute(ID, json!({})).unwrap();
assert_eq!(
r["css"],
json!(
".Box {\n background-image: url(\"Box.png\");\n position: absolute;\n left: 100px;\n top: 80px;\n width: 200px;\n height: 140px;\n z-index: 2;\n}\n"
)
);
// Photoshop: a name with spaces keeps them in the image name and turns them to `_` in the
// class; an opacity under 100 % follows the background.
let mut s = session("My Box 2");
s.edit("opacity", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().opacity = 128.0 / 255.0;
Ok(())
})
.unwrap();
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".My_Box_2 {\n background-image: url(\"My Box 2.png\");\n opacity: 0.502;\n position: absolute;\n"), "{css}");
}
#[test]
fn fill_and_type_layers_describe_their_colour_and_font() {
let doc = session("Box").active().unwrap().doc.clone();
// Photoshop: a solid colour gives `background-color`. A fill layer is a shape with a vector
// mask, placed at its outline; without one it has no rule (Copy CSS is greyed out, measured).
let mut fill = Layer::new("Card", LayerContent::Fill(Fill::Solid(photocraft_color::Color::rgb(1.0, 120.0 / 255.0, 30.0 / 255.0))));
assert!(rule(&doc, 4, &fill).is_none());
fill.vector_mask = Some(photocraft_doc::VectorMask::new(photocraft_vector::shapes::rect(250.0, 200.0, 120.0, 60.0)));
assert_eq!(
rule(&doc, 4, &fill).unwrap(),
".Card {\n background-color: rgb(255, 120, 30);\n position: absolute;\n left: 250px;\n top: 200px;\n width: 120px;\n height: 60px;\n z-index: 4;\n}\n"
);
// A type layer: size, family, colour, auto leading and alignment, then only its position
// (Photoshop writes no size for point text). Its position is where its pixels are.
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
let text = photocraft_doc::TextLayer {
font_family: "Inter".into(),
size_pt: 24.0,
color: photocraft_color::Color::rgb(0.0, 0.0, 0.0),
cache: Some(cache),
..Default::default()
};
let title = Layer::new("Title", LayerContent::Text(text));
let css = rule(&doc, 3, &title).unwrap_or_default();
assert_eq!(
css,
".Title {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 49px;\n top: 28px;\n z-index: 3;\n}\n"
);
// A group's own rule is its box, the canvas.
let group = Layer::group("Group 1", Vec::new());
assert_eq!(
rule(&doc, 5, &group).unwrap(),
".Group_1 {\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 5;\n}\n"
);
}
/// Measured: Layer › Copy CSS on a group holding a 50 × 30 layer "2nd-Box" at (10, 20) writes the
/// group's canvas box, then the layer, with no blank line; the group's end takes a place in the
/// stack, so the layer is 3 and the group 4 above the Background.
#[test]
fn a_group_writes_its_box_then_its_layers() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({"name": "2nd-Box"})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 20, 60, 50), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
s.execute("layer.groupLayers", json!({})).unwrap();
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(300, 200, 320, 220), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
let group = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.children().is_some()).unwrap().2.id.0;
let css = s.execute(ID, json!({"layer": group})).unwrap()["css"].as_str().unwrap().to_string();
let rest = css.split_once(' ').unwrap().1;
assert_eq!(
rest,
"{\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 4;\n}\n\
._2nd_Box {\n background-image: url(\"2nd-Box.png\");\n position: absolute;\n left: 10px;\n top: 20px;\n width: 50px;\n height: 30px;\n z-index: 3;\n}\n"
);
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".Top {\n") && css.contains(" z-index: 5;\n"), "{css}");
}
/// Measured: Copy CSS is greyed out for a Solid Color fill layer without a shape.
#[test]
fn copy_css_is_off_for_a_fill_layer_without_a_shape() {
let mut s = session("Box");
assert!(s.is_enabled(ID));
s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
assert!(!s.is_enabled(ID), "a plain fill layer has no CSS");
assert!(s.execute(ID, json!({})).is_err());
}
/// Point type as Photoshop placed it (measured: text bounds and pixel bounds from its scripting
/// interface, then the copied CSS).
#[test]
fn point_type_is_placed_as_photoshop_places_it() {
let arial_cap = 1467.0 / 2048.0 * 24.0;
let times_cap = 1356.0 / 2048.0 * 24.0;
let css = |pix: Rect, ink: [f64; 4], cap: f64, size: f64, line_height: f64| {
let at = place_point_text(pix, ink, 0.0, cap, size, line_height * size);
(position(at.x), position(at.y))
};
let s = |a: &str, b: &str| (a.to_string(), b.to_string());
// "Hello", Arial 24 at (50, 150).
assert_eq!(css(Rect::new(52, 132, 104, 151), [1.875, -17.25, 53.71875, 0.1875], arial_cap, 24.0, 1.2), s("50.125", "127.1"));
// The same at 48 px.
assert_eq!(css(Rect::new(53, 65, 158, 101), [3.75, -34.5, 107.4375, 0.375], arial_cap * 2.0, 48.0, 1.2), s("49.25", "54.2"));
// With a 40 pt leading: line-height 1.667.
assert_eq!(css(Rect::new(202, 82, 254, 101), [1.875, -17.25, 53.71875, 0.1875], arial_cap, 24.0, 1.667), s("200.125", "71.496"));
// "x": no descender.
assert_eq!(css(Rect::new(300, 237, 312, 250), [0.1875, -12.5625, 11.8799, 0.0], arial_cap, 24.0, 1.2), s("299.812", "229.1"));
// Descenders: "xyz", "xg", "Hg" in Arial, "Hg" and "xg" in Times New Roman.
assert_eq!(css(Rect::new(50, 187, 86, 205), [0.1875, -12.5625, 35.71875, 4.875], arial_cap, 24.0, 1.2), s("49.812", "176.566"));
assert_eq!(css(Rect::new(330, 237, 354, 255), [0.1875, -12.75, 23.6953, 4.875], arial_cap, 24.0, 1.2), s("329.812", "226.754"));
assert_eq!(css(Rect::new(302, 262, 329, 285), [1.875, -17.25, 29.0273, 4.875], arial_cap, 24.0, 1.2), s("300.125", "256.254"));
assert_eq!(css(Rect::new(50, 84, 79, 106), [0.375, -15.9375, 28.5, 5.0625], times_cap, 24.0, 1.2), s("49.625", "77.592"));
assert_eq!(css(Rect::new(150, 89, 174, 106), [0.1875, -11.0625, 23.5, 5.0625], times_cap, 24.0, 1.2), s("149.812", "77.717"));
}
#[test]
fn positions_are_cut_after_three_decimals() {
assert_eq!(position(49.8125), "49.812");
assert_eq!(position(141.5 - 14.4), "127.1");
assert_eq!(position(100.0), "100");
assert_eq!(position(f64::INFINITY), "0");
}
/// Photoshop 2025, paragraph text in a 200 × 120 box at (60, 40) that wraps to two lines whose
/// pixels span 156 × 51: `left: 59.937px; top: 36.948px; width: 156px; height: 51px;`. Unlike point
/// text it has a size, that of its text (not the box), and it's placed at its box, not where its
/// first pixel is; an explicit leading moves it down by that much (36 px: `top: 72.948px`).
#[test]
fn paragraph_text_is_placed_at_its_box_and_sized_by_its_text() {
let doc = session("Box").active().unwrap().doc.clone();
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(62, 44, 218, 95), &[0.0, 0.0, 0.0, 1.0]);
let mut text = photocraft_doc::TextLayer {
text: "Hello world this wraps around".into(),
font_family: "Inter".into(),
size_pt: 24.0,
cache: Some(cache),
shape: photocraft_doc::text::TextShape::Box { x: 0.0, y: 0.0, width: 200.0, height: 120.0 },
transform: photocraft_geom::Affine::translate(60.0, 40.0),
..Default::default()
};
let css = rule(&doc, 3, &Layer::new("Para", LayerContent::Text(text.clone()))).unwrap_or_default();
assert_eq!(
css,
".Para {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 60px;\n top: 40px;\n width: 156px;\n height: 51px;\n z-index: 3;\n}\n"
);
let style = photocraft_doc::text::CharStyle { font_family: "Inter".into(), size_pt: 24.0, leading_pt: Some(36.0), ..Default::default() };
text.runs = vec![photocraft_doc::text::TextRun { len: text.text.len(), style }];
let css = rule(&doc, 3, &Layer::new("Para", LayerContent::Text(text))).unwrap_or_default();
assert!(
css.contains(" line-height: 1.5;\n text-align: left;\n position: absolute;\n left: 60px;\n top: 76px;\n width: 156px;\n height: 51px;\n"),
"{css}"
);
}
#[test]
fn numbers_and_names_are_written_as_photoshop_does() {
assert_eq!(number(48.9374), "48.937");
assert_eq!(number(27.6), "27.6");
assert_eq!(number(100.0), "100");
assert_eq!(number(-0.0001), "0");
assert_eq!(number(f64::NAN), "0");
assert_eq!(class_name("My Box 2"), "My_Box_2");
assert_eq!(class_name(""), "layer");
}
/// Photoshop 2025: a class can't start with a digit, so a layer named "2nd Box" gets a `_` in
/// front; a hyphen becomes `_` like the other punctuation ("-2x" is `._2x`, "my-box" `.my_box`).
#[test]
fn class_names_never_start_with_a_digit() {
for (name, class) in [("2nd Box", "._2nd_Box {\n"), ("-2x", "._2x {\n"), ("my-box", ".my_box {\n")] {
let css = session(name).execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(class), "{name}: {css}");
}
}
/// Names go into quoted CSS strings: a `"`, a backslash or a line break in one is escaped, so the
/// string doesn't end early and keeps the name (Photoshop writes them unescaped, which breaks
/// the rule). Ordinary names are written as before.
#[test]
fn names_in_quoted_values_are_escaped() {
let css = session("Say \"hi\"").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" background-image: url(\"Say \\\"hi\\\".png\");\n"), "{css}");
let css = session("a\\b\nc").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" background-image: url(\"a\\\\b\\a c.png\");\n"), "{css}");
let doc = session("Box").active().unwrap().doc.clone();
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
let text = photocraft_doc::TextLayer { font_family: "My \"Font\"".into(), size_pt: 24.0, cache: Some(cache), ..Default::default() };
let css = rule(&doc, 3, &Layer::new("Title", LayerContent::Text(text))).unwrap_or_default();
assert!(css.contains(" font-family: \"My \\\"Font\\\"\";\n"), "{css}");
}
#[test]
fn bad_params_and_layers_without_css_are_errors() {
let mut s = session("Box");
assert!(s.execute(ID, json!({"layer": "x"})).is_err());
assert!(s.execute(ID, json!({"layer": 999_999})).is_err());
assert!(s.execute(ID, json!([])).is_err());
s.execute("layer.new.group", json!({})).unwrap();
assert!(s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().contains(" width: 400px;\n"), "an empty group writes its box");
let mut empty = Session::new();
assert!(empty.execute(ID, json!({})).is_err(), "no document");
}
/// A live rounded rectangle gives its corners as Photoshop writes them, before the fill: one
/// value when all four are equal, else top-left, top-right, bottom-right, bottom-left; a sharp
/// one writes none.
#[test]
fn a_rounded_rectangle_writes_its_border_radius() {
let mut s = session("Box");
let id = s.execute("shape.create", json!({"kind": "roundedRect", "rect": [40, 30, 120, 80], "radius": 12, "fill": "#ff0000"})).unwrap()["layer"]
.as_u64()
.unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" {\n border-radius: 12px;\n background-color: rgb(255, 0, 0);\n position: absolute;\n"), "{css}");
s.execute("shape.edit", json!({"layer": id, "radii": [20, 0, 10.5, 5]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" border-radius: 20px 0px 10.5px 5px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
s.execute("shape.edit", json!({"layer": id, "radii": [0, 0, 0, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!css.contains("border-radius") && css.contains(" background-color: rgb(255, 0, 0);\n"), "{css}");
// Scaled 2× on both axes, its corners are twice as round.
s.execute("shape.edit", json!({"layer": id, "radii": [12, 12, 12, 12]})).unwrap();
s.execute("shape.edit", json!({"layer": id, "transform": [2, 0, 0, 2, 0, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" border-radius: 24px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
}
/// Scaled 200 % across and 100 % down, a rounded rectangle's corners are 24 × 12 px ellipses, but
/// it keeps one radius per corner (12): no `border-radius` rather than a circular one. A flipped
/// one, whose outline runs the other way, keeps its circular corners and writes them.
#[test]
fn an_unequally_scaled_rounded_rectangle_writes_no_border_radius() {
let mut s = session("Box");
let create = json!({"kind": "roundedRect", "rect": [40, 30, 120, 80], "radius": 12, "fill": "#ff0000"});
let id = s.execute("shape.create", create.clone()).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"layer": id, "transform": [2, 0, 0, 1, 0, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!css.contains("border-radius") && css.contains(" {\n background-color: rgb(255, 0, 0);\n"), "{css}");
let flipped = s.execute("shape.create", create).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"layer": flipped, "transform": [-1, 0, 0, 1, 400, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": flipped})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" {\n border-radius: 12px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
}
/// A live ellipse writes `border-radius: 50%;` where a rounded rectangle writes its radii, so the
/// rule draws an ellipse, not a rectangle; other live shapes (a star here) write no geometry.
#[test]
fn an_ellipse_writes_a_half_border_radius() {
let mut s = session("Box");
let id = s.execute("shape.create", json!({"kind": "ellipse", "rect": [40, 30, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" {\n border-radius: 50%;\n background-color: rgb(255, 0, 0);\n position: absolute;\n"), "{css}");
let star = s.execute("shape.create", json!({"kind": "star", "rect": [40, 30, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
let css = s.execute(ID, json!({"layer": star})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!css.contains("border-radius") && css.contains(" {\n background-color: rgb(255, 0, 0);\n"), "{css}");
}
/// `css` without its double-quoted strings (escapes inside them skipped).
fn outside_strings(css: &str) -> String {
let (mut out, mut quoted, mut escaped) = (String::new(), false, false);
for c in css.chars() {
match (quoted, escaped, c) {
(true, true, _) => escaped = false,
(true, false, '\\') => escaped = true,
(_, false, '"') => quoted = !quoted,
(false, _, _) => out.push(c),
_ => {}
}
}
out
}
/// A name with a comment closer can't end a comment or break the rule: outside the quoted image
/// name there is no `*/`, and the class is sanitised.
#[test]
fn a_comment_closer_in_a_name_stays_inside_the_string() {
let css = session("a */ b").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!outside_strings(&css).contains("*/"), "{css}");
assert!(css.starts_with(".a____b {\n background-image: url(\"a */ b.png\");\n"), "{css}");
}
/// Layer effects aren't written: a layer with a drop shadow gives the same rule as without it,
/// placed and sized by its pixels, not the shadow.
#[test]
fn a_layer_with_a_drop_shadow_writes_its_rule_without_the_effect() {
let mut s = session("Box");
let plain = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
s.edit("fx", |doc, active| {
let l = doc.layer_mut(active.unwrap()).unwrap();
l.effects.enabled = true;
l.effects.items.push(photocraft_doc::effects::Effect::default_drop_shadow());
Ok(())
})
.unwrap();
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert_eq!(css, plain);
assert!(!css.contains("shadow"), "{css}");
}
/// Real point type goes through its layout: "Hello" at a baseline of 150 is placed by its line
/// box, which starts above its first pixel (Photoshop: 127.1 for pixels from 132), not at it.
#[test]
fn point_type_is_placed_by_its_line_box() {
let mut s = session("Box");
let id = s.execute("type.create", json!({"x": 50, "y": 150, "text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap();
let doc = &s.active().unwrap().doc;
let pix = photocraft_doc::comps::position_bounds(doc.walk().into_iter().find(|(_, _, l)| l.id.0 == id).unwrap().2);
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
let value = |key: &str| css.split(&format!(" {key}: ")).nth(1).and_then(|v| v.split("px;").next()).and_then(|v| v.parse::<f64>().ok()).unwrap();
let (left, top) = (value("left"), value("top"));
assert!((left - 50.0).abs() < 1.0, "left at the origin, within the pixel rounding: {css}");
assert!(top < f64::from(pix.y0) - 2.0 && top > 150.0 - 28.8, "top {top} above the pixels at {}: {css}", pix.y0);
}
+12 -4
View File
@@ -276,7 +276,7 @@ fn raw_enabled(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
match d.doc.mode {
ColorMode::Rgb | ColorMode::Grayscale => Ok(()),
m => Err(format!("Camera Raw Filter needs an RGB or Grayscale document (this one is {m:?})")),
m => Err(format!("RAW Develop Filter needs an RGB or Grayscale document (this one is {m:?})")),
}
}
@@ -412,12 +412,13 @@ fn camera_raw_cmd(s: &mut Session, p: &Value) -> Result<Value> {
if raw_pixels(area).is_none() {
return Err(bad(
RAW,
format!("the image is too large for Camera Raw ({}×{} px; max {} megapixels)", area.width(), area.height(), MAX_RAW_PIXELS / 1_000_000),
format!("the image is too large for RAW Develop ({}×{} px; max {} megapixels)", area.width(), area.height(), MAX_RAW_PIXELS / 1_000_000),
));
}
}
let t0 = Stopwatch::start();
let id = run_filter(s, RAW, "Camera Raw Filter", p, p.clone(), false, &|surf, canvas| camera_raw_surface(surf, canvas.union(&surf.content_bounds()), &cr))?;
let id =
run_filter(s, RAW, "RAW Develop Filter", p, p.clone(), false, &|surf, canvas| camera_raw_surface(surf, canvas.union(&surf.content_bounds()), &cr))?;
Ok(json!({"layer": id.0, "identity": cr.is_identity(), "ms": t0.ms()}))
}
@@ -469,7 +470,7 @@ pub fn specs() -> Vec<CommandSpec> {
},
CommandSpec {
id: RAW,
label: "Camera Raw Filter…",
label: "RAW Develop Filter…",
menu: &["Filter"],
shortcut: Some("Cmd+Shift+A"),
params: r##"{"temperature":-100..100=0,"tint":-100..100=0,"exposure":-5..5=0,"contrast":-100..100=0,"highlights":-100..100=0,"shadows":-100..100=0,"whites":-100..100=0,"blacks":-100..100=0,"texture":-100..100=0,"clarity":-100..100=0,"dehaze":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=0,"curveHighlights":-100..100=0,"curveLights":-100..100=0,"curveDarks":-100..100=0,"curveShadows":-100..100=0,"curveSplits":[25,50,75],"pointCurve":[[in,out]],"pointCurveRed":[[in,out]],"pointCurveGreen":[[in,out]],"pointCurveBlue":[[in,out]],"hslHue":[8],"hslSat":[8],"hslLum":[8],"gradeShadows":{"hue":deg,"sat":0..100,"lum":-100..100},"gradeMidtones":{},"gradeHighlights":{},"gradeGlobal":{},"gradeBlending":0..100=50,"gradeBalance":-100..100=0,"shadowTint":-100..100=0,"calibrationHue":[red,green,blue] -100..100,"calibrationSat":[red,green,blue] -100..100 (the Calibration panel: Shadows tint and the primaries' hue and saturation),"sharpenAmount":0..150=0,"sharpenRadius":0.5..3=1,"sharpenDetail":0..100=25,"sharpenMasking":0..100=0,"noiseLuminance":0..100=0,"noiseLuminanceDetail":0..100=50,"noiseColor":0..100=0,"noiseColorDetail":0..100=50,"grainAmount":0..100=0,"grainSize":0..100=25,"grainRoughness":0..100=50,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vignetteRoundness":-100..100=0,"vignetteFeather":0..100=50,"vignetteHighlights":0..100=0,"vignetteStyle":"highlightPriority|colorPriority|paintOverlay","seed":u32=0}"##,
@@ -492,6 +493,13 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests {
#[test]
fn raw_develop_filter_keeps_its_automation_id() {
let command = super::specs().into_iter().find(|command| command.id == "filter.cameraRaw").expect("existing RAW command");
assert_eq!(command.label, "RAW Develop Filter…");
}
use super::*;
fn session(depth: u32) -> Session {
@@ -537,6 +537,15 @@ impl LiveDab {
Ok(self)
}
/// Mix the dabs back without the layer's transparency lock, for a tool that erases a locked
/// layer anyway (the Background Eraser). Call it before pushing any points: build the dab with
/// the stroke's points taken out, then [`Self::push`] them (as `live_background_eraser` does),
/// because points pushed before it were already mixed back with the lock.
pub(crate) fn unlocked(mut self) -> Self {
self.lock = false;
self
}
/// Everything the stroke has touched so far.
pub fn bounds(&self) -> Rect {
self.bounds
+1 -1
View File
@@ -123,7 +123,7 @@ pub(crate) fn refusal(s: &Session, id: &str, p: &Value) -> Option<String> {
return Some("Move and transforms on several colour channels are not implemented yet".into());
}
if id == "filter.cameraRaw" {
return Some("Camera Raw requires the composite or one colour channel".into());
return Some("RAW Develop requires the composite or one colour channel".into());
}
None
}
+1
View File
@@ -110,6 +110,7 @@ pub use cmd::history_select_cmds;
pub use cmd::history_source_cmds;
pub use cmd::image_cmds;
pub use cmd::layer_copy_cmds;
pub use cmd::layer_css_cmds;
pub use cmd::layer_label_cmds;
pub use cmd::layer_list_cmds;
pub use cmd::layer_mask_props_cmds;
+1 -1
View File
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
section!("edit.preferences.plugIns", "Plugins…"),
section!("edit.preferences.type", "Type…"),
section!("edit.preferences.enhancedControls", "Enhanced Controls…"),
section!("edit.preferences.rawDefaults", "Camera Raw…"),
section!("edit.preferences.rawDefaults", "RAW Defaults…"),
section!("edit.preferences.integrations", "Integrations…"),
spec!(
"edit.keyboardShortcuts",
+1 -1
View File
@@ -24,7 +24,7 @@ pub const SECTIONS: [(&str, &str); 18] = [
("plugIns", "Plugins"),
("type", "Type"),
("enhancedControls", "Enhanced Controls"),
("rawDefaults", "Camera Raw Defaults"),
("rawDefaults", "RAW Defaults"),
("integrations", "Integrations"),
];
+21
View File
@@ -966,6 +966,27 @@ fn command_list_filter_finds_the_marquees_by_keyword() {
assert!(found("no command is called this").is_empty());
}
/// The rename to "RAW Develop" is display only: the filter and RAW Defaults are still found by
/// Photoshop's "Camera Raw" name, which their keywords carry (#12403).
#[test]
fn command_list_filter_finds_the_raw_commands_by_their_photoshop_name() {
let mut s = Session::new();
let list = s.execute("command.list", json!({})).unwrap();
let rows = list.as_array().unwrap();
let found = |needle: &str| -> Vec<String> {
rows.iter().filter(|c| crate::commands::list_entry_matches(c, needle)).map(|c| c["id"].as_str().unwrap().to_string()).collect()
};
for needle in ["camera raw", "Camera Raw", "CAMERA RAW"] {
let ids = found(needle);
assert!(ids.contains(&"filter.cameraRaw".to_string()), "{needle}: {ids:?}");
assert!(ids.contains(&"edit.preferences.rawDefaults".to_string()), "{needle}: {ids:?}");
}
// What the menus show is the new name, and the keywords are not a label.
let label = |id: &str| rows.iter().find(|c| c["id"] == id).unwrap()["label"].as_str().unwrap().to_string();
assert_eq!(label("filter.cameraRaw"), "RAW Develop Filter…");
assert_eq!(label("edit.preferences.rawDefaults"), "RAW Defaults…");
}
/// Every keyword entry names a real command, so a renamed id can't leave one behind.
#[test]
fn search_keywords_name_real_commands() {
+5 -5
View File
@@ -75,7 +75,7 @@ impl CameraRawDevelop {
pub fn new(device: &wgpu::Device) -> Result<Self, Unsupported> {
match crate::first_error(device, || Self::build(device)) {
(dev, None) => Ok(dev),
(_, Some(e)) => Err(Unsupported(format!("couldn't build the Camera Raw pipeline: {e}"))),
(_, Some(e)) => Err(Unsupported(format!("couldn't build the RAW Develop pipeline: {e}"))),
}
}
@@ -246,7 +246,7 @@ impl CameraRawDevelop {
Some(e) => {
// A half-done upload must not be taken for the cached source next time.
self.source = None;
Err(Unsupported(format!("GPU Camera Raw develop failed: {e}")))
Err(Unsupported(format!("GPU RAW Develop failed: {e}")))
}
None => result,
}
@@ -270,7 +270,7 @@ impl CameraRawDevelop {
let bytes = u64::from(row) * u64::from(h);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_camera_raw") });
self.encode(device, queue, &mut encoder, source, key, size, stages)?;
let Some(target) = self.target.as_ref().map(|t| &t.texture) else { return Err(Unsupported("no Camera Raw target".into())) };
let Some(target) = self.target.as_ref().map(|t| &t.texture) else { return Err(Unsupported("no RAW Develop target".into())) };
let buffer = match self.readback.take() {
Some(b) if b.size() == bytes => b,
_ => device.create_buffer(&wgpu::BufferDescriptor {
@@ -316,10 +316,10 @@ impl CameraRawDevelop {
fn check_size(device: &wgpu::Device, source: &[[f32; 4]], [w, h]: [u32; 2]) -> Result<(), Unsupported> {
let max = device.limits().max_texture_dimension_2d;
if w == 0 || h == 0 || w > max || h > max {
return Err(Unsupported(format!("a {w}×{h} Camera Raw preview doesn't fit the GPU's {max} px textures")));
return Err(Unsupported(format!("a {w}×{h} RAW Develop preview doesn't fit the GPU's {max} px textures")));
}
if source.len() as u64 != u64::from(w) * u64::from(h) {
return Err(Unsupported(format!("{} Camera Raw preview pixels for {w}×{h}", source.len())));
return Err(Unsupported(format!("{} RAW Develop preview pixels for {w}×{h}", source.len())));
}
Ok(())
}
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result<
.filter(|(_, v)| *v != 0.0)
.map(|(k, v)| format!(", {k} {v:+.0}"))
.collect::<String>();
let summary = format!("developed in Camera Raw (exposure {:+.2} EV{tone}, {wb}, {} demosaic{cropped})", tuning.exposure, tuning.demosaic.id());
let summary = format!("developed in RAW Develop (exposure {:+.2} EV{tone}, {wb}, {} demosaic{cropped})", tuning.exposure, tuning.demosaic.id());
Ok((developed_document(name, bytes, format, dev, &summary)?, wb_applied))
}
+42 -17
View File
@@ -4,7 +4,7 @@
//! Colours are compared in the surface's own colour channels (RGB, CMYK, Gray, Lab… at any depth),
//! so nothing is converted through RGB; only alpha changes.
use photocraft_color::SampleType;
use photocraft_color::{SampleType, read_sample, write_sample};
use photocraft_geom::Rect;
use photocraft_raster::{Surface, from_rgba};
use serde::{Deserialize, Serialize};
@@ -24,10 +24,10 @@ pub struct BgEraseSettings {
/// 0..1: how far from the sampled colour a colour is still partly erased. The distance is the
/// largest increase plus the largest decrease over the colour channels (`dist`); an exact
/// match is erased fully, then less the further a colour is, and colours at or beyond the
/// Tolerance are kept (`graded_weight`). Protect Foreground Color still compares the
/// foreground by the largest per-channel difference (`max_channel_dist`).
/// Tolerance are kept (`graded_weight`).
pub tolerance: f32,
/// Keep pixels that match the foreground colour.
/// Keep the foreground colour: the erase narrows to the colours between the sampled colour and
/// the foreground colour (see [`protected_tolerance`]).
pub protect_foreground: bool,
/// Straight RGBA foreground colour (for Protect Foreground Color).
pub foreground: [f32; 4],
@@ -60,10 +60,25 @@ fn dist(a: &[f32], b: &[f32]) -> f32 {
up + down
}
/// The largest per-channel difference of `a` from `b`: the distance Protect Foreground Color keeps
/// using (#11901 measured only the sample match; #11903 keeps today's measure for the foreground).
fn max_channel_dist(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs()))
/// The Tolerance Protect Foreground Color leaves (#11903): it narrows to `limit`, the distance from
/// the sampled colour to the foreground colour, so the sampled colour itself is still erased, the
/// erase fades out towards the foreground, and colours at least as far from the sample as the
/// foreground (the foreground itself included) are kept. `None` when the foreground is the sampled
/// colour: nothing is erased.
fn protected_tolerance(tol: f32, limit: f32) -> Option<f32> {
if limit.is_nan() || limit <= 0.0 {
return None;
}
Some(tol.min(limit))
}
/// `v` as the document stores it: rounded to the 8- or 16-bit levels, unchanged in 32-bit float.
/// The sampled colour is read from stored pixels, so the foreground is compared at the same
/// precision; otherwise a foreground between two levels misses its own stored colour (#11903).
fn at_sample_precision(sample: SampleType, v: f32) -> f32 {
let mut bytes = [0u8; 4];
write_sample(&mut bytes, sample, 0, v);
read_sample(&bytes, sample, 0)
}
/// The match weight of one dab for a colour `d` away from the sampled colour (#11901): an exact
@@ -108,13 +123,10 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option<i
let tol = if bs.tolerance.is_finite() { bs.tolerance.clamp(0.0, 1.0) } else { 0.0 };
let native = |c: [f32; 4]| -> Vec<f32> { from_rgba(&fmt, [c[0], c[1], c[2], 1.0])[..nc].to_vec() };
let swatch = native(bs.background);
let fg = native(bs.foreground);
let fg: Vec<f32> = native(bs.foreground).into_iter().map(|v| at_sample_precision(fmt.sample, v)).collect();
let (sampling, limits, protect_foreground) = (bs.sampling, bs.limits, bs.protect_foreground);
let float = fmt.sample == SampleType::F32;
let mut once: Option<Option<Vec<f32>>> = None;
// Find Edges grades soft edges like Contiguous does instead of cutting them hard (#11904):
// the reference application keeps at least as much of a blurred transition with it.
let match_w = move |d: f32| -> f32 { graded_weight(d, tol) };
let pre = pre.clone();
// The pixels before the stroke under the working copy, read once per working area. Sampling
// and matching read these, so a dab landing on pixels earlier dabs already erased still
@@ -145,6 +157,18 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option<i
Sampling::BackgroundSwatch => Some(swatch.clone()),
};
let Some(sampled) = sampled else { return };
// Protect Foreground Color narrows the Tolerance to the foreground colour (#11903), by the
// same distance as the sample match: the reference application measures a foreground that
// is off in two channels that way too.
let tol = if protect_foreground {
let Some(t) = protected_tolerance(tol, dist(&sampled, &fg)) else { return };
t
} else {
tol
};
// Find Edges grades soft edges like Contiguous does instead of cutting them hard (#11904):
// the reference application keeps at least as much of a blurred transition with it.
let match_w = |d: f32| -> f32 { graded_weight(d, tol) };
let (w, h) = (r.width() as usize, r.height() as usize);
// Which pixels the contiguous fill may pass, from the pre-stroke colours as before: it
// passes through pixels this stroke already erased.
@@ -153,7 +177,6 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option<i
// partly is matched by its current, decontaminated colour, which is pushed away from the
// sampled colour, so later dabs erase it again only while it is still within the Tolerance.
let mut weight = vec![0.0f32; w * h];
let protected = |c: &[f32]| protect_foreground && max_channel_dist(c, &fg) <= tol;
for y in r.y0..r.y1 {
for x in r.x0..r.x1 {
if fp.at(x, y) <= 0.0 {
@@ -164,11 +187,9 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option<i
continue;
}
let i = (y - r.y0) as usize * w + (x - r.x0) as usize;
if !protected(&o[..nc]) {
reach[i] = match_w(dist(&o[..nc], &sampled));
}
reach[i] = match_w(dist(&o[..nc], &sampled));
let c = work.px(x, y);
if c[a] > 0.0 && !protected(&c[..nc]) {
if c[a] > 0.0 {
weight[i] = match_w(dist(&c[..nc], &sampled));
}
}
@@ -249,6 +270,10 @@ fn keep_connected(weight: &mut [f32], w: usize, h: usize, sx: usize, sy: usize)
}
}
#[cfg(test)]
#[path = "bg_erase_protect_foreground_tests.rs"]
mod protect_foreground_tests;
#[cfg(test)]
#[path = "bg_erase_graded_alpha_tests.rs"]
mod graded_alpha_tests;
@@ -175,15 +175,3 @@ fn the_distance_is_measured_in_the_documents_own_channels() {
}
}
}
#[test]
fn protect_foreground_keeps_todays_distance_to_the_foreground() {
// #11903 measured the foreground only one channel away and keeps today's measure otherwise:
// the largest per-channel difference. This foreground is 100 levels off in red and in green
// (opposite signs): within Tolerance 50 by that measure, though the sample-match distance of
// #11901 adds the two to 200. The pixel is the sampled colour, so only the protection keeps it.
let bs = BgEraseSettings { protect_foreground: true, foreground: rgb([100, 140, 40]), ..swatch(50.0, rgb(SAMPLE)) };
assert_eq!(one_click(PixelFormat::RGBA8, rgb(SAMPLE), &bs), 255);
// Protection off: the same click erases the sample fully.
assert_eq!(one_click(PixelFormat::RGBA8, rgb(SAMPLE), &BgEraseSettings { protect_foreground: false, ..bs }), 0);
}
@@ -0,0 +1,236 @@
//! Protect Foreground Color (#11903): the protection fades with the distance from the foreground
//! colour, so the sampled colour is still erased while colours at and beyond the foreground are kept.
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::{Surface, from_rgba};
use crate::bg_erase::{BgEraseSettings, apply_background_eraser};
use crate::replace::{Limits, Sampling};
use crate::{BrushSettings, Stroke, StrokePoint};
/// Block `i` of the reference test layer: (200, 40 + 20 i, 40), so block i differs from block 0
/// by 20 i in green only.
fn block(i: usize) -> [f32; 4] {
[200.0 / 255.0, (40.0 + 20.0 * i as f32) / 255.0, 40.0 / 255.0, 1.0]
}
/// Eight 100 px blocks side by side, 900 x 300 (the reference's layout, shifted up).
fn blocks(fmt: PixelFormat) -> Surface {
let mut s = Surface::new(fmt);
for i in 0..8 {
let x = 100 * i as i32;
s.fill_rect(Rect::new(x, 0, x + 100, 300), &from_rgba(&fmt, block(i)));
}
s
}
fn stroke(points: &[(f64, f64)]) -> Stroke {
Stroke {
brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() },
points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect(),
}
}
fn settings(protect: Option<usize>) -> BgEraseSettings {
BgEraseSettings {
sampling: Sampling::Once,
limits: Limits::Discontiguous,
tolerance: 0.5,
protect_foreground: protect.is_some(),
foreground: block(protect.unwrap_or(0)),
..Default::default()
}
}
/// The reference's drag from block 0's centre through all eight, with `bs`; alpha (0-255) at each
/// centre.
fn drag_with(fmt: PixelFormat, bs: &BgEraseSettings) -> [i32; 8] {
let mut s = blocks(fmt);
apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), bs, None);
std::array::from_fn(|i| (s.rgba(100 * i as i32 + 50, 150)[3] * 255.0).round() as i32)
}
/// The reference's drag with the foreground at block `protect` (protection off for `None`).
fn drag(fmt: PixelFormat, protect: Option<usize>) -> [i32; 8] {
drag_with(fmt, &settings(protect))
}
/// Allowed deviation from the measured alpha ("within 8 levels").
const LEVELS: i32 = 8;
fn assert_near(got: [i32; 8], want: [i32; 8], what: &str) {
for i in 0..8 {
assert!((got[i] - want[i]).abs() <= LEVELS, "{what}: block {i}, got {got:?}, reference {want:?}");
}
}
/// The measured rows: Sampling Once, Discontiguous, Tolerance 50, 40 px hard tip.
const REFERENCE: [(usize, [i32; 8]); 3] =
[(1, [0, 255, 255, 255, 255, 255, 255, 255]), (3, [0, 76, 166, 255, 255, 255, 255, 255]), (5, [0, 40, 94, 148, 201, 255, 255, 255])];
/// The same drag without protection in the reference (the graded erase of #11901).
const UNPROTECTED: [i32; 8] = [0, 30, 75, 114, 156, 198, 238, 255];
#[test]
fn the_sampled_colour_is_erased_and_colours_from_the_foreground_on_are_kept() {
for (fg, want) in REFERENCE {
let got = drag(PixelFormat::RGBA8, Some(fg));
assert_near(got, want, &format!("fg block {fg}"));
for i in 0..8 {
// Fully kept and fully erased blocks match exactly.
if want[i] == 255 || want[i] == 0 {
assert_eq!(got[i], want[i], "fg block {fg}: block {i}, got {got:?}");
}
}
}
}
#[test]
fn a_foreground_off_in_two_channels_narrows_by_the_sample_distance() {
// Measured with the same drag: the Tolerance narrows to the foreground's distance from the
// sample (200,40,40) as the sample match measures it, the largest increase plus the largest
// decrease over the channels, not the largest per-channel difference.
let rows: [([i32; 3], [i32; 8]); 4] = [
// Red -100, green +100: 200 levels away, beyond Tolerance 50, so nothing is protected
// (the largest per-channel difference, 100, would keep blocks 5 to 7).
([100, 140, 40], [0, 32, 75, 112, 156, 196, 238, 255]),
// Red -50, green +50: 100 levels, like the foreground at block 5.
([150, 90, 40], [0, 40, 94, 153, 201, 255, 255, 255]),
// Two increases, the larger 50: 50 levels.
([230, 90, 40], [0, 101, 203, 255, 255, 255, 255, 255]),
([200, 90, 70], [0, 98, 202, 255, 255, 255, 255, 255]),
];
for (fg, want) in rows {
let foreground = [fg[0] as f32 / 255.0, fg[1] as f32 / 255.0, fg[2] as f32 / 255.0, 1.0];
let got = drag_with(PixelFormat::RGBA8, &BgEraseSettings { foreground, ..settings(Some(0)) });
assert_near(got, want, &format!("fg {fg:?}"));
assert_eq!(got[0], 0, "fg {fg:?}: the sample erased, got {got:?}");
}
}
#[test]
fn protection_narrows_the_tolerance_to_the_foreground_in_one_dab() {
// One click (Background Swatch = block 0, so the click's own pixel does not matter) on each
// block: with the foreground at block `fg`, the protected click erases what an unprotected
// click at Tolerance = the sample-to-foreground distance erases, and keeps block fg and beyond.
let fmt = PixelFormat::RGBA8;
let click = |protect: Option<usize>, tolerance: f32| -> Vec<f32> {
(0..8)
.map(|i| {
let mut s = blocks(fmt);
let bs = BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: block(0), tolerance, ..settings(protect) };
let x = 100.0 * i as f64 + 50.0;
apply_background_eraser(&mut s, &stroke(&[(x, 150.0)]), &bs, None);
s.rgba(x as i32, 150)[3]
})
.collect()
};
for fg in [1, 3, 5] {
let protected = click(Some(fg), 0.5);
let narrowed = click(None, 20.0 * fg as f32 / 255.0);
for i in 0..8 {
if i < fg {
assert!((protected[i] - narrowed[i]).abs() <= 1.0 / 255.0, "fg block {fg}: block {i} {protected:?} vs {narrowed:?}");
} else {
assert_eq!(protected[i], 1.0, "fg block {fg}: block {i} kept, {protected:?}");
}
}
}
}
#[test]
fn a_foreground_equal_to_the_sample_erases_nothing() {
for limits in [Limits::Contiguous, Limits::Discontiguous, Limits::FindEdges] {
for tolerance in [0.0, 0.1, 0.5, 1.0] {
let s = blocks(PixelFormat::RGBA8);
let mut t = s.clone();
let bs = BgEraseSettings { limits, tolerance, ..settings(Some(0)) };
apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None);
assert_eq!(t, s, "{limits:?} tolerance {tolerance}");
}
}
}
#[test]
fn find_edges_keeps_the_foreground_colour_itself() {
// Find Edges grades like Contiguous (#11904); a pixel exactly at the foreground stays.
let fmt = PixelFormat::RGBA8;
let mut s = blocks(fmt);
let bs = BgEraseSettings { limits: Limits::FindEdges, ..settings(Some(1)) };
apply_background_eraser(&mut s, &stroke(&[(80.0, 150.0), (120.0, 150.0)]), &bs, None);
assert_eq!(s.rgba(75, 150)[3], 0.0, "the sample erased");
assert_eq!(s.rgba(110, 150)[3], 1.0, "the foreground colour kept");
}
#[test]
fn protect_off_is_unchanged() {
// The drag without protection: the reference's row, which the protection change leaves alone.
assert_near(drag(PixelFormat::RGBA8, None), UNPROTECTED, "protection off");
let mut s = blocks(PixelFormat::RGBA8);
let mut t = s.clone();
let on_far = BgEraseSettings { foreground: [0.0, 0.0, 1.0, 1.0], protect_foreground: true, ..settings(None) };
apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &settings(None), None);
apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &on_far, None);
assert_eq!(s, t, "a foreground beyond the Tolerance protects nothing");
}
#[test]
fn protection_works_in_the_documents_own_channels() {
// 16-bit RGB: the same rows as 8-bit.
let rgb16 = PixelFormat::new(ColorMode::Rgb, SampleType::U16, true);
for (fg, want) in REFERENCE {
assert_near(drag(rgb16, Some(fg)), want, &format!("16-bit fg block {fg}"));
}
// Gray: blocks stepping by 20 in gray; foreground at block 3 keeps blocks 3 and beyond and
// still erases block 0.
let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, true);
let mut s = Surface::new(gray);
let level = |i: usize| (40.0 + 20.0 * i as f32) / 255.0;
for i in 0..8 {
let x = 100 * i as i32;
s.fill_rect(Rect::new(x, 0, x + 100, 300), &[level(i), 1.0]);
}
let fg = [level(3), level(3), level(3), 1.0];
let bs = BgEraseSettings { foreground: fg, ..settings(Some(3)) };
apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None);
let a: Vec<f32> = (0..8).map(|i| s.rgba(100 * i + 50, 150)[3]).collect();
assert_eq!(a[0], 0.0, "gray: the sample erased, {a:?}");
for (i, v) in a.iter().enumerate().skip(3) {
assert_eq!(*v, 1.0, "gray: block {i} kept, {a:?}");
}
}
#[test]
fn the_foreground_is_matched_at_the_documents_precision() {
// Mid grey 0.5 lies between two 8-bit (and 16-bit) levels and is stored one level up, nearer
// white. The stored foreground colour must still count as the foreground, and a foreground
// that is stored as the sampled colour must still protect everything.
let grey = [0.5, 0.5, 0.5, 1.0];
for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let fmt = PixelFormat::new(mode, sample, true);
let bs = BgEraseSettings {
sampling: Sampling::Once,
limits: Limits::FindEdges,
tolerance: 1.0,
protect_foreground: true,
foreground: grey,
..Default::default()
};
// White (the sample) next to the foreground grey.
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, [1.0; 4]));
s.fill_rect(Rect::new(100, 0, 200, 100), &from_rgba(&fmt, grey));
apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None);
assert_eq!(s.rgba(50, 50)[3], 0.0, "{fmt:?}: the sample erased");
assert_eq!(s.rgba(150, 50)[3], 1.0, "{fmt:?}: the stored foreground colour kept");
// The foreground grey is also the sample.
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(0, 0, 200, 100), &from_rgba(&fmt, grey));
let t = s.clone();
apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None);
assert_eq!(s, t, "{fmt:?}: a foreground stored as the sample erases nothing");
}
}
}
@@ -0,0 +1,274 @@
//! #11908: the Background Eraser's options bar has an Angle field between Tolerance and Protect
//! Foreground Color (0° by default, "Set the brush angle", whole degrees from −180 to 180, with the
//! reference application's alert for a typed value outside that) and a Pressure for Size toggle
//! after Protect Foreground Color. Both edit the tool's own brush.
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::PhotocraftApp;
use crate::state::{DialogKind, Tool};
use crate::theme::ThemeKind;
const PRESSURE: &str = "Always use pressure for size";
fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.ui.tool = tool;
let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, ThemeKind::ProMedium);
h.run_steps(4);
h
}
fn angle_field<'a>(h: &'a Harness<'static, PhotocraftApp>) -> Option<egui_kittest::Node<'a>> {
h.query_all_by_role(egui::accesskit::Role::SpinButton).find(|n| n.accesskit_node().description().as_deref() == Some("Set the brush angle"))
}
fn shown(h: &Harness<'static, PhotocraftApp>) -> String {
angle_field(h).expect("the Angle field").accesskit_node().value().map(|v| v.to_string()).unwrap_or_default()
}
fn left(h: &Harness<'static, PhotocraftApp>, label: &str) -> f64 {
h.get_by_label(label).accesskit_node().bounding_box().expect(label).x0
}
fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec<String> {
let dialogs = &h.state().ui.dialogs;
dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect()
}
fn type_angle(h: &mut Harness<'static, PhotocraftApp>, text: &str) -> f32 {
angle_field(h).expect("the Angle field").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(2);
h.state().session.tools.brush.angle
}
#[test]
fn angle_sits_between_tolerance_and_protect_foreground_color() {
let h = bar(Tool::BackgroundEraser);
let field = angle_field(&h).expect("the Angle field");
let angle = field.accesskit_node().bounding_box().unwrap().x0;
assert!(shown(&h).starts_with('0'), "default 0°: {}", shown(&h));
assert!(left(&h, "Tolerance:") < angle && angle < left(&h, "Protect Foreground Color"), "Tolerance < Angle < Protect Foreground Color");
assert_eq!(h.state().session.tools.brush.angle, 0.0);
}
#[test]
fn typed_angles_are_whole_degrees_clamped_with_the_alert() {
let mut h = bar(Tool::BackgroundEraser);
assert_eq!(type_angle(&mut h, "45.5"), 45.0);
assert_eq!(type_angle(&mut h, "-30"), -30.0);
assert!(alerts(&h).is_empty(), "in range: no alert, {:?}", alerts(&h));
assert_eq!(type_angle(&mut h, "400"), 180.0);
assert_eq!(alerts(&h), vec!["An integer between -180 ° and 180 ° is required. Closest value inserted.".to_string()]);
assert!(shown(&h).starts_with("180"), "{}", shown(&h));
h.state_mut().ui.dialogs.clear();
assert_eq!(type_angle(&mut h, "-200"), -180.0);
assert_eq!(alerts(&h).len(), 1, "one alert for -200");
}
#[test]
fn an_entry_left_by_a_tool_switch_does_not_alert_later() {
let mut h = bar(Tool::BackgroundEraser);
angle_field(&h).expect("the Angle field").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("400".into()));
h.run_steps(1);
// The tool changes before the entry is committed: the field goes away mid-typing.
h.state_mut().ui.tool = Tool::Brush;
h.run_steps(3);
h.state_mut().ui.tool = Tool::BackgroundEraser;
h.run_steps(3);
angle_field(&h).expect("the Angle field").click();
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert!(alerts(&h).is_empty(), "nothing typed this time: {:?}", alerts(&h));
}
#[test]
fn an_entry_kept_while_the_window_is_in_the_background_still_alerts() {
let mut h = bar(Tool::BackgroundEraser);
angle_field(&h).expect("the Angle field").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("400".into()));
h.run_steps(1);
// Another window takes the focus mid-entry, then this one gets it back.
h.input_mut().focused = false;
h.event(egui::Event::WindowFocused(false));
h.run_steps(3);
h.input_mut().focused = true;
h.event(egui::Event::WindowFocused(true));
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(h.state().session.tools.brush.angle, 180.0);
assert_eq!(alerts(&h), vec![crate::eraser_ui::ANGLE_RANGE_MESSAGE.to_string()], "typed before the switch, so it alerts");
}
#[test]
fn pressure_for_size_follows_protect_foreground_color_off_by_default() {
let mut h = bar(Tool::BackgroundEraser);
assert!(left(&h, "Protect Foreground Color") < left(&h, PRESSURE));
assert!(!h.state().session.tools.brush.pressure_size, "off by default");
h.get_by_label(PRESSURE).click();
h.run_steps(2);
assert!(h.state().session.tools.brush.pressure_size);
h.get_by_label(PRESSURE).click();
h.run_steps(2);
assert!(!h.state().session.tools.brush.pressure_size);
}
#[test]
fn angle_and_pressure_are_the_background_erasers_own() {
let mut h = bar(Tool::Brush);
h.state_mut().run("tools.setBrush", json!({"brush": {"angle": -20.0}})).unwrap();
h.run_steps(2);
h.state_mut().ui.tool = Tool::BackgroundEraser;
h.run_steps(3);
type_angle(&mut h, "30");
h.get_by_label(PRESSURE).click();
h.run_steps(2);
h.state_mut().ui.tool = Tool::Brush;
h.run_steps(3);
let brush = &h.state().session.tools.brush;
assert_eq!((brush.angle, brush.pressure_size), (-20.0, false), "the Brush keeps its own angle and pressure");
h.state_mut().ui.tool = Tool::BackgroundEraser;
h.run_steps(3);
let brush = &h.state().session.tools.brush;
assert_eq!((brush.angle, brush.pressure_size), (30.0, true), "the Background Eraser's values come back");
assert!(shown(&h).starts_with("30"), "{}", shown(&h));
}
#[test]
fn the_field_shows_the_brush_settings_angle() {
let mut h = bar(Tool::BackgroundEraser);
// The Brush Settings panel edits the live brush's angle through `tools.setBrush`.
h.state_mut().run("tools.setBrush", json!({"brush": {"angle": 60.0}})).unwrap();
h.run_steps(2);
assert!(shown(&h).starts_with("60"), "{}", shown(&h));
type_angle(&mut h, "-75");
assert_eq!(h.state().session.tools.brush.angle, -75.0, "what the panel reads");
}
#[test]
fn the_magic_eraser_has_neither() {
let bg = bar(Tool::BackgroundEraser);
assert!(bg.query_by_label("Angle").is_some(), "the Background Eraser's field is found by its name");
let h = bar(Tool::MagicEraser);
assert!(angle_field(&h).is_none());
assert!(h.query_by_label("Angle").is_none(), "no field named Angle, whatever its tooltip");
assert!(h.query_by_label(PRESSURE).is_none());
}
/// Focus the field and press `key` `n` times, then Enter.
fn step_angle(h: &mut Harness<'static, PhotocraftApp>, key: egui::Key, n: usize) -> f32 {
angle_field(h).expect("the Angle field").click();
h.run_steps(1);
for _ in 0..n {
h.key_press(key);
h.run_steps(1);
}
h.key_press(egui::Key::Enter);
h.run_steps(2);
h.state().session.tools.brush.angle
}
#[test]
fn arrow_steps_stop_at_the_ends_without_the_alert() {
let mut h = bar(Tool::BackgroundEraser);
type_angle(&mut h, "178");
assert_eq!(step_angle(&mut h, egui::Key::ArrowUp, 5), 180.0);
type_angle(&mut h, "-178");
assert_eq!(step_angle(&mut h, egui::Key::ArrowDown, 5), -180.0);
assert!(alerts(&h).is_empty(), "stepping is not typing: {:?}", alerts(&h));
}
#[test]
fn a_click_away_commits_with_the_alert() {
let mut h = bar(Tool::BackgroundEraser);
angle_field(&h).expect("the Angle field").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("400".into()));
h.run_steps(1);
h.get_by_label(PRESSURE).click();
h.run_steps(3);
assert_eq!(h.state().session.tools.brush.angle, 180.0);
assert_eq!(alerts(&h).len(), 1, "one alert on click-away: {:?}", alerts(&h));
}
#[test]
fn an_entry_that_is_not_a_number_keeps_the_angle_without_the_alert() {
let mut h = bar(Tool::BackgroundEraser);
type_angle(&mut h, "30");
for text in ["", "abc", "inf", "NaN"] {
assert_eq!(type_angle(&mut h, text), 30.0, "{text:?}");
}
assert!(alerts(&h).is_empty(), "{:?}", alerts(&h));
}
fn wheel_event(lines: f32) -> egui::Event {
egui::Event::MouseWheel {
source: egui::MouseWheelSource::Unknown,
unit: egui::MouseWheelUnit::Line,
delta: vec2(0.0, lines),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
}
}
#[test]
fn wheel_steps_with_the_focus_stop_at_the_ends_without_the_alert() {
// As in the app: the focused field takes the wheel before the bar is laid out.
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.ui.tool = Tool::BackgroundEraser;
let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(
|ui, app| {
crate::field_wheel::begin_frame(ui.ctx());
crate::panels::options_bar(app, ui)
},
app,
);
PhotocraftApp::setup_context(&h.ctx, ThemeKind::ProMedium);
h.run_steps(4);
type_angle(&mut h, "178");
angle_field(&h).expect("the Angle field").click();
h.run_steps(1);
for _ in 0..5 {
h.event(wheel_event(1.0));
h.run_steps(1);
}
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(h.state().session.tools.brush.angle, 180.0);
assert!(alerts(&h).is_empty(), "a wheel step is not typing: {:?}", alerts(&h));
}
#[test]
fn a_view_scroll_while_typing_keeps_the_alert() {
let mut h = bar(Tool::BackgroundEraser);
angle_field(&h).expect("the Angle field").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
// A scroll the field does not take (no wheel hand-off here) arrives with the typed text.
h.event(wheel_event(-3.0));
h.event(egui::Event::Text("400".into()));
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(h.state().session.tools.brush.angle, 180.0);
assert_eq!(alerts(&h), vec![crate::eraser_ui::ANGLE_RANGE_MESSAGE.to_string()], "typed, so it alerts");
}
+187
View File
@@ -0,0 +1,187 @@
//! #12193: Content-Aware Move's Structure and Color open a whole-number slider popup, the bar's
//! controls carry the reference tooltips, a typed value outside the range alerts and keeps the
//! closest value, and a live Transform On Drop box greys the bar with Cancel then Commit at the
//! right end. Changing these controls is not a history state.
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::PhotocraftApp;
use crate::state::{DialogKind, Tool};
use super::{COLOR_RANGE_ALERT, STRUCTURE_RANGE_ALERT};
fn app_harness(live_box: bool) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
app.ui.tool = Tool::ContentAwareMove;
if live_box {
app.ui.tool_options.cam_transform_on_drop = true;
assert!(crate::cam_transform::begin(&mut app, [20, 8]), "the dropped patch gets a box");
}
app
});
h.run_steps(5);
h
}
fn spin<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> egui_kittest::Node<'a> {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("the {label} field"))
}
/// Types `text` into the named field, then leaves it with Tab or Enter.
fn type_field(h: &mut Harness<'static, PhotocraftApp>, label: &str, text: &str, key: egui::Key) {
spin(h, label).click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(key);
h.run_steps(3);
}
fn alert(h: &Harness<'static, PhotocraftApp>) -> Option<String> {
h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).and_then(|d| d.fields.get("message")).and_then(|m| m.as_str()).map(str::to_owned)
}
fn steps(h: &Harness<'static, PhotocraftApp>) -> usize {
h.state().session.active().unwrap().history.past_len()
}
fn click_at(h: &mut Harness<'static, PhotocraftApp>, p: egui::Pos2) {
h.hover_at(p);
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(3);
}
#[test]
fn structure_and_color_default_to_whole_numbers_and_open_a_slider() {
let mut h = app_harness(false);
assert_eq!(h.state().ui.tool_options.cam_structure, 4.0);
assert_eq!(h.state().ui.tool_options.cam_color, 0.0);
assert_eq!(spin(&h, "Structure:").accesskit_node().numeric_value(), Some(4.0));
assert_eq!(spin(&h, "Color:").accesskit_node().numeric_value(), Some(0.0));
assert!(h.query_all_by_role(Role::Slider).next().is_none(), "the slider stays closed");
let before = steps(&h);
h.get_by_role_and_label(Role::Button, "Structure").click();
h.run_steps(4);
let slider = h.get_by_role_and_label(Role::Slider, "Structure").rect();
click_at(&mut h, egui::pos2(slider.right() - 3.0, slider.center().y));
assert_eq!(h.state().ui.tool_options.cam_structure, 7.0, "the slider's far end is 7");
assert_eq!(h.state().ui.tool_options.cam_structure.fract(), 0.0);
assert_eq!(alert(&h), None, "the slider does not alert");
assert_eq!(steps(&h), before, "the slider is not a history state");
h.get_by_role_and_label(Role::Button, "Color").click();
h.run_steps(4);
let color = h.get_by_role_and_label(Role::Slider, "Color").rect();
click_at(&mut h, egui::pos2(color.right() - 3.0, color.center().y));
assert_eq!(h.state().ui.tool_options.cam_color, 10.0);
assert_eq!(h.state().ui.tool_options.cam_color.fract(), 0.0);
assert_eq!(steps(&h), before);
}
#[test]
fn a_typed_value_outside_the_range_alerts_and_keeps_the_closest() {
for (label, typed, key, want, message) in [
("Structure:", "99", egui::Key::Enter, 7.0, STRUCTURE_RANGE_ALERT),
("Structure:", "0", egui::Key::Tab, 1.0, STRUCTURE_RANGE_ALERT),
("Color:", "99", egui::Key::Enter, 10.0, COLOR_RANGE_ALERT),
("Color:", "-5", egui::Key::Tab, 0.0, COLOR_RANGE_ALERT),
] {
let mut h = app_harness(false);
let before = steps(&h);
type_field(&mut h, label, typed, key);
let got = if label.starts_with("Structure") { h.state().ui.tool_options.cam_structure } else { h.state().ui.tool_options.cam_color };
assert_eq!(got, want, "{label} {typed}");
assert_eq!(alert(&h).as_deref(), Some(message), "{label} {typed}");
assert_eq!(steps(&h), before, "{label} {typed}: not a history state");
h.get_by_label("OK").click();
h.run_steps(4);
assert_eq!(alert(&h), None, "{label} {typed}: OK closes the alert");
let got = if label.starts_with("Structure") { h.state().ui.tool_options.cam_structure } else { h.state().ui.tool_options.cam_color };
assert_eq!(got, want, "{label} {typed}: the closest value stays");
}
}
#[test]
fn a_typed_value_inside_the_range_is_a_whole_number_without_an_alert() {
let mut h = app_harness(false);
let before = steps(&h);
type_field(&mut h, "Structure:", "4.2", egui::Key::Tab);
assert_eq!(h.state().ui.tool_options.cam_structure, 4.0);
type_field(&mut h, "Structure:", "6", egui::Key::Enter);
assert_eq!(h.state().ui.tool_options.cam_structure, 6.0);
type_field(&mut h, "Color:", "3.6", egui::Key::Tab);
assert_eq!(h.state().ui.tool_options.cam_color, 4.0);
type_field(&mut h, "Color:", "10", egui::Key::Enter);
assert_eq!(h.state().ui.tool_options.cam_color, 10.0);
type_field(&mut h, "Color:", "0", egui::Key::Tab);
assert_eq!(h.state().ui.tool_options.cam_color, 0.0);
assert_eq!(alert(&h), None);
assert_eq!(steps(&h), before);
}
#[test]
fn the_bar_has_the_reference_tooltips() {
for (role, label, tip) in [
(Role::ComboBox, "Mode:", "Choose a remix mode"),
(Role::SpinButton, "Structure:", "Adjust how strictly the source structure is preserved"),
(Role::SpinButton, "Color:", "Adjust how much the source color can be modified"),
(Role::CheckBox, "Sample All Layers", "Enable to remix all layers"),
(Role::CheckBox, "Transform On Drop", "Allows rotation and scaling of selection"),
] {
let mut h = app_harness(false);
assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover");
let at = h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("{label}")).rect().center();
h.hover_at(at);
// The tooltip waits out its delay; the harness steps at 1/60 s.
h.run_steps(60);
assert!(h.query_by_label(tip).is_some(), "{label}: resting on it shows {tip:?}");
}
}
#[test]
fn a_live_transform_box_greys_the_bar_and_puts_cancel_then_commit_at_the_right() {
let h = app_harness(false);
assert!(h.query_by_label("Commit transform").is_none());
assert!(h.query_by_label("Cancel transform").is_none());
assert!(h.query_by_label("Lasso around an area, then drag the selection").is_some());
let mut h = app_harness(true);
for (role, label) in [
(Role::Button, "New selection"),
(Role::ComboBox, "Mode:"),
(Role::SpinButton, "Structure:"),
(Role::SpinButton, "Color:"),
(Role::CheckBox, "Sample All Layers"),
(Role::CheckBox, "Transform On Drop"),
] {
let node = h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("{label}"));
assert!(node.accesskit_node().is_disabled(), "{label} is greyed while the box is up");
}
assert!(h.query_by_label("Lasso around an area, then drag the selection").is_none());
let cancel = h.get_by_label("Cancel transform");
let commit = h.get_by_label("Commit transform");
assert!(!cancel.accesskit_node().is_disabled() && !commit.accesskit_node().is_disabled());
let (cancel, commit) = (cancel.rect(), commit.rect());
assert!(cancel.right() <= commit.left() + 1.0, "Cancel then Commit: {cancel:?} {commit:?}");
let sample = h.get_by_role_and_label(Role::CheckBox, "Transform On Drop").rect();
assert!(cancel.left() > sample.right(), "the pair sits to the right of the controls");
assert!(commit.right() > 1200.0, "Commit is at the right end of the bar: {commit:?}");
let before = steps(&h);
h.get_by_label("Cancel transform").click();
h.run_steps(4);
assert!(!crate::cam_transform::active(h.state()));
assert_eq!(steps(&h), before, "Cancel drops the box without a history state");
assert!(!spin(&h, "Structure:").accesskit_node().is_disabled(), "the bar is usable again");
}
@@ -0,0 +1,86 @@
//! Content-Aware Move › Transform On Drop starts on (#12185): a fresh start and Reset Tool give
//! the checkbox on, a drop shows the scale and rotate box, Enter commits a plain move and Escape
//! cancels it. A saved `false` stays off; a missing key takes the new default.
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::{Tool, ToolOptions};
fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 100, "height": 60})).unwrap();
app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap();
app.run("select.rect", json!({"x": 6, "y": 14, "width": 32, "height": 32})).unwrap();
app.ui.tool = Tool::ContentAwareMove;
app
}
fn blue(app: &PhotocraftApp, x: i32, y: i32) -> bool {
let st = app.session.active().unwrap();
let layer = st.active_layer.and_then(|id| st.doc.layer(id)).unwrap();
layer.surface().unwrap().rgba(x, y)[0] < 0.5
}
fn drop_patch(app: &mut PhotocraftApp) {
let m = egui::Modifiers::NONE;
tool_event(app, ToolEvent::Down { x: 22.0, y: 30.0, pressure: 1.0 }, m);
tool_event(app, ToolEvent::Move { x: 72.0, y: 30.0, pressure: 1.0 }, m);
tool_event(app, ToolEvent::Up { x: 72.0, y: 30.0 }, m);
}
#[test]
fn fresh_start_and_reset_tool_leave_transform_on_drop_on() {
assert!(ToolOptions::default().cam_transform_on_drop);
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
assert!(app.ui.tool_options.cam_transform_on_drop, "a fresh start leaves Transform On Drop on");
app.ui.tool = Tool::ContentAwareMove;
app.ui.tool_options.cam_transform_on_drop = false;
crate::menus::invoke(&mut app, &egui::Context::default(), crate::tools::tool_reset::RESET, json!({})).unwrap();
assert!(app.ui.tool_options.cam_transform_on_drop, "Reset Tool turns Transform On Drop back on");
}
#[test]
fn a_stored_false_stays_off_and_a_missing_key_is_on() {
let mut v = serde_json::to_value(ToolOptions::default()).unwrap();
v["cam_transform_on_drop"] = json!(false);
let stored: ToolOptions = serde_json::from_value(v.clone()).unwrap();
assert!(!stored.cam_transform_on_drop, "a saved false stays off");
v.as_object_mut().unwrap().remove("cam_transform_on_drop");
let missing: ToolOptions = serde_json::from_value(v).unwrap();
assert!(missing.cam_transform_on_drop, "a missing key takes the new default");
}
#[test]
fn a_drop_shows_the_box_enter_commits_a_plain_move_and_escape_cancels() {
let mut app = app();
assert!(app.ui.tool_options.cam_transform_on_drop);
let steps = app.session.active().unwrap().history.past_len();
drop_patch(&mut app);
assert!(crate::cam_transform::active(&app), "the drop shows the box");
assert!(blue(&app, 22, 30) && !blue(&app, 72, 30), "the document waits");
assert_eq!(app.session.active().unwrap().history.past_len(), steps);
let place = crate::cam_transform::placement(app.ui.cam_transform.as_ref().unwrap()).unwrap();
assert!(place.is_plain_move());
let p = crate::cam_transform::params(&app, &place);
assert!(p.get("scaleX").is_none() && p.get("scaleY").is_none() && p.get("rotate").is_none(), "a plain move sends no scale or rotate: {p}");
assert_eq!(p["offset"], json!([50, 0]));
crate::cam_transform::cancel(&mut app);
assert!(!crate::cam_transform::active(&app));
assert!(blue(&app, 22, 30) && !blue(&app, 72, 30), "Escape cancels the move");
assert_eq!(app.session.active().unwrap().history.past_len(), steps);
assert_ne!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.contentAwareMove"));
drop_patch(&mut app);
assert!(crate::cam_transform::active(&app));
crate::cam_transform::commit(&mut app);
assert!(!crate::cam_transform::active(&app) && !app.ui.status_error, "{}", app.ui.status);
let (id, sent) = app.session.journal.last().cloned().unwrap();
assert_eq!(id, "paint.contentAwareMove");
assert_eq!(sent["offset"], json!([50, 0]));
assert!(sent.get("scaleX").is_none() && sent.get("scaleY").is_none() && sent.get("rotate").is_none(), "{sent}");
assert!(blue(&app, 72, 30) && !blue(&app, 22, 30), "Enter commits the plain move");
assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);
}
+2
View File
@@ -236,6 +236,7 @@ mod tests {
app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap();
app.run("select.lasso", json!({"points": [[6, 14], [38, 14], [38, 46], [6, 46]]})).unwrap();
app.ui.tool = Tool::ContentAwareMove;
app.ui.tool_options.cam_transform_on_drop = false;
let m = egui::Modifiers::NONE;
let steps = app.session.active().unwrap().history.past_len();
@@ -317,6 +318,7 @@ mod tests {
app.run("paint.pencil", json!({"points": [[150, 160], [170, 160]], "size": 12, "color": "#0000ff"})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 10, "width": 300, "height": 300})).unwrap();
app.ui.tool = Tool::ContentAwareMove;
app.ui.tool_options.cam_transform_on_drop = false;
let m = egui::Modifiers::NONE;
tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m);
tool_event(&mut app, ToolEvent::Move { x: 340.0, y: 100.0, pressure: 1.0 }, m);
+48 -1
View File
@@ -47,7 +47,7 @@ use gradient_map::gradient_map;
pub use gradient_map::{gradient_presets, is_gray, swatches};
use hue_saturation::hue_saturation;
#[cfg(test)]
use hue_saturation::{lightness_track, move_hue_range_handle, saturation_track};
use hue_saturation::{hue_range_handle_at, hue_range_zone, lightness_track, move_hue_range_handle, move_hue_range_zone, saturation_track};
use levels::levels;
pub(crate) use levels::levels_drag;
pub use levels::{auto_levels, gamma_from_pos, gamma_pos};
@@ -273,6 +273,53 @@ mod tests {
assert_eq!(track_stops(&cx(false), &stops), None);
}
/// #9272 review: at the narrowest Properties panel (a 230-point bar) a 30° zone is ~19 points
/// wide; a press in its middle grabs the zone, not a handle, while each handle stays grabbable.
#[test]
fn hue_range_zones_stay_selectable_on_a_narrow_bar() {
let w = 230.0;
let xs = [75.0f32, 105.0, 135.0, 165.0].map(|d| d / 360.0 * w);
for (a, z) in [(0, 1), (1, 2), (2, 3)] {
assert_eq!(hue_range_handle_at(xs, (xs[a] + xs[z]) / 2.0, w), None, "the middle of zone {a}..{z} is the zone's");
}
for (k, x) in xs.iter().enumerate() {
assert_eq!(hue_range_handle_at(xs, *x + 1.0, w), Some(k as u8), "handle {k}");
}
assert_eq!(hue_range_handle_at(xs, xs[0] - 9.0, w), Some(0), "the full reach outside the range");
let stacked = [50.0, 50.0, 80.0, 120.0];
assert!(hue_range_handle_at(stacked, 51.0, w).is_some(), "coinciding handles stay grabbable");
// Reds (315/345…15\45): its fully-on zone crosses the seam, ~9.6 points from each edge.
let reds = [315.0f32, 345.0, 15.0, 45.0].map(|d| d / 360.0 * w);
for x in [w - 1.0, w - 3.0, 0.5, 2.5] {
assert_eq!(hue_range_handle_at(reds, x, w), None, "x {x}: Reds' fully-on zone across the seam");
}
assert_eq!(hue_range_handle_at(reds, reds[1] + 1.0, w), Some(1));
assert_eq!(hue_range_handle_at(reds, reds[2] - 1.0, w), Some(2));
}
/// #9252: Photoshop 2025's zone drags on a colour range (measured on Reds): the fully-on span
/// moves all four handles, each fade its own two; a side stops at the other and the range
/// never passes a turn.
#[test]
fn hue_range_zones_move_their_handles() {
let reds = [-45.0, -15.0, 15.0, 45.0];
assert_eq!(hue_range_zone(reds, 345.0 - 15.0), Some(0));
assert_eq!(hue_range_zone(reds, 0.0), Some(1));
assert_eq!(hue_range_zone(reds, 30.0), Some(2));
assert_eq!(hue_range_zone(reds, 180.0), None);
let centre = move_hue_range_zone(reds, 1, 37.0);
assert_eq!(centre, [-8.0, 22.0, 52.0, 82.0], "all four, as Photoshop's 315/345…15\\45 → 352/21…52\\81");
let left = move_hue_range_zone(centre, 0, -19.0);
assert_eq!(left, [-27.0, 3.0, 52.0, 82.0], "the left two only");
let right = move_hue_range_zone(left, 2, 19.0);
assert_eq!(right, [-27.0, 3.0, 71.0, 101.0], "the right two only");
assert_eq!(move_hue_range_zone(reds, 0, 100.0), [-15.0, 15.0, 15.0, 45.0], "the left side stops at the right");
assert_eq!(move_hue_range_zone(reds, 2, -100.0), [-45.0, -15.0, -15.0, 15.0], "and the right at the left");
let wide = move_hue_range_zone(reds, 2, 500.0);
assert!(wide[3] - wide[0] <= 359.0 + 1e-3, "{wide:?}");
assert_eq!(move_hue_range_zone(reds, 1, f32::NAN), reds);
}
#[test]
fn hue_range_drag_canonicalizes_bounds_before_clamping() {
let moved = move_hue_range_handle([0.0, 350.0, 100.0, 200.0], 2, 354.0);
@@ -38,6 +38,62 @@ pub(super) fn move_hue_range_handle(bounds: [f32; 4], k: usize, deg: f32) -> [f3
b
}
/// The range handle a press at `x` grabs, given the four handles' x positions on a bar `w` wide:
/// the nearest within 10 points, or within a third of the gap to the next handle on that side, so
/// the middle third of a narrow zone still drags the zone (at least 3 points, for handles that
/// coincide). The bar is a hue circle: the next handle past an edge is the first from the other.
pub(super) fn hue_range_handle_at(xs: [f32; 4], x: f32, w: f32) -> Option<u8> {
let k = nearest(&xs, x)?;
let (xk, d) = (xs[k as usize], x - xs[k as usize]);
let gap = xs
.iter()
.enumerate()
.filter(|&(j, _)| j != k as usize)
.map(|(_, &o)| if d >= 0.0 { (o - xk).rem_euclid(w) } else { (xk - o).rem_euclid(w) })
.fold(f32::INFINITY, f32::min);
(d.abs() < (gap / 3.0).clamp(3.0, 10.0)).then_some(k)
}
/// Which zone of a colour range a hue `deg` falls in, between its handles: 0 = the left fade
/// (between the first two), 1 = the fully-on span, 2 = the right fade; `None` outside the range.
pub(super) fn hue_range_zone(bounds: [f32; 4], deg: f32) -> Option<u8> {
let b = HueRange::canonical_bounds(bounds);
let rel = (deg - b[0]).rem_euclid(360.0);
let (one, two, three) = (b[1] - b[0], b[2] - b[0], b[3] - b[0]);
if rel <= one {
Some(0)
} else if rel <= two {
Some(1)
} else if rel <= three {
Some(2)
} else {
None
}
}
/// A drag of `delta` degrees on a zone of a colour range (#9252), as in Photoshop: the left fade
/// moves the two left handles, the fully-on span all four, the right fade the two right handles;
/// a side never crosses the other or grows the range past a turn.
pub(super) fn move_hue_range_zone(start: [f32; 4], zone: u8, delta: f32) -> [f32; 4] {
let b = HueRange::canonical_bounds(start);
if !delta.is_finite() {
return b;
}
let moved = match zone {
0 => {
let d = delta.min(b[2] - b[1]).max(b[3] - 359.0 - b[0]);
[b[0] + d, b[1] + d, b[2], b[3]]
}
1 => b.map(|v| v + delta),
2 => {
let d = delta.max(b[1] - b[2]).min(b[0] + 359.0 - b[3]);
[b[0], b[1], b[2] + d, b[3] + d]
}
_ => b,
};
HueRange::canonical_bounds(moved)
}
/// The spectrum bar after the adjustment (what each hue becomes), sampled at `n` hues.
fn adjusted_spectrum(v: &Value, n: usize) -> Vec<Color32> {
let adj = photocraft_engine::commands::adjustment_from_params("hueSaturation", v);
@@ -177,17 +233,44 @@ pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) ->
p.rect_filled(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, fill);
p.rect_stroke(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, Stroke::new(1.0, t.text_dim), StrokeKind::Inside);
}
ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-range-bars"), bars));
let drag_id = cx.mem.with("hs-range-drag");
let zone_id = cx.mem.with("hs-range-zone");
let mut which: Option<u8> = ui.data(|d| d.get_temp(drag_id)).flatten();
// A press between the handles drags a zone (#9252): its zone, the bounds and x it began at.
let mut zone: Option<(u8, [f32; 4], f32)> = ui.data(|d| d.get_temp(zone_id)).flatten();
if bresp.is_pointer_button_down_on()
&& ui.input(|i| i.pointer.primary_pressed())
&& let Some(pos) = ui.input(|i| i.pointer.press_origin())
{
which = nearest(&b.map(xof), pos.x).filter(|k| (xof(b[*k as usize]) - pos.x).abs() < 10.0);
which = hue_range_handle_at(b.map(xof), pos.x, w);
zone = if which.is_none() { hue_range_zone(b, deg_of(pos.x)).map(|z| (z, b, pos.x)) } else { None };
}
if bresp.is_pointer_button_down_on()
&& let (Some(k), Some(pos)) = (which, ui.input(|i| i.pointer.interact_pos()))
{
// The release frame applies its position too: a move and a release that land in one frame
// would otherwise commit the bounds from before the move. It ends where the button let go,
// not where the pointer went after that in the same frame.
let released_at = ui.input(|i| {
i.events.iter().find_map(|e| match e {
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos),
_ => None,
})
});
let live = bresp.is_pointer_button_down_on() || released_at.is_some();
let drag_pos = released_at.or_else(|| ui.input(|i| i.pointer.interact_pos()));
if live && let (Some((z, start, x0)), Some(pos)) = (zone, drag_pos) {
let before = b;
b = move_hue_range_zone(start, z, (pos.x - x0) / w * 360.0);
if b != before {
v[key]["range"] = json!(b.map(|x| x.round()));
e.changed = true;
}
}
if zone.is_some() && !bresp.is_pointer_button_down_on() {
zone = None;
e.commit = true;
}
ui.data_mut(|d| d.insert_temp(zone_id, zone));
if live && let (Some(k), Some(pos)) = (which, drag_pos) {
let k = k as usize;
let deg = deg_of(pos.x);
let before = b;
@@ -1148,6 +1148,138 @@ fn gradient_map_stop_picker_closed_without_a_colour_changes_nothing() {
}
}
/// #9252: in a Hue/Saturation layer's Properties, dragging the zones between the range handles
/// moves them as Photoshop does: the fully-on span all four, a fade its own two; one history step
/// per drag.
#[test]
fn hue_saturation_range_zones_drag_their_handles() {
let mut h = app_harness("hueSaturation", "rgb", 8);
let (id, _) = layer(&h);
let mem = crate::adjust_editors::layer_mem(id);
h.ctx.data_mut(|d| d.insert_temp(mem.with("hs-range"), 3usize)); // Greens: 75/105…135\165
h.run_steps(3);
let bars: Rect = h.ctx.data(|d| d.get_temp(mem.with("hs-range-bars"))).expect("the range bars");
let x = |deg: f32| bars.left() + deg / 360.0 * bars.width();
let y = bars.center().y;
let greens = |h: &Harness<'_, PhotocraftApp>| match layer(h).1 {
Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds,
other => panic!("{other:?}"),
};
let steps = h.state().session.active().unwrap().history.past_len();
drag(&mut h, Pos2::new(x(120.0), y), Pos2::new(x(156.0), y));
let b = greens(&h);
assert!((b[0] - 111.0).abs() <= 1.0 && (b[3] - 201.0).abs() <= 1.0 && (b[1] - b[0] - 30.0).abs() < 0.5, "all four moved ~36°: {b:?}");
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one step");
let before = greens(&h);
drag(&mut h, Pos2::new(x((before[0] + before[1]) / 2.0), y), Pos2::new(x((before[0] + before[1]) / 2.0 - 18.0), y));
let b = greens(&h);
assert!((b[0] - (before[0] - 18.0)).abs() <= 1.0 && (b[1] - (before[1] - 18.0)).abs() <= 1.0, "left two moved: {before:?} → {b:?}");
assert_eq!([b[2], b[3]], [before[2], before[3]], "right two stay");
}
/// CodeRabbit on #9272: a move and release that land in the same frame still move the zone; the
/// release frame applies its position before the drag commits.
#[test]
fn a_zone_drag_released_in_the_frame_it_moves_still_moves() {
let mut h = app_harness("hueSaturation", "rgb", 8);
let (id, _) = layer(&h);
let mem = crate::adjust_editors::layer_mem(id);
h.ctx.data_mut(|d| d.insert_temp(mem.with("hs-range"), 3usize)); // Greens: 75/105…135\165
h.run_steps(3);
let bars: Rect = h.ctx.data(|d| d.get_temp(mem.with("hs-range-bars"))).expect("the range bars");
let x = |deg: f32| bars.left() + deg / 360.0 * bars.width();
let y = bars.center().y;
let steps = h.state().session.active().unwrap().history.past_len();
let (from, to) = (Pos2::new(x(120.0), y), Pos2::new(x(156.0), y));
h.hover_at(from);
h.run_steps(1);
h.drag_at(from);
h.run_steps(1);
// One frame: the pointer moves and lets go (the harness's queued events take a frame each,
// so both go straight into the next frame's input).
let events = &mut h.input_mut().events;
events.push(egui::Event::PointerMoved(to));
events.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(3);
let b = match layer(&h).1 {
Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds,
other => panic!("{other:?}"),
};
assert!((b[0] - 111.0).abs() <= 1.0 && (b[3] - 201.0).abs() <= 1.0, "all four moved ~36°: {b:?}");
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one step");
// A handle released in the frame it moves lands there too.
let (from, to) = (Pos2::new(x(b[3]), y), Pos2::new(x(b[3] + 20.0), y));
h.hover_at(from);
h.run_steps(1);
h.drag_at(from);
h.run_steps(1);
let events = &mut h.input_mut().events;
events.push(egui::Event::PointerMoved(to));
events.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
h.run_steps(3);
let after = match layer(&h).1 {
Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds,
other => panic!("{other:?}"),
};
assert!((after[3] - (b[3] + 20.0)).abs() <= 1.0 && after[..3] == b[..3], "the right handle moved 20°: {b:?} → {after:?}");
// A release followed by more movement in one frame ends where the button let go.
let b = after;
let (from, to) = (Pos2::new(x((b[1] + b[2]) / 2.0), y), Pos2::new(x((b[1] + b[2]) / 2.0 + 10.0), y));
h.hover_at(from);
h.run_steps(1);
h.drag_at(from);
h.run_steps(1);
let events = &mut h.input_mut().events;
events.push(egui::Event::PointerMoved(to));
events.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
events.push(egui::Event::PointerMoved(Pos2::new(x(b[3] + 60.0), y)));
h.run_steps(3);
let last = match layer(&h).1 {
Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds,
other => panic!("{other:?}"),
};
assert!(last.iter().zip(&b).all(|(l, b)| (l - (b + 10.0)).abs() <= 1.0), "moved 10° to the release, not past it: {b:?} → {last:?}");
}
/// FredApps review on #9272: a zone drag across the 0/360 seam. Reds' fully-on span sits on both
/// ends of the bar; a drag from its middle third at either end (nearer a handle grabs the handle)
/// moves the whole range intact, and the handles that pass the seam come out at the other end.
#[test]
fn hue_saturation_range_zone_drags_across_the_seam() {
let mut h = app_harness("hueSaturation", "rgb", 8);
let (id, _) = layer(&h);
let mem = crate::adjust_editors::layer_mem(id);
h.ctx.data_mut(|d| d.insert_temp(mem.with("hs-range"), 1usize)); // Reds: 315/345…15\45
h.run_steps(3);
let bars: Rect = h.ctx.data(|d| d.get_temp(mem.with("hs-range-bars"))).expect("the range bars");
let x = |deg: f32| bars.left() + deg / 360.0 * bars.width();
let y = bars.center().y;
let reds = |h: &Harness<'_, PhotocraftApp>| match layer(h).1 {
Adjustment::HueSaturation { ranges, .. } => ranges[0].bounds,
other => panic!("{other:?}"),
};
let on_circle = |b: [f32; 4]| b.map(|d| d.rem_euclid(360.0).round());
let widths = |b: [f32; 4]| [b[1] - b[0], b[2] - b[1], b[3] - b[2]];
let mut steps = h.state().session.active().unwrap().history.past_len();
// (press, release, where the four handles land on the circle)
for (from, to, want) in [
// The span's right end, dragged left: 15\45 cross the seam to the right end.
(358.0, 298.0, [255.0, 285.0, 315.0, 345.0]),
// Back right from its middle: 315\345 cross the seam to the left end.
(300.0, 360.0, [315.0, 345.0, 15.0, 45.0]),
// The span's left end, dragged right: 315/345 cross the seam to the left end.
(2.0, 62.0, [15.0, 45.0, 75.0, 105.0]),
] {
let before = reds(&h);
drag(&mut h, Pos2::new(x(from), y), Pos2::new(x(to), y));
let b = reds(&h);
assert!(on_circle(b).iter().zip(&want).all(|(d, w)| (d - w).abs() <= 1.0), "{from}° → {to}°: {before:?} → {b:?}, want {want:?}");
assert_eq!(widths(b), widths(before), "{from}° → {to}°: the range moves intact");
steps += 1;
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "{from}° → {to}°: one step");
}
}
/// Selective Color in Properties: the Colors dropdown's choice lives in editor memory, so
/// switching colour commits nothing, and each colour keeps its own row.
#[test]
@@ -75,7 +75,7 @@ impl DetailPreview {
let result = match rx.try_recv() {
Ok(result) => result,
Err(TryRecvError::Empty) => return,
Err(TryRecvError::Disconnected) => Err("Camera Raw detail preview worker stopped".into()),
Err(TryRecvError::Disconnected) => Err("RAW Develop detail preview worker stopped".into()),
};
self.pending = None;
match result {
@@ -104,7 +104,7 @@ impl DetailPreview {
// The engine's full-image pipeline needs multiple temporary float buffers. Never start
// an unbounded allocation just because a huge sparse document was zoomed into.
if self.area.width() as u64 * self.area.height() as u64 > 64_000_000 {
self.error = Some("Full-resolution Camera Raw preview is limited to 64 megapixels; the proxy remains available".into());
self.error = Some("Full-resolution RAW Develop preview is limited to 64 megapixels; the proxy remains available".into());
self.failed_revision = Some(revision);
return;
}
@@ -124,7 +124,7 @@ impl DetailPreview {
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| develop(&source, raw_curve.as_deref().map(Vec::as_slice), area, &params, &coverage)))
.map(|surface| (revision, surface))
.map_err(|_| "Camera Raw detail preview failed; the proxy remains available".into());
.map_err(|_| "RAW Develop detail preview failed; the proxy remains available".into());
if !cancel.load(Ordering::Relaxed) {
let _ = tx.send(result);
ctx.request_repaint();
@@ -141,7 +141,7 @@ impl DetailPreview {
}) {
Ok(_) => self.pending = Some((revision, rx)),
Err(e) => {
self.error = Some(format!("Cannot start Camera Raw preview: {e}"));
self.error = Some(format!("Cannot start RAW Develop preview: {e}"));
self.failed_revision = Some(revision);
}
}
@@ -152,7 +152,7 @@ impl DetailPreview {
// instead of blocking its UI with the full-image engine pipeline.
drop(work);
drop(rx);
self.error = Some("Full-resolution filtered preview requires a native Camera Raw worker; the web preview keeps the proxy".into());
self.error = Some("Full-resolution filtered preview requires a native RAW Develop worker; the web preview keeps the proxy".into());
self.failed_revision = Some(revision);
}
}
+8 -8
View File
@@ -32,11 +32,11 @@ impl Pass {
return false;
}
if adapter.get_info().device_type == wgpu::DeviceType::Cpu {
log::info!("Camera Raw develops on the CPU: software graphics adapter");
log::info!("RAW Develop develops on the CPU: software graphics adapter");
return false;
}
if !CameraRawDevelop::supported(adapter) {
log::info!("Camera Raw develops on the CPU: the adapter can't render Rgba32Float");
log::info!("RAW Develop develops on the CPU: the adapter can't render Rgba32Float");
return false;
}
true
@@ -53,7 +53,7 @@ impl Pass {
let (on, out) = (device.clone(), slot.clone());
let spawned = std::thread::Builder::new().name("camera-raw-pipeline".into()).spawn(move || {
let pass = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Self::build_on(&on))).unwrap_or_else(|_| {
log::warn!("building the Camera Raw pipeline panicked; Camera Raw develops on the CPU");
log::warn!("building the RAW Develop pipeline panicked; RAW Develop develops on the CPU");
None
});
let _ = out.set(pass);
@@ -70,7 +70,7 @@ impl Pass {
match CameraRawDevelop::new(device) {
Ok(pass) => Some(Pass(Arc::new(Mutex::new(pass)))),
Err(e) => {
log::warn!("{e}; Camera Raw develops on the CPU");
log::warn!("{e}; RAW Develop develops on the CPU");
None
}
}
@@ -140,7 +140,7 @@ impl CameraRawGpu {
match pass.develop(&self.device, &self.queue, Some(&self.health), px, key, size, &stages) {
Ok(out) => Some(out),
Err(e) => {
log::warn!("{}; Camera Raw develops on the CPU", e.0);
log::warn!("{}; RAW Develop develops on the CPU", e.0);
self.failed.store(true, Ordering::Relaxed);
None
}
@@ -215,7 +215,7 @@ mod tests {
let _gpu = photocraft_testkit::gpu_lock();
let Some((mut app, ctx)) = gpu_app(8) else { return };
let canvas = app.gpu.clone().expect("GPU canvas");
assert!(!canvas.camera_raw_started(), "no Camera Raw pipeline at launch (#6419)");
assert!(!canvas.camera_raw_started(), "no RAW Develop pipeline at launch (#6419)");
crate::camera_raw_ui::open(&mut app, &ctx).unwrap();
assert!(canvas.camera_raw_started(), "built (or refused) from the first open");
assert_eq!(app.camera_raw.as_ref().map(|d| d.develop_backend), Some("cpu"), "the first frame doesn't wait for the pipeline");
@@ -233,7 +233,7 @@ mod tests {
force_pass(&app);
crate::camera_raw_ui::open(&mut app, &ctx).unwrap();
if app.camera_raw.as_ref().is_some_and(|d| d.gpu.is_none()) {
eprintln!("skipping: the device can't run the Camera Raw pass");
eprintln!("skipping: the device can't run the RAW Develop pass");
return;
}
let per_pixel = CameraRaw {
@@ -272,7 +272,7 @@ mod tests {
force_pass(&app);
crate::camera_raw_ui::open(&mut app, &ctx).unwrap();
if app.camera_raw.as_ref().is_some_and(|d| d.gpu.is_none()) {
eprintln!("skipping: the device can't run the Camera Raw pass");
eprintln!("skipping: the device can't run the RAW Develop pass");
return;
}
let (backend, _, _) = developed(&mut app, &ctx, CameraRaw { exposure: 0.5, ..Default::default() });
@@ -56,7 +56,7 @@ impl CameraRawPreviewState {
/// Validate with the rest of the Camera Raw request before changing anything.
pub(crate) fn prepare(current: CameraRawPreviewState, value: &Value) -> Result<CameraRawPreviewState, String> {
let obj = value.as_object().ok_or("Camera Raw view must be an object")?;
let obj = value.as_object().ok_or("RAW Develop view must be an object")?;
let mut next = current;
for (key, value) in obj {
match key.as_str() {
@@ -65,22 +65,22 @@ pub(crate) fn prepare(current: CameraRawPreviewState, value: &Value) -> Result<C
let z = value
.as_f64()
.filter(|z| z.is_finite() && (MIN_ZOOM as f64..=MAX_ZOOM as f64).contains(z))
.ok_or("Camera Raw zoom must be 'fit' or 0.0001–16 (1 = 100%)")?;
.ok_or("RAW Develop zoom must be 'fit' or 0.0001–16 (1 = 100%)")?;
next.zoom = Some(z as f32);
}
"center" => {
let a = value.as_array().filter(|a| a.len() == 2).ok_or("Camera Raw center must be [u,v]")?;
let a = value.as_array().filter(|a| a.len() == 2).ok_or("RAW Develop center must be [u,v]")?;
let coordinate = |i| {
a.get(i)
.and_then(Value::as_f64)
.filter(|v| v.is_finite() && (0.0..=1.0).contains(v))
.map(|v| v as f32)
.ok_or("Camera Raw center must be finite coordinates in 0–1")
.ok_or("RAW Develop center must be finite coordinates in 0–1")
};
next.center = [coordinate(0)?, coordinate(1)?];
}
"hand" => next.hand = value.as_bool().ok_or("Camera Raw hand must be a boolean")?,
_ => return Err(format!("unknown Camera Raw view property {key}")),
"hand" => next.hand = value.as_bool().ok_or("RAW Develop hand must be a boolean")?,
_ => return Err(format!("unknown RAW Develop view property {key}")),
}
}
if obj.get("zoom").and_then(Value::as_str) == Some("fit") {
+2 -2
View File
@@ -247,7 +247,7 @@ impl CameraRawDialog {
let (tx, rx) = std::sync::mpsc::channel::<Result<ProxyFrame, String>>();
let repaint = ctx.clone();
let spawned = std::thread::Builder::new().name("camera-raw-proxy".into()).spawn(move || {
let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())).map_err(|_| "Camera Raw preview failed".to_string());
let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())).map_err(|_| "RAW Develop preview failed".to_string());
// The dialog may have closed or rendered on its own meanwhile; then nobody listens.
if tx.send(frame).is_ok() {
repaint.request_repaint();
@@ -273,7 +273,7 @@ impl CameraRawDialog {
let frame = match rx.try_recv() {
Ok(frame) => frame,
Err(std::sync::mpsc::TryRecvError::Empty) => return Ok(()),
Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("Camera Raw preview worker stopped".to_string()),
Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("RAW Develop preview worker stopped".to_string()),
};
self.pending = None;
self.publish(ctx, frame?);
@@ -49,7 +49,7 @@ fn history_keys(d: &mut CameraRawDialog, ctx: &egui::Context) {
}
pub(super) fn commit(app: &mut PhotocraftApp) -> Result<Value, String> {
let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?;
let d = app.camera_raw.as_ref().ok_or(tl!("RAW Develop isn't open"))?;
let result = match d.target {
Target::NewFilter => {
let mut p = d.command_params();
@@ -225,12 +225,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
impl CameraRawDialog {
/// "Camera Raw (name)" for the open-time dialog, "Camera Raw Filter (layer)" otherwise.
/// "RAW Develop (name)" for the open-time dialog, "RAW Develop Filter (layer)" otherwise.
fn window_title(&self) -> String {
if self.target == Target::OpenRaw {
crate::i18n::fmt(tl!("Camera Raw ({name})"), &[("name", &self.layer_name)])
crate::i18n::fmt(tl!("RAW Develop ({name})"), &[("name", &self.layer_name)])
} else {
crate::i18n::fmt(tl!("Camera Raw Filter ({layer})"), &[("layer", &self.layer_name)])
crate::i18n::fmt(tl!("RAW Develop Filter ({layer})"), &[("layer", &self.layer_name)])
}
}
}
@@ -56,11 +56,11 @@ pub(super) fn preview_area(canvas: Rect, surf: &photocraft_raster::Surface) -> R
let width = area.x1.checked_sub(area.x0).filter(|n| (1..=1_048_576).contains(n));
let height = area.y1.checked_sub(area.y0).filter(|n| (1..=1_048_576).contains(n));
let (Some(w), Some(h)) = (width, height) else {
return Err("Camera Raw preview bounds are too large".into());
return Err("RAW Develop preview bounds are too large".into());
};
let (w, h) = (w as usize, h as usize);
if w.checked_mul(h).is_none_or(|pixels| pixels > 512_000_000) {
return Err("Camera Raw preview bounds are too large".into());
return Err("RAW Develop preview bounds are too large".into());
}
Ok((area, w, h))
}
@@ -213,7 +213,7 @@ pub(super) fn done(app: &mut PhotocraftApp) -> Value {
return json!({"done": false, "saved": saved});
}
app.ui.status = if !saved.is_empty() {
crate::i18n::fmt(tl!("Saved Camera Raw settings to {file}"), &[("file", &saved.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "))])
crate::i18n::fmt(tl!("Saved RAW Develop settings to {file}"), &[("file", &saved.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "))])
} else if stored.iter().all(|s| *s == Stored::Defaults) {
tl!("Nothing to save: these raws are at their default settings").to_string()
} else {
@@ -104,7 +104,7 @@ fn completion_identity_applies_remaining_settings_after_tab_reordering() {
let state = app.session.active().unwrap();
assert_eq!(state.doc.id, replacement);
assert!(!state.is_dirty(), "development finishes opening only the replacement");
assert!(state.history.past_len() > 0, "remaining Camera Raw settings were applied");
assert!(state.history.past_len() > 0, "remaining RAW Develop settings were applied");
assert!(!app.view_docs.contains(&raw.document));
assert!(app.view_docs.contains(&replacement));
}
@@ -9,7 +9,7 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val
return None;
}
let Some(fields) = params.as_object() else {
return Some(Err("Camera Raw params must be an object".into()));
return Some(Err("RAW Develop params must be an object".into()));
};
if fields.is_empty() {
return Some(
@@ -30,26 +30,26 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val
}
let ui = params.get("ui")?;
let Some(fields) = ui.as_object() else {
return Some(Err("Camera Raw ui must be an object".into()));
return Some(Err("RAW Develop ui must be an object".into()));
};
for (key, value) in fields {
match key.as_str() {
"set" | "scope" | "view" | "demosaic" => {}
"before" | "commit" | "cancel" | "done" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" if value.is_boolean() => {}
"before" | "commit" | "cancel" | "done" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" => {
return Some(Err(format!("Camera Raw {key} must be a boolean")));
return Some(Err(format!("RAW Develop {key} must be a boolean")));
}
_ => return Some(Err(format!("unknown Camera Raw ui property {key}"))),
_ => return Some(Err(format!("unknown RAW Develop ui property {key}"))),
}
}
let ends = ["commit", "cancel", "done"].into_iter().filter(|k| ui.get(*k).and_then(Value::as_bool) == Some(true)).count();
if ends > 1 {
return Some(Err("Camera Raw takes one of commit, cancel and done".into()));
return Some(Err("RAW Develop takes one of commit, cancel and done".into()));
}
for (key, run) in [("saveSettings", save_settings as fn(&mut PhotocraftApp) -> Result<Value, String>), ("loadSettings", load_settings)] {
if ui.get(key).and_then(Value::as_bool) == Some(true) {
if fields.len() > 1 {
return Some(Err(format!("Camera Raw {key} must be sent on its own")));
return Some(Err(format!("RAW Develop {key} must be sent on its own")));
}
return Some(run(app));
}
@@ -83,23 +83,23 @@ fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Opti
}
if let Some(set) = ui.get("set") {
if !set.is_object() {
return Some(Err("bad Camera Raw settings: expected an object".into()));
return Some(Err("bad RAW Develop settings: expected an object".into()));
}
let mut cur = serde_json::to_value(&d.params).unwrap_or(json!({}));
if let (Value::Object(c), Value::Object(s)) = (&mut cur, set) {
for (k, v) in s {
if !c.contains_key(k) {
return Some(Err(format!("unknown Camera Raw setting {k}")));
return Some(Err(format!("unknown RAW Develop setting {k}")));
}
c.insert(k.clone(), v.clone());
}
}
next_params = match serde_json::from_value::<CameraRaw>(cur) {
Ok(p) => p,
Err(e) => return Some(Err(format!("bad Camera Raw settings: {e}"))),
Err(e) => return Some(Err(format!("bad RAW Develop settings: {e}"))),
};
if let Err(e) = next_params.validate_changes(&d.original) {
return Some(Err(format!("bad Camera Raw settings: {e}")));
return Some(Err(format!("bad RAW Develop settings: {e}")));
}
}
let scope_update = match ui.get("scope") {
@@ -534,7 +534,7 @@ pub(super) enum Coverage {
pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
if photocraft_engine::color_channels::selected(&app.session).is_some_and(|c| c.len() > 1) {
return Err("Camera Raw requires the composite or one colour channel".into());
return Err("RAW Develop requires the composite or one colour channel".into());
}
photocraft_engine::commands::find("filter.cameraRaw").map(|c| (c.enabled)(&app.session)).unwrap_or(Err("unknown command".into()))?;
let (layer, surf, _) = crate::distort_ui::active_pixels(app)?;
@@ -552,7 +552,7 @@ pub fn open_smart_filter(app: &mut PhotocraftApp, ctx: &egui::Context, layer: La
};
let filter = sm.smart_filters.get(index).ok_or("no such smart filter")?;
if filter.command != RAW {
return Err("the smart filter is not a Camera Raw filter".into());
return Err("the smart filter is not a RAW Develop filter".into());
}
let params = raw_params(RAW, &filter.params).map_err(|e| e.to_string())?;
let surf = photocraft_engine::smart_cmds::render_below_filter(&st.doc, sm, index)
@@ -130,9 +130,9 @@ fn existing_sidecar_is_ours(_: &str) -> Option<bool> {
/// Save Settings…: the dialog's settings as a Camera Raw `.xmp` settings file.
pub(super) fn save_settings(app: &mut PhotocraftApp) -> Result<Value, String> {
let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?;
let d = app.camera_raw.as_ref().ok_or(tl!("RAW Develop isn't open"))?;
let bytes = photocraft_io::camera_raw_xmp::save(&d.params).into_bytes();
app.pick_save("Camera Raw Settings.xmp", move |app, path| {
app.pick_save("RAW Develop Settings.xmp", move |app, path| {
let write = app.services.write.as_mut().ok_or("no writer configured")?;
write(&path, &bytes)?;
Ok(json!({"path": path}))
@@ -142,10 +142,10 @@ pub(super) fn save_settings(app: &mut PhotocraftApp) -> Result<Value, String> {
/// Load Settings…: applies a Camera Raw `.xmp` settings file's supported settings over the
/// dialog's; the status bar names how many were not supported.
pub(super) fn load_settings(app: &mut PhotocraftApp) -> Result<Value, String> {
app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?;
app.camera_raw.as_ref().ok_or(tl!("RAW Develop isn't open"))?;
app.pick_file_bytes_filtered(&["xmp"], |app, name, bytes| {
let file = crate::file_open::display_name(&name);
let d = app.camera_raw.as_mut().ok_or(tl!("Camera Raw isn't open"))?;
let d = app.camera_raw.as_mut().ok_or(tl!("RAW Develop isn't open"))?;
let mut next = d.params.clone();
let mut report = photocraft_io::camera_raw_xmp::load(&mut next, &bytes).map_err(|e| format!("{file}: {e}"))?;
// A crop only applies as a raw file opens; the filter has none, so it is not supported.
@@ -164,9 +164,9 @@ pub(super) fn load_settings(app: &mut PhotocraftApp) -> Result<Value, String> {
}
app.ui.status_error = false;
app.ui.status = if report.ignored.is_empty() {
crate::i18n::fmt(tl!("Loaded Camera Raw settings from {file}"), &[("file", &file)])
crate::i18n::fmt(tl!("Loaded RAW Develop settings from {file}"), &[("file", &file)])
} else {
let template = "Loaded Camera Raw settings from {file} ({n} not supported)";
let template = "Loaded RAW Develop settings from {file} ({n} not supported)";
crate::i18n::fmt(tl!(template), &[("file", &file), ("n", &report.ignored.len().to_string())])
};
Ok(json!({"applied": report.applied, "ignored": report.ignored}))
@@ -111,7 +111,7 @@ fn finish_worker(d: &mut CameraRawDialog, ctx: &egui::Context) {
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
panic!("the Camera Raw preview worker never finished");
panic!("the RAW Develop preview worker never finished");
}
/// The dialog's controls develop the proxy on a worker (#5964): the frame it shows is the one
@@ -200,7 +200,7 @@ fn a_worker_failure_is_reported_until_the_next_frame() {
};
let fail = |app: &mut PhotocraftApp| {
let (tx, rx) = std::sync::mpsc::channel();
tx.send(Err("Camera Raw preview failed".to_string())).unwrap();
tx.send(Err("RAW Develop preview failed".to_string())).unwrap();
let d = app.camera_raw.as_mut().unwrap();
d.pending = Some(rx);
d.dirty = false;
@@ -213,7 +213,7 @@ fn a_worker_failure_is_reported_until_the_next_frame() {
frame(&mut app);
fail(&mut app);
frame(&mut app);
assert!(app.ui.status_error && app.ui.status == "Camera Raw preview failed", "{}", app.ui.status);
assert!(app.ui.status_error && app.ui.status == "RAW Develop preview failed", "{}", app.ui.status);
// No new frame yet: the error stays.
frame(&mut app);
assert!(app.ui.status_error);
@@ -372,7 +372,7 @@ fn raw_opens_in_camera_raw_and_open_redevelops() {
menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "temperature": 30, "contrast": 20}}})).unwrap().unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!(r["redeveloped"], true, "{r}");
assert!(r.get("filter").is_some(), "contrast is applied as a Camera Raw step: {r}");
assert!(r.get("filter").is_some(), "contrast is applied as a RAW Develop step: {r}");
assert!(app.camera_raw.is_none());
assert_eq!(app.session.documents().len(), 1);
let st = app.session.active().unwrap();
@@ -729,7 +729,7 @@ fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() {
open_raw(&mut app, &ctx, raw).unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!((r["document"].as_u64(), r["redeveloped"].as_bool(), r.get("filter")), (Some(0), Some(false), None), "{r}");
assert_eq!(r.get("defaults"), None, "ProPhoto, 16-bit: no Camera Raw Default to apply: {r}");
assert_eq!(r.get("defaults"), None, "ProPhoto, 16-bit: no RAW Develop Default to apply: {r}");
// Preference off: raws open straight away.
app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap();
app.open_bytes("c.dng", &dng).unwrap();
@@ -892,7 +892,7 @@ fn camera_raw_defaults_apply_when_a_raw_opens() {
open_raw(&mut app, &ctx, raw).unwrap();
let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
assert_eq!(r["defaults"], json!(["sharpenFor", "colorSpace"]), "{r}");
assert!(r.get("filter").is_some(), "Sharpen For is a Camera Raw step: {r}");
assert!(r.get("filter").is_some(), "Sharpen For is a RAW Develop step: {r}");
let st = app.session.active().unwrap();
assert_eq!(st.doc.depth, photocraft_color::SampleType::U16);
assert_eq!(st.saved_revision, st.revision);
+15 -2
View File
@@ -13,8 +13,8 @@ fn hindi_has_the_reveal_and_camera_raw_rows() {
let hi = lang("hi");
assert_eq!(tr(hi, "Reveal in Explorer"), "Explorer में दिखाएँ");
assert_eq!(tr(hi, "Reveal in Finder"), "Finder में दिखाएँ");
assert_eq!(tr(hi, "Camera Raw…"), "Camera Raw…");
assert!(has(hi, "Camera Raw…"), "Camera Raw… is a catalog row, not a fallback");
assert_eq!(tr(hi, "RAW Defaults…"), "RAW डिफ़ॉल्ट…");
assert!(has(hi, "RAW Defaults…"), "RAW Defaults… is a catalog row, not a fallback");
}
#[test]
@@ -510,3 +510,16 @@ fn bundled_catalogs_are_consistent() {
}
}
}
#[test]
fn raw_develop_labels_are_translated_in_every_shipped_catalog() {
if !needs_catalogs() {
return;
}
for language in LANGUAGES.iter().skip(1) {
let l = lang(language.code);
for source in ["RAW Develop", "RAW Develop Filter", "RAW Develop Filter…", "RAW Defaults", "RAW Defaults…"] {
assert!(has(l, source) && !tr(l, source).is_empty(), "{}: {source}", language.code);
}
}
}
+4 -2
View File
@@ -263,8 +263,8 @@ pub use services::{
AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn,
CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn,
ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox,
LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, RightButtonDownFn,
SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable,
RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
};
pub use text::bidi_text;
pub use text::cjk_fonts;
@@ -1034,6 +1034,8 @@ mod pen_path_ownership_tests;
#[cfg(test)]
mod artboard_options_bar_tests;
#[cfg(test)]
mod background_eraser_bar_angle_tests;
#[cfg(test)]
mod brush_opacity_minimum_tests;
#[cfg(test)]
mod doc_tab_menu_tests;
+3 -2
View File
@@ -119,14 +119,15 @@ fn background_eraser_draws_live_and_commits_what_it_showed() {
fn a_refused_background_eraser_stroke_shows_nothing_and_reports_on_release() {
let mut app = app(8, Tool::BackgroundEraser);
app.run("layer.new.layer", json!({})).unwrap();
app.run("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
// Lock image pixels refuses (Lock transparent pixels does not, #11905).
app.run("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();
let steps = app.session.active().unwrap().history.past_len();
let m = Modifiers::NONE;
tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m);
tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 20.0, pressure: 1.0 }, m);
assert!(app.live_stroke.is_none(), "the engine refuses the stroke, so nothing is drawn live");
tool_event(&mut app, ToolEvent::Up { x: 40.0, y: 20.0 }, m);
assert!(app.ui.status_error && app.ui.status.contains("transparency"), "{}", app.ui.status);
assert!(app.ui.status_error && app.ui.status.contains("is locked"), "{}", app.ui.status);
assert_eq!(app.session.active().unwrap().history.past_len(), steps);
}
+3 -2
View File
@@ -168,7 +168,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Edit", "Preferences"], "Type…", None, "edit.preferences.type"),
(&["Edit", "Preferences"], "Enhanced Controls…", None, "edit.preferences.enhancedControls"),
(&["Edit", "Preferences"], "---", None, "---"),
(&["Edit", "Preferences"], "Camera Raw…", None, "edit.preferences.rawDefaults"),
(&["Edit", "Preferences"], "RAW Defaults…", None, "edit.preferences.rawDefaults"),
(&["Image", "Mode"], "Bitmap", None, "image.mode.bitmap"),
(&["Image", "Mode"], "Grayscale", None, "image.mode.grayscale"),
(&["Image", "Mode"], "Duotone", None, "image.mode.duotone"),
@@ -259,6 +259,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Layer", "New"], "---", None, "---"),
(&["Layer", "New"], "Layer Via Copy", Some("Cmd+J"), "layer.new.layerViaCopy"),
(&["Layer", "New"], "Layer Via Cut", Some("Cmd+Shift+J"), "layer.new.layerViaCut"),
(&["Layer"], "Copy CSS", None, "layer.copyCSS"),
(&["Layer"], "Duplicate Layer…", None, "layer.duplicate"),
(&["Layer", "Delete"], "Layer", None, "layer.delete"),
(&["Layer", "Delete"], "Hidden Layers", None, "layer.delete.hiddenLayers"),
@@ -570,7 +571,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
(&["Filter"], "Convert for Smart Filters", None, "filter.convertForSmartFilters"),
(&["Filter"], "---", None, "---"),
(&["Filter"], "Filter Gallery…", None, "filter.filterGallery"),
(&["Filter"], "Camera Raw Filter…", Some("Cmd+Shift+A"), "filter.cameraRaw"),
(&["Filter"], "RAW Develop Filter…", Some("Cmd+Shift+A"), "filter.cameraRaw"),
(&["Filter"], "Adaptive Wide Angle…", Some("Cmd+Alt+Shift+A"), "filter.adaptiveWideAngle"),
(&["Filter"], "Lens Correction…", Some("Cmd+Shift+R"), "filter.lensCorrection"),
(&["Filter"], "Liquify…", Some("Cmd+Shift+X"), "filter.liquify"),
+8
View File
@@ -86,6 +86,14 @@ fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str,
if id == "help.checkForUpdates" {
return Some(crate::updates_ui::check(app, ctx, params.clone()));
}
// Layer › Copy CSS: the engine writes the CSS, the clipboard is the shell's (#9372).
if id == photocraft_engine::layer_css_cmds::ID {
return Some(app.run(id, params.clone()).inspect(|r| {
if let Some(css) = r.get("css").and_then(Value::as_str) {
ctx.copy_text(css.to_string());
}
}));
}
if id == "ui.symmetryTransform" {
return Some(crate::symmetry_ui::begin(app).map(|_| Value::Null));
}
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::menu_catalog::CATALOG;
use crate::menus::is_live;
/// Minimum number of live catalog items. Raise it when parity grows; never lower it.
pub const FLOOR: usize = 661;
pub const FLOOR: usize = 663;
/// One top-level menu's coverage.
#[derive(Clone, Debug, serde::Serialize)]
+25
View File
@@ -556,3 +556,28 @@ fn proof_setup_presets_and_checkmarks() {
let params = crate::filter_dialog::parse_spec(spec.params);
assert!(matches!(&params[0].kind, crate::filter_dialog::Kind::Choice { options, .. } if options[0] == "srgb" && !options.iter().any(|v| v.contains('/'))));
}
/// Layer › Copy CSS puts the layer's CSS on the clipboard, as Photoshop's does (#9372).
#[test]
fn copy_css_puts_the_layers_css_on_the_clipboard() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.session.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
app.session.execute("layer.new.layer", json!({"name": "Box"})).unwrap();
app.session
.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(100, 80, 300, 220), &[0.2, 0.4, 0.8, 1.0]);
Ok(())
})
.unwrap();
app.sync_views();
assert!(crate::menus::menu_items(&app).iter().any(|i| i.id == "layer.copyCSS" && i.path == ["Layer"]), "Layer › Copy CSS");
let ctx = egui::Context::default();
let mut result = None;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
result = Some(invoke(&mut app, ui.ctx(), "layer.copyCSS", json!({})));
});
out.textures_delta.clear();
let css = result.unwrap().unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".Box {\n background-image: url(\"Box.png\");\n"), "{css}");
assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText(css)]);
}
@@ -1,4 +1,4 @@
//! #11398: Edit › Preferences says "Plugins…" and "Camera Raw…" and has the reference
//! #11398: Edit › Preferences says "Plugins…" and "RAW Defaults…" and has the reference
//! application's two separators (after the first entry and before Camera Raw…).
use crate::menu_catalog::CATALOG;
@@ -33,7 +33,7 @@ fn preferences_submenu_reads_in_the_reference_order_with_two_separators() {
"Type…",
"Enhanced Controls…",
"---",
"Camera Raw…",
"RAW Defaults…",
]
);
}
@@ -76,12 +76,12 @@ fn engine_labels_match_the_catalogue_for_the_renamed_rows() {
assert_eq!(engine, catalogue, "{id}");
}
assert_eq!(photocraft_engine::commands::find("edit.preferences.plugIns").unwrap().label, "Plugins…");
assert_eq!(photocraft_engine::commands::find("edit.preferences.rawDefaults").unwrap().label, "Camera Raw…");
assert_eq!(photocraft_engine::commands::find("edit.preferences.rawDefaults").unwrap().label, "RAW Defaults…");
}
#[test]
fn preferences_dialog_page_names_follow_the_menu() {
let title = |key: &str| photocraft_engine::prefs::SECTIONS.iter().find(|(k, _)| *k == key).map(|(_, t)| *t);
assert_eq!(title("plugIns"), Some("Plugins"));
assert_eq!(title("rawDefaults"), Some("Camera Raw Defaults"));
assert_eq!(title("rawDefaults"), Some("RAW Defaults"));
}
+7
View File
@@ -429,6 +429,10 @@ pub type PenEndFn = Box<dyn Fn() -> Option<bool> + Send + Sync>;
/// whether the app window is focused (to re-assert WinTab overlap priority on activation).
pub type TabletPollFn = Box<dyn FnMut(bool)>;
/// What the last self-update came to: `Ok` with the version it installed, `Err` with the reason it
/// could not be installed, `None` when there is nothing to report ([`Services::last_update`]).
pub type LastUpdateFn = fn() -> Option<Result<String, String>>;
/// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of
/// I/O dependencies.
#[derive(Default)]
@@ -486,6 +490,9 @@ pub struct Services {
pub alert: Option<fn()>,
/// Starts a background check for published releases (desktop, outside Flatpak).
pub check_updates: Option<photocraft_engine::updates_cmds::CheckFn>,
/// What the last self-update came to, read once at the first frame: `Ok` with the version it
/// installed, `Err` with the reason it could not be installed (desktop).
pub last_update: Option<LastUpdateFn>,
/// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as
/// documents.
pub inbox: Option<Inbox>,
@@ -137,7 +137,7 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() {
h.state_mut().run("layer.select", json!({"layer": a})).unwrap();
h.state_mut().run("filter.cameraRaw", json!({"exposure": 1.0, "contrast": 20})).unwrap();
h.run_steps(4);
let (from, to) = (at(&h, "Camera Raw Filter"), at(&h, "Smart B"));
let (from, to) = (at(&h, "RAW Develop Filter"), at(&h, "Smart B"));
drag(&mut h, from, to, Modifiers::ALT);
let raw = |h: &egui_kittest::Harness<'static, PhotocraftApp>, id: u64| match &h.state().session.active().unwrap().doc.layer(LayerId(id)).unwrap().content {
LayerContent::Smart(sm) => sm.smart_filters.iter().find(|f| f.command == "filter.cameraRaw").map(|f| f.params.clone()),
@@ -147,7 +147,7 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() {
assert_eq!(raw(&h, b).unwrap()["exposure"], 1.0);
// B is above A in the panel, so its copy is the upper of the two Camera Raw rows.
let copy = h
.query_all_by_label("Camera Raw Filter")
.query_all_by_label("RAW Develop Filter")
.filter(|n| n.accesskit_node().role() == Role::Button)
.map(|n| n.rect().center())
.min_by(|p, q| p.y.total_cmp(&q.y))
@@ -160,7 +160,7 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() {
h.run_steps(1);
}
h.run_steps(3);
let dialog = h.state().camera_raw.as_ref().expect("Camera Raw opened");
let dialog = h.state().camera_raw.as_ref().expect("RAW Develop opened");
assert_eq!(dialog.layer, LayerId(b));
}
+8 -2
View File
@@ -74,7 +74,9 @@ pub struct ToolOptions {
pub cam_mode: String,
pub cam_structure: f32,
pub cam_color: f32,
/// Content-Aware Move: Transform On Drop (a transform box on the dropped patch).
/// Content-Aware Move: Transform On Drop (a transform box on the dropped patch). On by
/// default (#12185); a saved `false` stays off.
#[serde(default = "yes")]
pub cam_transform_on_drop: bool,
/// Dodge/Burn: shadows | midtones | highlights, exposure %, protect tones.
pub tone_range: String,
@@ -469,7 +471,7 @@ impl Default for ToolOptions {
cam_mode: "move".into(),
cam_structure: 4.0,
cam_color: 0.0,
cam_transform_on_drop: false,
cam_transform_on_drop: true,
tone_range: "midtones".into(),
exposure: 50.0,
protect_tones: true,
@@ -560,3 +562,7 @@ impl Default for ToolOptions {
}
}
}
#[cfg(test)]
#[path = "../cam_transform_on_drop_default_tests.rs"]
mod cam_transform_on_drop_default_tests;
+59 -2
View File
@@ -90,6 +90,49 @@ fn opt(ui: &mut egui::Ui, text: &str) {
crate::widgets::scrub_option_label(ui, &label);
}
/// The reference application's alert for a Background Eraser Angle typed outside −180…180.
pub(crate) const ANGLE_RANGE_MESSAGE: &str = "An integer between -180 ° and 180 ° is required. Closest value inserted.";
/// The Background Eraser's Angle: an angle icon and a whole-degree field on the brush tip's
/// angle, −180…180, default 0. Returns true when a typed value was out of range and was clamped
/// (400 → 180): the caller shows [`ANGLE_RANGE_MESSAGE`] once the entry is committed.
fn angle_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) -> bool {
let t = Tokens::get(ui.ctx());
let tip = tl!("Set the brush angle");
ui.add(icons::image("rotate-cw", 15.0, t.text_dim)).on_hover_text(tip);
// A wider range than the angle's, so a typed 400 reaches us and can be told apart from 180.
let mut a = b.angle;
// Read before the field: it consumes the arrow keys it steps with, and the wheel it steps
// with while focused never shows in the scroll delta (a view's scroll does, and is no step).
let arrow_or_wheel =
ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowDown)) || crate::field_wheel::focused_field_wheeled(ui.ctx());
let r = widgets::value_field_named(ui, tl!("Angle"), &mut a, -ANGLE_TYPED_MAX..=ANGLE_TYPED_MAX, "°", 52.0);
let out_of_range = r.id.with("bg-eraser-angle-out-of-range");
// The flag lives only while an entry is being typed: drawn without the keyboard, the field
// drops it, so an entry the tool switch cut off (never committed) can't alert on a later one.
// The widget's own focus, not `has_focus()`: that is false while the window is in the
// background, and switching away mid-entry must keep the alert for the commit.
if !ui.memory(|m| m.has_focus(r.id)) && !r.lost_focus() {
ui.data_mut(|d| d.remove_temp::<bool>(out_of_range));
}
if r.changed() && a.is_finite() {
let whole = a.trunc();
let clamped = whole.clamp(-180.0, 180.0);
b.angle = clamped;
// Only typing alerts: a scrub or an arrow-key step past the end just stops there.
let stepped = r.dragged() || arrow_or_wheel;
// A wheel step over the field without its focus is no entry either.
let typed_out = whole != clamped && !stepped && (r.has_focus() || r.lost_focus());
ui.data_mut(|d| d.insert_temp(out_of_range, typed_out));
}
let r = r.on_hover_text(tip);
// Enter (or a click away) commits the entry: the alert comes then, not mid-typing.
r.lost_focus() && ui.data_mut(|d| d.remove_temp::<bool>(out_of_range)).unwrap_or(false)
}
/// How far the Angle field lets a typed number through before [`angle_field`] clamps it.
const ANGLE_TYPED_MAX: f32 = 1.0e6;
/// Options bar for the Magic Eraser and Background Eraser. Returns false for other tools.
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
let o = &mut app.ui.tool_options;
@@ -133,8 +176,22 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
if tolerance_field(ui, &mut o.bg_tolerance) {
open_range_alert(app);
}
let o = &mut app.ui.tool_options;
widgets::checkbox(ui, &mut o.bg_protect_fg, tl!("Protect Foreground Color")).on_hover_text(tl!("Do not erase the foreground swatch color"));
// Angle and Pressure for Size edit the tool's own brush (the shell swaps one in per
// tool), through `tools.setBrush` like the Brush Settings panel.
let before = app.session.tools.brush.clone();
let mut brush = before.clone();
if angle_field(ui, &mut brush) {
let message = tl!(ANGLE_RANGE_MESSAGE).to_string();
app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default());
}
widgets::checkbox(ui, &mut app.ui.tool_options.bg_protect_fg, tl!("Protect Foreground Color"))
.on_hover_text(tl!("Do not erase the foreground swatch color"));
let name = tl!("Always use pressure for size");
let pressure = icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), brush.pressure_size, name, false);
if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() {
brush.pressure_size = !brush.pressure_size;
}
crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush);
}
_ => return false,
}
+130 -31
View File
@@ -615,6 +615,128 @@ fn pct(ui: &mut egui::Ui, label: &str, v: &mut f32) {
crate::widgets::value_field(ui, v, 1.0..=100.0, "%", 58.0);
}
const STRUCTURE_RANGE_ALERT: &str = "An integer between 1 and 7 is required. Closest value inserted.";
const COLOR_RANGE_ALERT: &str = "An integer between 0 and 10 is required. Closest value inserted.";
const STRUCTURE_TIP: &str = "Adjust how strictly the source structure is preserved";
const COLOR_TIP: &str = "Adjust how much the source color can be modified";
/// Structure or Color on the Content-Aware Move bar (#12193): a whole-number field and a slider
/// popup. A typed value outside `lo..=hi` becomes the closest value; returns true once the field
/// is left, so the caller opens the alert. A scrub stops at the end without an alert.
fn cam_integer_popup(ui: &mut egui::Ui, id: &str, name: &str, value: &mut f32, lo: f32, hi: f32, tip: &str) -> bool {
*value = if value.is_finite() { value.round().clamp(lo, hi) } else { lo };
let draft_id = ui.make_persistent_id(egui::IdSalt::new(id)).with("typed");
let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(draft_id));
let mut typed = draft.filter(|(_, stored)| *stored == *value).map_or(*value, |(typed, _)| typed);
// Wide range so a typed 99 reaches here unclamped. The caption just before this names the field.
let r = crate::widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "", 40.0).on_hover_text(tl!(tip));
let out_id = r.id.with("out-of-range");
if r.gained_focus() {
ui.ctx().data_mut(|d| d.remove_temp::<bool>(out_id));
}
if r.changed() && typed.is_finite() {
*value = typed.round().clamp(lo, hi);
let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none();
let out = typing && !(lo..=hi).contains(&typed);
ui.ctx().data_mut(|d| d.insert_temp(out_id, out));
if typing && r.has_focus() {
ui.ctx().data_mut(|d| d.insert_temp(draft_id, (typed, *value)));
} else {
ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(draft_id));
}
}
if !r.has_focus() {
ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(draft_id));
}
cam_amount_slider(ui, name, value, lo, hi, tip);
r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::<bool>(out_id)).unwrap_or(false)
}
/// The ▾ beside a Content-Aware Move amount: its pop-up slider snaps to whole numbers in `lo..=hi`.
fn cam_amount_slider(ui: &mut egui::Ui, name: &str, value: &mut f32, lo: f32, hi: f32, tip: &str) {
let (rect, resp) = ui.allocate_exact_size(vec2(14.0, 22.0), egui::Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), name));
let resp = resp.on_hover_text(tl!(tip));
let popup = egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
let open = popup.is_open();
if resp.hovered() || open {
let t = Tokens::get(ui.ctx());
ui.painter().rect_filled(rect, t.radius_sm, t.field_border.gamma_multiply(0.6));
}
crate::widgets::chevron_icon(ui, rect, ui.style().interact(&resp), open);
let parent_layer = resp.layer_id;
popup.show(|ui| {
crate::press_menu::above_parent_ui(parent_layer, ui);
ui.set_min_width(160.0);
let mut v = *value;
let s = crate::widgets::slider(ui, &mut v, lo..=hi, None);
if v.is_finite() {
let snapped = v.round().clamp(lo, hi);
if snapped != *value {
*value = snapped;
}
}
s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), name));
});
}
fn open_cam_range_alert(app: &mut PhotocraftApp, message: &str) {
let message = tl!(message).to_owned();
let shown =
app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(message.as_str()));
if !shown {
app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default());
}
}
/// Content-Aware Move's options (#12193). While the Transform On Drop box is up, the controls are
/// greyed and Cancel then Commit sit at the right end.
fn content_aware_move_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let live = crate::cam_transform::active(app);
ui.add_enabled_ui(!live, |ui| {
crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui);
crate::widgets::vline(ui, 22.0);
opt(ui, tl!("Mode:"));
let modes = [("move".to_string(), tl!("Move")), ("extend".to_string(), tl!("Extend"))];
crate::widgets::dropdown(ui, "cam-mode", tl!("Mode"), &mut app.ui.tool_options.cam_mode, &modes, 90.0);
if let Some(mode) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("cam-mode"))) {
mode.on_hover_text(tl!("Choose a remix mode"));
}
opt(ui, tl!("Structure:"));
if cam_integer_popup(ui, "cam-structure", "Structure", &mut app.ui.tool_options.cam_structure, 1.0, 7.0, STRUCTURE_TIP) {
open_cam_range_alert(app, STRUCTURE_RANGE_ALERT);
}
opt(ui, tl!("Color:"));
if cam_integer_popup(ui, "cam-color", "Color", &mut app.ui.tool_options.cam_color, 0.0, 10.0, COLOR_TIP) {
open_cam_range_alert(app, COLOR_RANGE_ALERT);
}
crate::widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.content_aware_move, tl!("Sample All Layers"))
.on_hover_text(tl!("Enable to remix all layers"));
crate::widgets::checkbox(ui, &mut app.ui.tool_options.cam_transform_on_drop, tl!("Transform On Drop"))
.on_hover_text(tl!("Allows rotation and scaling of selection"));
});
crate::widgets::vline(ui, 22.0);
if live {
// right_to_left places the first widget at the right, so Commit is the rightmost and
// Cancel sits just to its left.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let tip = crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]);
let commit = crate::icons::button(ui, "check", 26.0, false, &tip);
commit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Commit transform"));
if commit.clicked() {
crate::cam_transform::commit(app);
}
let cancel = crate::icons::button(ui, "ban", 26.0, false, tl!("Cancel transform (Esc)"));
cancel.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Cancel transform"));
if cancel.clicked() {
crate::cam_transform::cancel(app);
}
});
} else {
opt(ui, tl!("Lasso around an area, then drag the selection"));
}
}
/// Options bar for the retouching and smart-selection tools. Returns false for other tools.
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye)
@@ -622,6 +744,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
{
return false;
}
if tool == Tool::ContentAwareMove {
content_aware_move_bar(app, ui);
return true;
}
let composite = crate::canvas::paint_target(app).as_str() == Some("pixels");
let o = &mut app.ui.tool_options;
match tool {
@@ -682,37 +808,6 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
crate::widgets::vline(ui, 22.0);
opt(ui, tl!("Lasso around an area, then drag the selection"));
}
Tool::ContentAwareMove => {
// The lasso's selection mode leads, as on the Patch tool's bar (#11024).
crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui);
crate::widgets::vline(ui, 22.0);
opt(ui, tl!("Mode:"));
let modes = [("move".to_string(), tl!("Move")), ("extend".to_string(), tl!("Extend"))];
crate::widgets::dropdown(ui, "cam-mode", tl!("Mode"), &mut o.cam_mode, &modes, 90.0);
opt(ui, tl!("Structure:"));
crate::widgets::value_field(ui, &mut o.cam_structure, 1.0..=7.0, "", 40.0);
opt(ui, tl!("Color:"));
crate::widgets::value_field(ui, &mut o.cam_color, 0.0..=10.0, "", 40.0);
crate::widgets::checkbox(ui, &mut o.sample_all.content_aware_move, tl!("Sample All Layers"));
crate::widgets::checkbox(ui, &mut o.cam_transform_on_drop, tl!("Transform On Drop"));
crate::widgets::vline(ui, 22.0);
if crate::cam_transform::active(app) {
// The box on the dropped patch: ✓ computes the move, ⊘ drops it (as ↩ / Esc).
let tip = crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]);
let commit = crate::icons::button(ui, "check", 26.0, false, &tip);
commit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Commit transform"));
if commit.clicked() {
crate::cam_transform::commit(app);
}
let cancel = crate::icons::button(ui, "ban", 26.0, false, tl!("Cancel transform (Esc)"));
cancel.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Cancel transform"));
if cancel.clicked() {
crate::cam_transform::cancel(app);
}
} else {
opt(ui, tl!("Lasso around an area, then drag the selection"));
}
}
Tool::PatternStamp => {
pattern_stamp_options(app, ui);
}
@@ -890,3 +985,7 @@ fn pattern_stamp_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "../cam_options_bar_tests.rs"]
mod cam_options_bar_tests;
@@ -659,6 +659,7 @@ fn content_aware_move_tool_lassoes_then_moves_or_extends() {
app.run("paint.pencil", json!({"points": [[20, 30], [24, 30]], "size": 6, "color": "#0000ff"})).unwrap();
let blue = |app: &PhotocraftApp, x: i32| active(app).surface().unwrap().rgba(x, 30)[0] < 0.5;
app.ui.tool = Tool::ContentAwareMove;
app.ui.tool_options.cam_transform_on_drop = false;
app.ui.tool_options.cam_mode = mode.into();
app.ui.tool_options.cam_structure = 7.0;
let m = egui::Modifiers::NONE;
@@ -329,6 +329,9 @@ pub(crate) fn nudge(app: &mut PhotocraftApp, dx: f64, dy: f64) {
/// Save for Web (Legacy): refused under an open box, as it would export without the preview (#6737).
pub(crate) const SAVE_FOR_WEB: &str = "file.export.saveForWebLegacy";
/// Layer › Copy CSS: refused under an open box too, as it would copy the bounds from before it.
const COPY_CSS: &str = photocraft_engine::layer_css_cmds::ID;
/// While transforming, Undo and Redo apply to the box: `Some(enabled)` for those commands (and
/// Toggle Last State, which would change the document under the box), `None` for the rest.
pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {
@@ -352,7 +355,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {
// No Toggle Last State or history jump under the box, and one box at a time.
"edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" => Some(false),
// Save for Web exports the committed document and would ignore the pending box (#6737).
SAVE_FOR_WEB => Some(false),
// Copy CSS, likewise, would copy the layers' bounds from before the box.
SAVE_FOR_WEB | COPY_CSS => Some(false),
// Rotate and Flip turn the box (not while warping, where the mesh is the box).
_ if box_preset(id).is_some() => Some(t.warp.is_none()),
// One box over several layers doesn't warp (#6501).
@@ -400,7 +404,8 @@ fn box_preset(id: &str) -> Option<(f64, f64, f64)> {
/// `None` for other commands or when not transforming.
/// The commands the open box answers itself ([`is_enabled`], [`intercept`]).
fn box_command(id: &str) -> bool {
matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB) || box_preset(id).is_some()
matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB | COPY_CSS)
|| box_preset(id).is_some()
}
pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option<Result<serde_json::Value, String>> {
@@ -411,7 +416,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option<Result<serde_json:
match id {
"edit.undo" => Some(Ok(step(app, false))),
"edit.redo" => Some(Ok(step(app, true))),
"edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB => {
"edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB | COPY_CSS => {
Some(Err("Commit or cancel the transform first".into()))
}
_ => {
@@ -1148,6 +1148,47 @@ fn save_for_web_is_off_under_a_pending_transform() {
assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "back after the box closes");
}
/// Layer › Copy CSS reads the committed document, so, as Save for Web (#6737), it is off while a
/// box is pending: the clipboard never gets the bounds from before the move. After Cancel it
/// copies the old place, after a commit the new one.
#[test]
fn copy_css_is_off_under_a_pending_transform() {
let id = photocraft_engine::layer_css_cmds::ID;
let ctx = egui::Context::default();
let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));
let copy_css = |app: &mut PhotocraftApp| {
let mut result = None;
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| result = Some(crate::menus::invoke(app, ui.ctx(), id, json!({}))));
out.textures_delta.clear();
(result.unwrap(), out.platform_output.commands)
};
let moved = |app: &mut PhotocraftApp| {
crate::menus::invoke(app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap();
let t = app.ui.transform.as_mut().unwrap();
t.quad = t.quad.map(|[x, y]| [x + 20.0, y]);
};
assert!(crate::menus::is_enabled(&app, id), "enabled with no box");
moved(&mut app);
assert!(!crate::menus::is_enabled(&app, id), "off under the box");
let (result, clipboard) = copy_css(&mut app);
assert!(result.is_err(), "refused under the box: {result:?}");
assert!(clipboard.is_empty(), "nothing reaches the clipboard: {clipboard:?}");
assert!(app.ui.transform.is_some(), "the box stays open");
cancel(&mut app);
assert!(crate::menus::is_enabled(&app, id), "back after Cancel");
let (result, clipboard) = copy_css(&mut app);
let css = result.unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains("left: 8px;"), "{css}");
assert_eq!(clipboard, [egui::OutputCommand::CopyText(css)]);
moved(&mut app);
commit(&mut app);
assert!(app.ui.transform.is_none() && crate::menus::is_enabled(&app, id), "back after the commit");
let (result, clipboard) = copy_css(&mut app);
let css = result.unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains("left: 28px;"), "the moved place: {css}");
assert_eq!(clipboard, [egui::OutputCommand::CopyText(css)]);
}
/// #352: ⌥⌘T transforms a copy. OK leaves the original and a moved copy as one history step;
/// Cancel leaves no copy and nothing to redo; with a selection the copy holds the selected
/// pixels only.
+131 -11
View File
@@ -11,6 +11,12 @@ pub(crate) struct Runtime {
/// The startup prompt and the self-update behind it (desktop).
#[cfg(not(target_arch = "wasm32"))]
updater: craft_update::updater::Updater,
/// What the last self-update came to, shown in the result window until it is closed.
#[cfg(not(target_arch = "wasm32"))]
last_update: craft_update::updater::Status,
/// The check running was asked for with Help ▸ Check for Updates.
#[cfg(not(target_arch = "wasm32"))]
requested: bool,
}
impl Default for Runtime {
@@ -20,6 +26,10 @@ impl Default for Runtime {
notified_version: None,
#[cfg(not(target_arch = "wasm32"))]
updater: craft_update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION),
#[cfg(not(target_arch = "wasm32"))]
last_update: craft_update::updater::Status::Idle,
#[cfg(not(target_arch = "wasm32"))]
requested: false,
}
}
}
@@ -51,11 +61,33 @@ pub(crate) fn check(app: &mut PhotocraftApp, _ctx: &egui::Context, params: Value
app.updates_rt.startup_checked = true;
// A release the user dismissed is offered again by a manual check.
app.updates_rt.notified_version = None;
// The window shows this check from now on.
#[cfg(not(target_arch = "wasm32"))]
{
app.updates_rt.requested = true;
app.updates_rt.updater.dismiss_status();
app.updates_rt.last_update = craft_update::updater::Status::Idle;
// A check made before the first frame leaves the last self-update's records for the
// next start.
app.services.last_update = None;
}
}
result
}
pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(read) = app.services.last_update.take() {
use craft_update::updater::Status as Shown;
app.updates_rt.last_update = match read() {
Some(Ok(version)) => Shown::Updated(version),
Some(Err(reason)) => Shown::InstallFailed(reason),
None => Shown::Idle,
};
if app.updates_rt.last_update != Shown::Idle {
app.ui.updates_open = true;
}
}
// `updates.status` also polls (automation may consume the result before this frame).
app.session.updates.poll();
if let Status::Available { release } = &app.session.updates.status
@@ -64,7 +96,19 @@ pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) {
app.updates_rt.notified_version = Some(release.version.clone());
app.ui.updates_open = true;
#[cfg(not(target_arch = "wasm32"))]
app.updates_rt.updater.offer(release_of(release));
{
let updater = &mut app.updates_rt.updater;
updater.offer(release_of(release));
// While an update installs or waits for the app to close, or while the launcher keeps
// this version, no prompt opens: a manual check reports that state in the result window.
if std::mem::take(&mut app.updates_rt.requested) && !updater.prompt_open() {
updater.check_now(ctx);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
if !matches!(app.session.updates.status, Status::Checking) {
app.updates_rt.requested = false;
}
if app.session.updates.check.is_none() {
return;
@@ -89,7 +133,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
{
let was_open = app.updates_rt.updater.prompt_open();
app.updates_rt.updater.tick(ctx);
// The restart helper is scheduled before the app closes, so no update starts over unsaved work.
// An update starts, and a ready one asks the app to close, only while no work is unsaved.
let clean = !app.has_unsaved_work();
match app.updates_rt.updater.show_if(ctx, clean) {
craft_update::updater::Action::None => {}
@@ -98,8 +142,9 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
// relaunches once the process exits.
craft_update::updater::Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
}
// The last self-update's outcome, hidden while the prompt showed, is still shown after it.
if was_open && !app.updates_rt.updater.prompt_open() {
app.ui.updates_open = false;
app.ui.updates_open = app.updates_rt.last_update != craft_update::updater::Status::Idle;
}
}
if let Some(url) = download {
@@ -108,15 +153,37 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
if app.updates_rt.updater.prompt_open() {
return;
}
if app.ui.updates_open {
let dialog = craft_update::CheckResultDialog::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION);
match dialog.show(ctx, &check_status(&app.session.updates.status)) {
craft_update::CheckResultResponse::None => {}
craft_update::CheckResultResponse::Close => app.ui.updates_open = false,
craft_update::CheckResultResponse::CheckAgain => {
let _ = check(app, ctx, serde_json::json!({}));
}
let status = shown_status(app);
let dialog = craft_update::CheckResultDialog::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION);
match dialog.show(ctx, &status) {
craft_update::CheckResultResponse::None => {}
craft_update::CheckResultResponse::Close => {
app.ui.updates_open = false;
app.updates_rt.updater.dismiss_status();
app.updates_rt.last_update = craft_update::updater::Status::Idle;
}
craft_update::CheckResultResponse::CheckAgain => {
let _ = check(app, ctx, serde_json::json!({}));
}
craft_update::CheckResultResponse::RestartToUpdate => app.updates_rt.updater.restart_to_update(),
}
}
/// What the open result window shows: the updater's answer to a manual check (an update installing
/// or ready, or a version the launcher keeps), else the last self-update's outcome, else the
/// engine's check.
#[cfg(not(target_arch = "wasm32"))]
fn shown_status(app: &PhotocraftApp) -> craft_update::updater::Status {
use craft_update::updater::Status as Shown;
let updater = app.updates_rt.updater.status();
if !app.ui.updates_open {
Shown::Idle
} else if *updater != Shown::Idle {
updater.clone()
} else if app.updates_rt.last_update != Shown::Idle {
app.updates_rt.last_update.clone()
} else {
check_status(&app.session.updates.status)
}
}
@@ -270,6 +337,59 @@ mod tests {
assert!(app.updates_rt.updater.prompt_open());
}
#[cfg(not(target_arch = "wasm32"))]
fn press_escape(app: &mut PhotocraftApp, ctx: &egui::Context) {
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let mut output = ctx.run_ui(egui::RawInput { events: vec![escape], ..Default::default() }, |ui| show(app, ui.ctx()));
output.textures_delta.clear();
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn the_last_update_opens_the_result_window_once_until_it_is_closed() {
use craft_update::updater::Status as Shown;
let (mut app, _, _) = app();
app.services.last_update = Some(|| Some(Ok("99.0.0".into())));
let ctx = egui::Context::default();
at(&mut app, &ctx, 0.0);
assert!(app.ui.updates_open);
assert_eq!(shown_status(&app), Shown::Updated("99.0.0".into()));
assert!(app.services.last_update.is_none(), "read once");
at(&mut app, &ctx, 1.0);
assert_eq!(shown_status(&app), Shown::Updated("99.0.0".into()), "shown until closed");
press_escape(&mut app, &ctx);
assert!(!app.ui.updates_open);
assert_eq!(app.updates_rt.last_update, Shown::Idle);
assert_eq!(shown_status(&app), Shown::Idle);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_failed_update_is_reported_until_a_manual_check_replaces_it() {
use craft_update::updater::Status as Shown;
let (mut app, calls, _) = app();
app.services.last_update = Some(|| Some(Err("the installer exited with code 1603".into())));
app.session.edit_prefs(|p| p.general.automatically_check_updates = false);
let ctx = egui::Context::default();
at(&mut app, &ctx, 0.0);
assert_eq!(shown_status(&app), Shown::InstallFailed("the installer exited with code 1603".into()));
menus::invoke(&mut app, &ctx, "help.checkForUpdates", serde_json::json!({})).unwrap();
assert_eq!(*calls.lock().unwrap(), 1);
assert_eq!(shown_status(&app), Shown::Checking, "the window shows the new check");
let (mut early, _, _) = self::app();
early.services.last_update = Some(|| Some(Err("unread".into())));
menus::invoke(&mut early, &ctx, "help.checkForUpdates", serde_json::json!({})).unwrap();
at(&mut early, &ctx, 0.0);
assert_eq!(shown_status(&early), Shown::Checking, "a check before the first frame is not replaced by the last update");
assert!(early.services.last_update.is_none());
let (mut quiet, _, _) = self::app();
quiet.services.last_update = Some(|| None);
at(&mut quiet, &ctx, 0.0);
assert!(!quiet.ui.updates_open, "nothing to report opens nothing");
}
#[test]
fn a_manual_check_that_fails_to_start_opens_the_status_window() {
let mut app =
@@ -101,6 +101,12 @@ pub fn field_gesture_running(ctx: &Context) -> bool {
ctx.data(|d| d.get_temp::<Gesture>(gesture_id())).is_some_and(|g| matches!(g.owner, Owner::Field(_)) && now - g.last <= GESTURE_GAP)
}
/// Whether [`begin_frame`] handed wheel notches to the focused value field this frame: they step
/// it as the arrow keys do, though the frame's scroll delta no longer shows them.
pub(crate) fn focused_field_wheeled(ctx: &Context) -> bool {
ctx.data(|d| d.get_temp::<Vec<Event>>(taken_id())).is_some_and(|e| !e.is_empty())
}
/// Record that value field `id` (whose slot is `field`, as given to [`notches`]) has keyboard
/// focus this frame, so the wheel is its next frame.
pub fn set_focused(ctx: &Context, id: Id, field: Id) {
+226
View File
@@ -0,0 +1,226 @@
//! Guard the production display surfaces without banning compatibility identifiers or notices.
use std::path::{Path, PathBuf};
const BANNED: &[&str] = &[
"Camera Raw",
"Adobe Single-line Composer",
"Adobe Every-line Composer",
"Adobe PDF Presets",
"Default Photoshop Size",
"All shortcuts reset to Photoshop defaults.",
];
// Photoshop's own wording where it is stored data or a search alias, never a label: the .atn step
// name Save Actions writes back (the menu item and window read "RAW Develop"), and the names a
// command list is filtered by.
const ALLOWED: &[&str] = &[
"Adobe Camera Raw Filter",
"Camera Raw Filter",
"Camera Raw Defaults",
"Save these settings as a Camera Raw .xmp file",
"Load settings from a Camera Raw .xmp file",
];
// The only catalog rows that may say "Camera Raw": their English text names Photoshop's .xmp files.
const ALLOWED_KEYS: &[&str] = &["Save these settings as a Camera Raw .xmp file", "Load settings from a Camera Raw .xmp file"];
const ROOTS: &[&str] = &["src", "../engine/src"];
fn is_word(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// The bans as written, before any exemption: does `text` say one of them as a whole word?
fn mentions_banned(text: &str) -> bool {
BANNED.iter().any(|banned| {
text.match_indices(banned)
.any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word))
})
}
fn banned_display(text: &str) -> bool {
!ALLOWED.contains(&text) && mentions_banned(text)
}
// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is
// needed, so this guard can also run by itself when a full application build is unavailable.
#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together.
fn literals(source: &str) -> Vec<String> {
let chars: Vec<char> = source.chars().collect();
let mut out = Vec::new();
let mut at = 0;
let mut test_module = false;
let mut test_depth = 0_usize;
while at < chars.len() {
if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) {
at += 12;
let rest: String = chars[at..].iter().collect();
if rest.trim_start().starts_with("mod ") {
test_module = true;
}
} else if chars.get(at..at + 2) == Some(&['/', '/']) {
while at < chars.len() && chars[at] != '\n' {
at += 1;
}
} else if chars.get(at..at + 2) == Some(&['/', '*']) {
at += 2;
let mut depth = 1;
while at < chars.len() && depth > 0 {
if chars.get(at..at + 2) == Some(&['/', '*']) {
depth += 1;
at += 2;
} else if chars.get(at..at + 2) == Some(&['*', '/']) {
depth -= 1;
at += 2;
} else {
at += 1;
}
}
} else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) {
let start = at;
at += 1;
while chars.get(at) == Some(&'#') {
at += 1;
}
let hashes = at - start - 1;
if chars.get(at) != Some(&'"') {
continue;
}
at += 1;
let begin = at;
while at < chars.len() {
if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) {
break;
}
at += 1;
}
if !test_module {
out.push(chars[begin..at].iter().collect());
}
at += 1 + hashes;
} else if chars[at] == '"' {
at += 1;
let mut text = String::new();
while at < chars.len() {
let c = chars[at];
at += 1;
if c == '"' {
break;
}
if c == '\\' && at < chars.len() {
text.push(chars[at]);
at += 1;
} else {
text.push(c);
}
}
if !test_module {
out.push(text);
}
} else if chars[at] == '\'' && chars.get(at + 2) == Some(&'\'') {
at += 3; // A character literal such as '"', not the start of a string.
} else {
if test_module {
match chars[at] {
'{' => test_depth += 1,
'}' => {
test_depth = test_depth.saturating_sub(1);
if test_depth == 0 {
test_module = false;
}
}
';' if test_depth == 0 => test_module = false,
_ => {}
}
}
at += 1;
}
}
out
}
fn check_tree(path: &Path, failures: &mut Vec<String>) {
if path.is_dir() {
for entry in std::fs::read_dir(path).expect("source directory") {
let path = entry.expect("source entry").path();
if path.file_name().is_some_and(|name| name == "tests") {
continue;
}
check_tree(&path, failures);
}
} else if path.extension().is_some_and(|ext| ext == "rs") {
let name = path.file_name().expect("source filename").to_string_lossy();
if name == "tests.rs" || name.ends_with("_tests.rs") {
return;
}
let source = std::fs::read_to_string(path).expect("UTF-8 Rust source");
// Skip only inline test modules, not later production following test-only imports.
for text in literals(&source) {
if banned_display(&text) {
failures.push(format!("{}: {text:?}", path.display()));
}
}
}
}
#[test]
fn production_display_names_stay_neutral() {
let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut failures = Vec::new();
for root in ROOTS {
let root = base.join(root);
assert!(root.exists(), "missing display source: {}", root.display());
check_tree(&root, &mut failures);
}
assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n"));
}
#[test]
fn guard_distinguishes_labels_from_identifiers_and_comments() {
for name in BANNED {
assert!(banned_display(name), "{name}");
}
for name in ALLOWED {
assert!(!banned_display(name), "{name}");
}
assert!(!banned_display("filter.cameraRaw"));
assert!(!banned_display("tool.guidedUpright"));
assert!(!banned_display("insert.smartArt"));
assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]);
assert_eq!(literals("r#\"raw label\"#"), ["raw label"]);
}
#[test]
fn catalogs_do_not_restore_retired_display_names() {
// The catalogs live in craft-i18n (`CRAFT_I18N_DIR`, at `craft-i18n.rev`); without it there is nothing to scan.
let Some(root) = std::env::var_os("CRAFT_I18N_DIR").filter(|d| !d.is_empty()) else {
return;
};
let mut scanned = 0;
for entry in std::fs::read_dir(PathBuf::from(root).join("locales")).expect("craft-i18n locales directory") {
let path = entry.expect("locale entry").path().join("photocraft.tsv");
if !path.is_file() {
continue;
}
scanned += 1;
let source = std::fs::read_to_string(&path).expect("UTF-8 catalog");
for line in source.lines().filter(|line| !line.starts_with('#')) {
let columns: Vec<_> = line.split('\t').collect();
if let [_, key, value] = columns.as_slice() {
assert!(ALLOWED_KEYS.contains(key) || !mentions_banned(key), "{}: retired key {key}", path.display());
if !ALLOWED_KEYS.contains(key) {
assert!(!mentions_banned(value), "{}: retired display text {value}", path.display());
}
assert_ne!(*key, "Open in camera raw", "{}: dormant key", path.display());
}
}
}
assert!(scanned > 30, "only {scanned} photocraft.tsv catalogs under CRAFT_I18N_DIR");
}
#[test]
fn guard_scans_production_after_test_only_items() {
let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; }
#[cfg(test)] use fixtures::Helper;
fn production() { let _ = r#"live label"#; }
"###;
assert_eq!(literals(source), ["live label"]);
assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]);
}
+17
View File
@@ -0,0 +1,17 @@
# Feature naming
PhotoCraft names its own raw-processing workspace **RAW Develop**, the adjustment **RAW Develop Filter**, and its raw preferences **RAW Defaults**. All 34 shipped non-English catalogs use the new keys and localized labels.
## Compatibility boundary
The `filter.cameraRaw` command, raw preference IDs, Rust type names and serialized settings remain stable. Existing documents retain their own saved filter names. New filters get the neutral display name.
Adobe Camera Raw PSD/action descriptor class names, XMP namespaces and the settings-file compatibility descriptions are unchanged. Import/export mapping code and attribution are unchanged.
A Photoshop action's step name is stored in the action file, so a saved Camera Raw step keeps Photoshop's "Camera Raw Filter" wording and a loaded action round-trips unchanged. Only PhotoCraft's own step labels, menus and windows say RAW Develop Filter.
## Validation before readiness
Review menu and dialog layout in the supported interfaces, run the engine/UI tests and the existing PSD/action/XMP round-trip tests, and complete the normal platform gates. This is a feature naming change, not a legal determination.
The catalog cleanup removes 136 dormant rows for branded composer labels, PDF presets, old Photoshop defaults and the unused raw-opening label. No active non-localization call sites use those keys. Current PhotoCraft defaults and required compatibility descriptions remain intact. Regression guards cover production Rust display literals and catalog keys; explicit exceptions document interchange descriptions and identifiers.
+3 -3
View File
@@ -2,14 +2,14 @@
Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand.
**662 of 662 menu items live (100.0%).**
**664 of 664 menu items live (100.0%).**
| Menu | Live | Total | % |
|---|---:|---:|---:|
| File | 52 | 52 | 100% |
| File | 53 | 53 | 100% |
| Edit | 75 | 75 | 100% |
| Image | 61 | 61 | 100% |
| Layer | 162 | 162 | 100% |
| Layer | 163 | 163 | 100% |
| Type | 74 | 74 | 100% |
| Select | 25 | 25 | 100% |
| Filter | 75 | 75 | 100% |
+2 -2
View File
@@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Tools](#tools) | 36 | 9 | 0 | |
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 199 (target 0) |
| [Type](#type) | 5 | 5 | 0 | |
| [Automation](#automation) | 5 | 4 | 2 | 662 of 662 menu items live (100.0%) |
| [Automation](#automation) | 5 | 4 | 2 | 664 of 664 menu items live (100.0%) |
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present |
| [Distribution](#distribution) | 5 | 5 | 1 | |
| [Open bugs](#open-bugs) | 31 | 1 | 0 | |
@@ -256,7 +256,7 @@ Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.
## Automation
Menu wiring (`docs/parity-checklist.md`): 662 of 662 menu items live (100.0%). This counts dispatch, not behaviour.
Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). This counts dispatch, not behaviour.
| Id | Target | Status | Issue | Note |
|---|---|---|---|---|
+2 -1
View File
@@ -1,6 +1,6 @@
# UI parity: tools, handles, modifiers and feel
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (a click on the image centres a filter dialog's preview window, #9648; a gradient stop dragged off the bar is removed in every stop editor, Gradient Map and Layer Style included, #10742; Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Hue/Saturation range zones drag, #9252; a click on the image centres a filter dialog's preview window, #9648; a gradient stop dragged off the bar is removed in every stop editor, Gradient Map and Layer Style included, #10742; Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames everyLine truncated
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
@@ -295,6 +295,7 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-24 | minor | Path Selection selects path components and has the Path Operations menu; the menu and `+` / `-` change the selected components' operation (`path.setOperation`); the Pen carries on an open shape layer or vector mask path from its endpoint (#1397 feedback); row stays partial until the Shape tools have the menu; no percentage changed |
| 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) |
| 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) |
| 2026-10-24 | minor | Hue/Saturation: dragging between a colour range's handles moves them as Photoshop 2025 does: the fully-on span moves all four, each fade its own two (#9252). Scores unchanged. |
| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed |
| 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. |
| 2026-10-24 | minor | Type options bar: the alignment and paragraph-direction buttons show the edited or selected type layer's paragraph instead of the tool defaults, as Photoshop's bar does. Scores unchanged. |
@@ -116,5 +116,5 @@ modules:
path: stage
- type: git
url: https://github.com/storytold/craft-i18n
commit: 723a3b49ca26899acc838262478f65d59ac1bc26
commit: 31d158f9ee077086e3bb446909e8129bc8092d3b
dest: craft-i18n
@@ -127,5 +127,5 @@ modules:
# The interface translations at the commit in craft-i18n.rev (a test keeps the two equal).
- type: git
url: https://github.com/storytold/craft-i18n
commit: 723a3b49ca26899acc838262478f65d59ac1bc26
commit: 31d158f9ee077086e3bb446909e8129bc8092d3b
dest: craft-i18n