Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Analysis, notes, proof views, workspaces (+ in-progress work of other agents)

Brandon Thomasaa87012aab6d
diff --git a/Cargo.lock b/Cargo.lock
index be61c1121..284cce661 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3366,8 +3366,10 @@ name = "photocraft-engine"
version = "0.1.0"
dependencies = [
"blake3",
+ "flate2",
"photocraft-algo",
"photocraft-cms",
+ "photocraft-codecs",
"photocraft-color",
"photocraft-compose",
"photocraft-doc",
@@ -3379,6 +3381,7 @@ dependencies = [
"photocraft-raster",
"photocraft-text",
"photocraft-vector",
+ "rayon",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -3496,6 +3499,7 @@ dependencies = [
name = "photocraft-text"
version = "0.1.0"
dependencies = [
+ "flate2",
"parley",
"photocraft-color",
"photocraft-doc",
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 7e5e72939..a2b4edc00 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -21,10 +21,16 @@ USAGE:
applies to the preceding --cmd. Prints each command's JSON result.
photocraft-cli batch --actions <actions.json> --in <dir> --out <dir> [--format <ext>]
Apply an action list ([{\"command\": id, \"params\": {…}}, …]) to every image in a directory.
+ photocraft-cli droplet <file.pcdroplet> <file-or-dir>… [--out <dir>]
+ Run a droplet (File › Automate › Create Droplet) on images and folders.
photocraft-cli commands [--json] [--filter <text>]
List the engine command registry.
photocraft-cli mcp [--bridge <127.0.0.1:port>]
Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`).
+ photocraft-cli serve [--port <port>]
+ Keep one headless session open and answer JSON lines ({\"id\",\"method\",\"params\"}) on stdio,
+ or on 127.0.0.1:<port>. Methods: engine.execute, engine.commands, doc.open/new/save/inspect/render/
+ select/close, session.list, batch, methods (docs/control-protocol.md#headless-server).
";
struct Args {
@@ -43,6 +49,7 @@ const VALUE_FLAGS: &[&str] = &[
"--in",
"--filter",
"--bridge",
+ "--port",
];
fn parse(args: &[String]) -> Result<Args, String> {
@@ -105,13 +112,19 @@ pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
"run" => run_cmds(&parsed, out, err),
"batch" => batch(&parsed, out, err),
"commands" => commands(&parsed, out),
+ "droplet" => droplet(&parsed, out, err),
"mcp" => mcp(&parsed),
+ "serve" => serve(&parsed, err),
"-h" | "--help" | "help" => {
let _ = write!(out, "{USAGE}");
return 0;
}
"--version" | "version" => {
- let _ = writeln!(out, "photocraft-cli {}", photocraft_engine::build_info::long_version());
+ let _ = writeln!(
+ out,
+ "photocraft-cli {}",
+ photocraft_engine::build_info::long_version()
+ );
return 0;
}
other => {
@@ -343,6 +356,41 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
}
}
+fn droplet(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
+ let (file, inputs) = a
+ .positional
+ .split_first()
+ .ok_or("droplet needs <file.pcdroplet> and inputs")?;
+ if inputs.is_empty() {
+ return Err("droplet needs at least one input file or folder".into());
+ }
+ let mut p = json!({"droplet": file, "input": inputs});
+ if let Some(o) = a.get("--out") {
+ p["output"] = json!(o);
+ }
+ let mut s = photocraft_engine::Session::new();
+ let r = s
+ .execute("file.automate.runDroplet", p)
+ .map_err(|e| e.to_string())?;
+ for f in r["files"].as_array().into_iter().flatten() {
+ let _ = writeln!(out, "ok {}", f.as_str().unwrap_or_default());
+ }
+ let errors = r["errors"].as_array().cloned().unwrap_or_default();
+ for e in &errors {
+ let _ = writeln!(
+ err,
+ "FAIL {}: {}",
+ e["file"].as_str().unwrap_or_default(),
+ e["error"].as_str().unwrap_or_default()
+ );
+ }
+ if errors.is_empty() {
+ Ok(())
+ } else {
+ Err(format!("{} file(s) failed", errors.len()))
+ }
+}
+
fn commands(a: &Args, out: &mut dyn Write) -> R {
let h = Headless::new();
let list = h.command_list();
@@ -393,6 +441,26 @@ fn commands(a: &Args, out: &mut dyn Write) -> R {
Ok(())
}
+fn serve(a: &Args, err: &mut dyn Write) -> R {
+ use std::sync::{Arc, Mutex};
+ let h = Arc::new(Mutex::new(Headless::new()));
+ match a.get("--port") {
+ Some(port) => {
+ let port: u16 = port.parse().map_err(|_| format!("bad --port `{port}`"))?;
+ let addr = format!("127.0.0.1:{port}");
+ photocraft_automation::rpc::serve_tcp(&addr, h, |local| {
+ let _ = writeln!(err, "photocraft-cli serving on {local}");
+ })
+ .map_err(|e| e.to_string())
+ }
+ None => {
+ let stdin = std::io::stdin();
+ photocraft_automation::rpc::serve_lines(&h, stdin.lock(), std::io::stdout())
+ .map_err(|e| e.to_string())
+ }
+ }
+}
+
fn mcp(a: &Args) -> R {
let server = match a.get("--bridge") {
Some(addr) => PhotocraftMcp::bridge(addr).map_err(|e| e.to_string())?,
diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs
index c4573c5db..b2d6e3dad 100644
--- a/apps/photocraft-cli/tests/cli.rs
+++ b/apps/photocraft-cli/tests/cli.rs
@@ -332,3 +332,38 @@ fn mcp_stdio_handshake_and_tool_call() {
let _ = child.kill();
let _ = child.wait();
}
+
+#[test]
+fn droplet_runs_an_action_on_files() {
+ let d = tmp("droplet");
+ write_png(&d.join("a.png"), 8, 4, 3);
+ write_png(&d.join("b.png"), 6, 2, 5);
+ let droplet = d.join("rot.pcdroplet");
+ std::fs::write(
+ &droplet,
+ json!({"photocraftDroplet": 1, "name": "rot", "action": {"steps": [["image.imageRotation.90cw", {}]]}, "options": {"format": "png"}}).to_string(),
+ )
+ .unwrap();
+ let out_dir = d.join("out");
+ let (out, _) = ok(bin()
+ .arg("droplet")
+ .arg(&droplet)
+ .arg(d.join("a.png"))
+ .arg(d.join("b.png"))
+ .arg("--out")
+ .arg(&out_dir));
+ assert_eq!(
+ out.lines().filter(|l| l.starts_with("ok")).count(),
+ 2,
+ "{out}"
+ );
+ let img = photocraft_codecs::decode(&std::fs::read(out_dir.join("a.png")).unwrap()).unwrap();
+ assert_eq!(img.dimensions(), (4, 8));
+ let o = bin()
+ .arg("droplet")
+ .arg(d.join("a.png"))
+ .arg(d.join("b.png"))
+ .output()
+ .unwrap();
+ assert!(!o.status.success(), "not a droplet");
+}
diff --git a/assets/dict/LICENSE-SCOWL.txt b/assets/dict/LICENSE-SCOWL.txt
new file mode 100644
index 000000000..44efb0fbb
--- /dev/null
+++ b/assets/dict/LICENSE-SCOWL.txt
@@ -0,0 +1,258 @@
+en_US-scowl-50.txt.gz: English word list for Edit > Check Spelling.
+Source: SCOWL (Spell Checker Oriented Word Lists) 2020.12.07 by Kevin Atkinson,
+http://wordlist.aspell.net/ (downloads.sourceforge.net/project/wordlist/SCOWL/2020.12.07/scowl-2020.12.07.tar.gz).
+Built from final/{english,american}-{words,upper,contractions,proper-names,abbreviations}.{10,20,35,40,50}
+(size 50, en_US spelling), converted Latin-1 -> UTF-8, possessives ("'s") removed (the checker strips them),
+grouped by SCOWL level ("#10", "#20", "#35", "#40", "#50" header lines; each word under the most common level it appears in), sorted within a level, one word per line, gzip -9. 72,403 words.
+
+SCOWL licence (verbatim from the distribution's Copyright file):
+-----------------------------------------------------------------
+
+The collective work is Copyright 2000-2018 by Kevin Atkinson as well
+as any of the copyrights mentioned below:
+
+ Copyright 2000-2018 by Kevin Atkinson
+
+ Permission to use, copy, modify, distribute and sell these word
+ lists, the associated scripts, the output created from the scripts,
+ and its documentation for any purpose is hereby granted without fee,
+ provided that the above copyright notice appears in all copies and
+ that both that copyright notice and this permission notice appear in
+ supporting documentation. Kevin Atkinson makes no representations
+ about the suitability of this array for any purpose. It is provided
+ "as is" without express or implied warranty.
+
+Alan Beale <[email protected]> also deserves special credit as he has,
+in addition to providing the 12Dicts package and being a major
+contributor to the ENABLE word list, given me an incredible amount of
+feedback and created a number of special lists (those found in the
+Supplement) in order to help improve the overall quality of SCOWL.
+
+The 10 level includes the 1000 most common English words (according to
+the Moby (TM) Words II [MWords] package), a subset of the 1000 most
+common words on the Internet (again, according to Moby Words II), and
+frequently class 16 from Brian Kelk's "UK English Wordlist
+with Frequency Classification".
+
+The MWords package was explicitly placed in the public domain:
+
+ The Moby lexicon project is complete and has
+ been place into the public domain. Use, sell,
+ rework, excerpt and use in any way on any platform.
+
+ Placing this material on internal or public servers is
+ also encouraged. The compiler is not aware of any
+ export restrictions so freely distribute world-wide.
+
+ You can verify the public domain status by contacting
+
+ Grady Ward
+ 3449 Martha Ct.
+ Arcata, CA 95521-4884
+
+
+The "UK English Wordlist With Frequency Classification" is also in the
+Public Domain:
+
+ Date: Sat, 08 Jul 2000 20:27:21 +0100
+ From: Brian Kelk <[email protected]>
+
+ > I was wondering what the copyright status of your "UK English
+ > Wordlist With Frequency Classification" word list as it seems to
+ > be lacking any copyright notice.
+
+ There were many many sources in total, but any text marked
+ "copyright" was avoided. Locally-written documentation was one
+ source. An earlier version of the list resided in a filespace called
+ PUBLIC on the University mainframe, because it was considered public
+ domain.
+
+ Date: Tue, 11 Jul 2000 19:31:34 +0100
+
+ > So are you saying your word list is also in the public domain?
+
+ That is the intention.
+
+The 20 level includes frequency classes 7-15 from Brian's word list.
+
+The 35 level includes frequency classes 2-6 and words appearing in at
+least 11 of 12 dictionaries as indicated in the 12Dicts package. All
+words from the 12Dicts package have had likely inflections added via
+my inflection database.
+
+The 12Dicts package and Supplement is in the Public Domain.
+
+The WordNet database, which was used in the creation of the
+Inflections database, is under the following copyright:
+
+ This software and database is being provided to you, the LICENSEE,
+ by Princeton University under the following license. By obtaining,
+ using and/or copying this software and database, you agree that you
+ have read, understood, and will comply with these terms and
+ conditions.:
+
+ Permission to use, copy, modify and distribute this software and
+ database and its documentation for any purpose and without fee or
+ royalty is hereby granted, provided that you agree to comply with
+ the following copyright notice and statements, including the
+ disclaimer, and that the same appear on ALL copies of the software,
+ database and documentation, including modifications that you make
+ for internal use or for distribution.
+
+ WordNet 1.6 Copyright 1997 by Princeton University. All rights
+ reserved.
+
+ THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON
+ UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON
+ UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-
+ ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE
+ LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT INFRINGE ANY
+ THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
+
+ The name of Princeton University or Princeton may not be used in
+ advertising or publicity pertaining to distribution of the software
+ and/or database. Title to copyright in this software, database and
+ any associated documentation shall at all times remain with
+ Princeton University and LICENSEE agrees to preserve same.
+
+The 40 level includes words from Alan's 3esl list found in version 4.0
+of his 12dicts package. Like his other stuff the 3esl list is also in the
+public domain.
+
+The 50 level includes Brian's frequency class 1, words appearing
+in at least 5 of 12 of the dictionaries as indicated in the 12Dicts
+package, and uppercase words in at least 4 of the previous 12
+dictionaries. A decent number of proper names is also included: The
+top 1000 male, female, and Last names from the 1990 Census report; a
+list of names sent to me by Alan Beale; and a few names that I added
+myself. Finally a small list of abbreviations not commonly found in
+other word lists is included.
+
+The name files form the Census report is a government document which I
+don't think can be copyrighted.
+
+The file special-jargon.50 uses common.lst and word.lst from the
+"Unofficial Jargon File Word Lists" which is derived from "The Jargon
+File". All of which is in the Public Domain. This file also contain
+a few extra UNIX terms which are found in the file "unix-terms" in the
+special/ directory.
+
+The 55 level includes words from Alan's 2of4brif list found in version
+4.0 of his 12dicts package. Like his other stuff the 2of4brif is also
+in the public domain.
+
+The 60 level includes all words appearing in at least 2 of the 12
+dictionaries as indicated by the 12Dicts package.
+
+The 70 level includes Brian's frequency class 0 and the 74,550 common
+dictionary words from the MWords package. The common dictionary words,
+like those from the 12Dicts package, have had all likely inflections
+added. The 70 level also included the 5desk list from version 4.0 of
+the 12Dics package which is in the public domain.
+
+The 80 level includes the ENABLE word list, all the lists in the
+ENABLE supplement package (except for ABLE), the "UK Advanced Cryptics
+Dictionary" (UKACD), the list of signature words from the YAWL package,
+and the 10,196 places list from the MWords package.
+
+The ENABLE package, mainted by M\Cooper <[email protected]>,
+is in the Public Domain:
+
+ The ENABLE master word list, WORD.LST, is herewith formally released
+ into the Public Domain. Anyone is free to use it or distribute it in
+ any manner they see fit. No fee or registration is required for its
+ use nor are "contributions" solicited (if you feel you absolutely
+ must contribute something for your own peace of mind, the authors of
+ the ENABLE list ask that you make a donation on their behalf to your
+ favorite charity). This word list is our gift to the Scrabble
+ community, as an alternate to "official" word lists. Game designers
+ may feel free to incorporate the WORD.LST into their games. Please
+ mention the source and credit us as originators of the list. Note
+ that if you, as a game designer, use the WORD.LST in your product,
+ you may still copyright and protect your product, but you may *not*
+ legally copyright or in any way restrict redistribution of the
+ WORD.LST portion of your product. This *may* under law restrict your
+ rights to restrict your users' rights, but that is only fair.
+
+UKACD, by J Ross Beresford <[email protected]>, is under the
+following copyright:
+
+ Copyright (c) J Ross Beresford 1993-1999. All Rights Reserved.
+
+ The following restriction is placed on the use of this publication:
+ if The UK Advanced Cryptics Dictionary is used in a software package
+ or redistributed in any form, the copyright notice must be
+ prominently displayed and the text of this document must be included
+ verbatim.
+
+ There are no other restrictions: I would like to see the list
+ distributed as widely as possible.
+
+The 95 level includes the 354,984 single words, 256,772 compound
+words, 4,946 female names and the 3,897 male names, and 21,986 names
+from the MWords package, ABLE.LST from the ENABLE Supplement, and some
+additional words found in my part-of-speech database that were not
+found anywhere else.
+
+Accent information was taken from UKACD.
+
+The VarCon package was used to create the American, British, Canadian,
+and Australian word list. It is under the following copyright:
+
+ Copyright 2000-2016 by Kevin Atkinson
+
+ Permission to use, copy, modify, distribute and sell this array, the
+ associated software, and its documentation for any purpose is hereby
+ granted without fee, provided that the above copyright notice appears
+ in all copies and that both that copyright notice and this permission
+ notice appear in supporting documentation. Kevin Atkinson makes no
+ representations about the suitability of this array for any
+ purpose. It is provided "as is" without express or implied warranty.
+
+ Copyright 2016 by Benjamin Titze
+
+ Permission to use, copy, modify, distribute and sell this array, the
+ associated software, and its documentation for any purpose is hereby
+ granted without fee, provided that the above copyright notice appears
+ in all copies and that both that copyright notice and this permission
+ notice appear in supporting documentation. Benjamin Titze makes no
+ representations about the suitability of this array for any
+ purpose. It is provided "as is" without express or implied warranty.
+
+ Since the original words lists come from the Ispell distribution:
+
+ Copyright 1993, Geoff Kuenning, Granada Hills, CA
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. All modifications to the source code must be clearly marked as
+ such. Binary redistributions based on modified source code
+ must be clearly marked as modified versions in the documentation
+ and/or other materials provided with the distribution.
+ (clause 4 removed with permission from Geoff Kuenning)
+ 5. The name of Geoff Kuenning may not be used to endorse or promote
+ products derived from this software without specific prior
+ written permission.
+
+ THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
diff --git a/assets/dict/en_US-scowl-50.txt.gz b/assets/dict/en_US-scowl-50.txt.gz
new file mode 100644
index 000000000..3015aad76
Binary files /dev/null and b/assets/dict/en_US-scowl-50.txt.gz differ
diff --git a/assets/icons/chevron-up.svg b/assets/icons/chevron-up.svg
new file mode 100644
index 000000000..b011f7721
--- /dev/null
+++ b/assets/icons/chevron-up.svg
@@ -0,0 +1,13 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="m18 15-6-6-6 6" />
+</svg>
diff --git a/assets/icons/file.svg b/assets/icons/file.svg
new file mode 100644
index 000000000..7daf04c2f
--- /dev/null
+++ b/assets/icons/file.svg
@@ -0,0 +1,14 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" />
+ <path d="M14 2v4a2 2 0 0 0 2 2h4" />
+</svg>
diff --git a/assets/icons/house.svg b/assets/icons/house.svg
new file mode 100644
index 000000000..8bf34bdc8
--- /dev/null
+++ b/assets/icons/house.svg
@@ -0,0 +1,14 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8" />
+ <path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
+</svg>
diff --git a/assets/icons/rectangle-vertical.svg b/assets/icons/rectangle-vertical.svg
new file mode 100644
index 000000000..e76594578
--- /dev/null
+++ b/assets/icons/rectangle-vertical.svg
@@ -0,0 +1,13 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="12" height="20" x="6" y="2" rx="2" />
+</svg>
diff --git a/assets/icons/ruler.svg b/assets/icons/ruler.svg
new file mode 100644
index 000000000..1eb52e3c5
--- /dev/null
+++ b/assets/icons/ruler.svg
@@ -0,0 +1,17 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z" />
+ <path d="m14.5 12.5 2-2" />
+ <path d="m11.5 9.5 2-2" />
+ <path d="m8.5 6.5 2-2" />
+ <path d="m17.5 15.5 2-2" />
+</svg>
diff --git a/assets/icons/slice-knife.svg b/assets/icons/slice-knife.svg
new file mode 100644
index 000000000..8d4115ffa
--- /dev/null
+++ b/assets/icons/slice-knife.svg
@@ -0,0 +1,16 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <!-- PhotoCraft's own Slice tool glyph (not from an icon set): a knife over a cut line. -->
+ <path d="M4 20l6-6" />
+ <path d="M10 14l8.6-8.6a2 2 0 0 1 2.8 2.8L12.5 17z" />
+ <path d="M3 22h7" stroke-dasharray="2 2" />
+</svg>
diff --git a/assets/icons/square-dot.svg b/assets/icons/square-dot.svg
new file mode 100644
index 000000000..898323f61
--- /dev/null
+++ b/assets/icons/square-dot.svg
@@ -0,0 +1,14 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="18" height="18" x="3" y="3" rx="2" />
+ <circle cx="12" cy="12" r="1" />
+</svg>
diff --git a/assets/icons/square-plus.svg b/assets/icons/square-plus.svg
new file mode 100644
index 000000000..efb75f85c
--- /dev/null
+++ b/assets/icons/square-plus.svg
@@ -0,0 +1,15 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="18" height="18" x="3" y="3" rx="2" />
+ <path d="M8 12h8" />
+ <path d="M12 8v8" />
+</svg>
diff --git a/assets/icons/toggle-left.svg b/assets/icons/toggle-left.svg
new file mode 100644
index 000000000..7a72a7210
--- /dev/null
+++ b/assets/icons/toggle-left.svg
@@ -0,0 +1,14 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="20" height="12" x="2" y="6" rx="6" ry="6" />
+ <circle cx="8" cy="12" r="2" />
+</svg>
diff --git a/assets/icons/toggle-right.svg b/assets/icons/toggle-right.svg
new file mode 100644
index 000000000..0c17fb097
--- /dev/null
+++ b/assets/icons/toggle-right.svg
@@ -0,0 +1,14 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <rect width="20" height="12" x="2" y="6" rx="6" ry="6" />
+ <circle cx="16" cy="12" r="2" />
+</svg>
diff --git a/crates/algo/examples/bench_photo.rs b/crates/algo/examples/bench_photo.rs
new file mode 100644
index 000000000..c9e11228d
--- /dev/null
+++ b/crates/algo/examples/bench_photo.rs
@@ -0,0 +1,102 @@
+//! Timing for the computational-photography algorithms on a ~24 MP (6000×4000) image:
+//! Camera Raw develop, Lens Correction, Adaptive Wide Angle, HDR merge + tone mapping, Crop and
+//! Straighten detection, and a 4-image panorama registration + blend (2 MP sources).
+//! `cargo run --release -p photocraft-algo --example bench_photo [case-substring]`
+use std::time::Instant;
+
+use photocraft_algo::camera_raw::{CameraRaw, Wheel, develop};
+use photocraft_algo::hdr::{self, MergeOptions, ToneMethod};
+use photocraft_algo::lens::{self, LensCorrection};
+use photocraft_algo::panorama::{self, AlignOptions, Layout, RoiImage};
+use photocraft_algo::tone::HdrToning;
+use photocraft_algo::transform::Interp;
+use photocraft_algo::wideangle::{self, Constraint, Orientation, WideAngle, WideModel};
+use photocraft_color::PixelFormat;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+fn pattern(w: usize, h: usize) -> Vec<[f32; 4]> {
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = (i % w, i / w);
+ let t = ((x * 7 + y * 3) % 251) as f32 / 251.0;
+ [(x % 256) as f32 / 255.0 * 0.6 + 0.2 * t, ((x * 3 + y) / 11 % 256) as f32 / 255.0, ((x ^ y) % 256) as f32 / 255.0, 1.0]
+ })
+ .collect()
+}
+
+fn time<T>(name: &str, only: &Option<String>, f: impl FnOnce() -> T) -> Option<T> {
+ if only.as_ref().is_some_and(|o| !name.contains(o.as_str())) {
+ return None;
+ }
+ let t0 = Instant::now();
+ let r = f();
+ println!("{name:<40} {:>9.1} ms", t0.elapsed().as_secs_f64() * 1000.0);
+ Some(r)
+}
+
+fn main() {
+ let only = std::env::args().nth(1);
+ let (w, h) = (6000usize, 4000usize);
+ let px = pattern(w, h);
+ let r = Rect::new(0, 0, w as i32, h as i32);
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ let bytes: Vec<u8> = px.iter().flat_map(|q| q.map(|v| (v * 255.0) as u8)).collect();
+ s.write_interleaved(r, &bytes);
+
+ time("camera raw: basic (wb, exposure, tone)", &only, || {
+ let mut a = px.clone();
+ develop(&mut a, w, h, &CameraRaw { temperature: 20.0, exposure: 0.3, contrast: 20.0, highlights: -40.0, shadows: 40.0, whites: 10.0, blacks: -10.0, vibrance: 20.0, ..Default::default() }, false);
+ });
+ time("camera raw: clarity + texture + dehaze", &only, || {
+ let mut a = px.clone();
+ develop(&mut a, w, h, &CameraRaw { clarity: 30.0, texture: 20.0, dehaze: 25.0, ..Default::default() }, false);
+ });
+ time("camera raw: hsl + grading + curve", &only, || {
+ let mut a = px.clone();
+ let mut hs = [0.0; 8];
+ hs[2] = 30.0;
+ develop(&mut a, w, h, &CameraRaw { hsl_sat: hs, grade_shadows: Wheel { hue: 220.0, sat: 30.0, lum: 0.0 }, point_curve: vec![[0.0, 10.0], [128.0, 140.0], [255.0, 250.0]], ..Default::default() }, false);
+ });
+ time("camera raw: sharpen + NR + grain + vignette", &only, || {
+ let mut a = px.clone();
+ develop(&mut a, w, h, &CameraRaw { sharpen_amount: 40.0, noise_luminance: 30.0, noise_color: 25.0, grain_amount: 20.0, vignette_amount: -30.0, ..Default::default() }, false);
+ });
+ time("lens correction (distortion, CA, vignette, persp)", &only, || {
+ lens::correct(&s, r, &LensCorrection { profile: Some(lens::generic_profile(24.0)), distortion: 10.0, red_cyan: 20.0, vignette_amount: 30.0, vertical: -20.0, angle: 1.5, ..Default::default() })
+ });
+ time("adaptive wide angle (fisheye, 2 constraints)", &only, || {
+ let p = WideAngle {
+ model: WideModel::Fisheye,
+ focal_length: 12.0,
+ constraints: vec![Constraint { a: [500.0, 600.0], b: [5500.0, 600.0], orientation: Orientation::Horizontal }, Constraint { a: [700.0, 500.0], b: [700.0, 3500.0], orientation: Orientation::Vertical }],
+ ..Default::default()
+ };
+ wideangle::apply(&s, r, &p, Interp::Bicubic)
+ });
+ time("hdr: merge 3 exposures + local adaptation", &only, || {
+ let shots: Vec<Vec<[f32; 4]>> = [0.5f32, 1.0, 2.0].iter().map(|k| px.iter().map(|q| [(q[0] * k).min(1.0), (q[1] * k).min(1.0), (q[2] * k).min(1.0), 1.0]).collect()).collect();
+ let refs: Vec<&[[f32; 4]]> = shots.iter().map(Vec::as_slice).collect();
+ let t0 = Instant::now();
+ let mut m = hdr::merge(w, h, &refs, &MergeOptions { exposures: vec![0.5, 1.0, 2.0], remove_ghosts: true, ghost_base: None, response: None });
+ println!(" merge {:.1} ms", t0.elapsed().as_secs_f64() * 1000.0);
+ hdr::tone_map(&mut m.px, w, h, &ToneMethod::LocalAdaptation(HdrToning { radius: 7.0, strength: 0.52, ..Default::default() }));
+ });
+ time("crop and straighten: detection", &only, || photocraft_algo::scancrop::find_photos(w, h, &px));
+ time("panorama: 4 × 2 MP register + blend", &only, || {
+ let (sw, sh) = (1700usize, 1200usize);
+ let views: Vec<Vec<f32>> = (0..4).map(|k| (0..sw * sh).map(|i| { let q = px[(i / sw + 300) * w + i % sw + 1100 * k]; 0.3 * q[0] + 0.6 * q[1] + 0.1 * q[2] }).collect()).collect();
+ let prepared: Vec<panorama::PreparedImage> = views.iter().map(|v| (sw, sh, v.clone(), None)).collect();
+ let t0 = Instant::now();
+ let feats = panorama::detect_many(&prepared, 800);
+ let matches = panorama::match_pairs(&feats);
+ let al = panorama::align(&feats, &matches, &AlignOptions { layout: Layout::Reposition, focal: None, reference: None, geometric: false });
+ println!(" register {:.1} ms ({} pairs, placed {})", t0.elapsed().as_secs_f64() * 1000.0, matches.len(), al.as_ref().map_or(0, |a| a.placements.iter().flatten().count()));
+ let rois: Vec<RoiImage> = views.iter().enumerate().map(|(k, v)| RoiImage { x0: 1100 * k as i32, y0: 0, w: sw, h: sh, ch: 1, px: v.clone(), alpha: vec![1.0; sw * sh] }).collect();
+ let cw = 1100 * 3 + sw;
+ let wts: Vec<Vec<f32>> = (0..4i32).map(|k| (0..sw * sh).map(|i| { let x = (i % sw) as i32 + 1100 * k; if (x / 1100).min(3) == k { 1.0 } else { 0.0 } }).collect()).collect();
+ let t1 = Instant::now();
+ let _ = panorama::multiband(cw, sh, &rois, &wts, panorama::blend_levels(cw, sh));
+ println!(" multiband {:.1} ms", t1.elapsed().as_secs_f64() * 1000.0);
+ });
+}
diff --git a/crates/algo/src/artistic.rs b/crates/algo/src/artistic.rs
new file mode 100644
index 000000000..b77e63430
--- /dev/null
+++ b/crates/algo/src/artistic.rs
@@ -0,0 +1,244 @@
+//! Filter Gallery: the 47 "artistic" filters of Photoshop's gallery (Artistic, Brush Strokes,
+//! Distort, Sketch, Stylize and Texture), applied as a stack of effect layers in order.
+//!
+//! Each filter is described by a parameter notation string (the same notation the engine
+//! registry uses, e.g. `{"pencilWidth":1..24=4,"texture":"canvas|brick"}`, first choice =
+//! default) so the engine, the dialogs and agents share one source of truth. The pixel work
+//! lives in [`crate::artistic_fx`]. Implemented clean-room from observed behaviour: parameter
+//! names and ranges follow Photoshop's dialogs; the looks are our own approximations.
+
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+
+macro_rules! gallery {
+ ($( $v:ident = $key:literal, $name:literal, $cat:literal, $doc:literal; )*) => {
+ /// One Filter Gallery filter.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ pub enum GalleryFilter { $($v),* }
+
+ impl GalleryFilter {
+ /// Every gallery filter, grouped by category in Photoshop's order.
+ pub const ALL: &'static [GalleryFilter] = &[$(GalleryFilter::$v),*];
+ /// Camel-case key (`coloredPencil`); the command id is `filter.gallery.<key>`.
+ pub fn key(self) -> &'static str { match self { $(GalleryFilter::$v => $key),* } }
+ /// Engine command id.
+ pub fn command_id(self) -> &'static str { match self { $(GalleryFilter::$v => concat!("filter.gallery.", $key)),* } }
+ /// Display name (Photoshop's).
+ pub fn name(self) -> &'static str { match self { $(GalleryFilter::$v => $name),* } }
+ /// Gallery folder.
+ pub fn category(self) -> &'static str { match self { $(GalleryFilter::$v => $cat),* } }
+ /// Parameter notation (ranges, defaults, choices).
+ pub fn params_doc(self) -> &'static str { match self { $(GalleryFilter::$v => $doc),* } }
+ }
+ };
+}
+
+gallery! {
+ // ---- Artistic ----
+ ColoredPencil = "coloredPencil", "Colored Pencil", "Artistic", r#"{"pencilWidth":1..24=4,"strokePressure":0..15=8,"paperBrightness":0..50=25}"#;
+ Cutout = "cutout", "Cutout", "Artistic", r#"{"numberOfLevels":2..8=4,"edgeSimplicity":0..10=4,"edgeFidelity":1..3=2}"#;
+ DryBrush = "dryBrush", "Dry Brush", "Artistic", r#"{"brushSize":0..10=2,"brushDetail":0..10=8,"texture":1..3=1}"#;
+ FilmGrain = "filmGrain", "Film Grain", "Artistic", r#"{"grain":0..20=4,"highlightArea":0..20=0,"intensity":0..10=10}"#;
+ Fresco = "fresco", "Fresco", "Artistic", r#"{"brushSize":0..10=2,"brushDetail":0..10=8,"texture":1..3=1}"#;
+ NeonGlow = "neonGlow", "Neon Glow", "Artistic", r#"{"glowSize":-24..24=5,"glowBrightness":0..50=15,"glowColor":json}"#;
+ PaintDaubs = "paintDaubs", "Paint Daubs", "Artistic", r#"{"brushSize":1..50=8,"sharpness":0..40=7,"brushType":"simple|lightRough|darkRough|wideSharp|wideBlurry|sparkle"}"#;
+ PaletteKnife = "paletteKnife", "Palette Knife", "Artistic", r#"{"strokeSize":1..50=25,"strokeDetail":1..3=3,"softness":0..10=0}"#;
+ PlasticWrap = "plasticWrap", "Plastic Wrap", "Artistic", r#"{"highlightStrength":0..20=15,"detail":1..15=9,"smoothness":1..15=7}"#;
+ PosterEdges = "posterEdges", "Poster Edges", "Artistic", r#"{"edgeThickness":0..10=2,"edgeIntensity":0..10=1,"posterization":0..6=2}"#;
+ RoughPastels = "roughPastels", "Rough Pastels", "Artistic", r#"{"strokeLength":0..40=6,"strokeDetail":1..20=4,"texture":"canvas|brick|burlap|sandstone","scaling":50..200=100,"relief":0..50=20,"light":"bottom|bottomLeft|left|topLeft|top|topRight|right|bottomRight","invert":bool}"#;
+ SmudgeStick = "smudgeStick", "Smudge Stick", "Artistic", r#"{"strokeLength":0..10=2,"highlightArea":0..20=0,"intensity":0..10=10}"#;
+ Sponge = "sponge", "Sponge", "Artistic", r#"{"brushSize":0..10=2,"definition":0..25=12,"smoothness":1..15=5}"#;
+ Underpainting = "underpainting", "Underpainting", "Artistic", r#"{"brushSize":0..40=6,"textureCoverage":0..40=16,"texture":"canvas|brick|burlap|sandstone","scaling":50..200=100,"relief":0..50=4,"light":"top|topRight|right|bottomRight|bottom|bottomLeft|left|topLeft","invert":bool}"#;
+ Watercolor = "watercolor", "Watercolor", "Artistic", r#"{"brushDetail":1..14=9,"shadowIntensity":0..10=1,"texture":1..3=1}"#;
+ // ---- Brush Strokes ----
+ AccentedEdges = "accentedEdges", "Accented Edges", "Brush Strokes", r#"{"edgeWidth":1..14=2,"edgeBrightness":0..50=38,"smoothness":1..15=5}"#;
+ AngledStrokes = "angledStrokes", "Angled Strokes", "Brush Strokes", r#"{"directionBalance":0..100=50,"strokeLength":3..50=15,"sharpness":0..10=3}"#;
+ Crosshatch = "crosshatch", "Crosshatch", "Brush Strokes", r#"{"strokeLength":3..50=9,"sharpness":0..20=6,"strength":1..3=1}"#;
+ DarkStrokes = "darkStrokes", "Dark Strokes", "Brush Strokes", r#"{"balance":0..10=5,"blackIntensity":0..10=6,"whiteIntensity":0..10=2}"#;
+ InkOutlines = "inkOutlines", "Ink Outlines", "Brush Strokes", r#"{"strokeLength":1..50=4,"darkIntensity":0..50=20,"lightIntensity":0..50=10}"#;
+ Spatter = "spatter", "Spatter", "Brush Strokes", r#"{"sprayRadius":0..25=10,"smoothness":1..15=5}"#;
+ SprayedStrokes = "sprayedStrokes", "Sprayed Strokes", "Brush Strokes", r#"{"strokeLength":0..20=12,"sprayRadius":0..25=7,"strokeDirection":"rightDiagonal|horizontal|leftDiagonal|vertical"}"#;
+ SumiE = "sumiE", "Sumi-e", "Brush Strokes", r#"{"strokeWidth":3..15=10,"strokePressure":0..15=2,"contrast":0..40=16}"#;
+ // ---- Distort ----
+ DiffuseGlow = "diffuseGlow", "Diffuse Glow", "Distort", r#"{"graininess":0..10=6,"glowAmount":0..20=10,"clearAmount":0..20=15,"background":json}"#;
+ Glass = "glass", "Glass", "Distort", r#"{"distortion":0..20=5,"smoothness":1..15=3,"texture":"frosted|blocks|canvas|tinyLens","scaling":50..200=100,"invert":bool}"#;
+ OceanRipple = "oceanRipple", "Ocean Ripple", "Distort", r#"{"rippleSize":1..15=9,"rippleMagnitude":0..20=9}"#;
+ // ---- Sketch (foreground = ink, background = paper) ----
+ BasRelief = "basRelief", "Bas Relief", "Sketch", r#"{"detail":1..15=13,"smoothness":1..15=3,"light":"bottom|bottomLeft|left|topLeft|top|topRight|right|bottomRight","foreground":json,"background":json}"#;
+ ChalkCharcoal = "chalkCharcoal", "Chalk & Charcoal", "Sketch", r#"{"charcoalArea":0..20=6,"chalkArea":0..20=6,"strokePressure":0..5=1,"foreground":json,"background":json}"#;
+ Charcoal = "charcoal", "Charcoal", "Sketch", r#"{"charcoalThickness":1..7=1,"detail":0..5=5,"lightDarkBalance":0..100=50,"foreground":json,"background":json}"#;
+ Chrome = "chrome", "Chrome", "Sketch", r#"{"detail":0..10=4,"smoothness":0..10=7}"#;
+ ConteCrayon = "conteCrayon", "Conté Crayon", "Sketch", r#"{"foregroundLevel":1..15=11,"backgroundLevel":1..15=7,"texture":"canvas|brick|burlap|sandstone","scaling":50..200=100,"relief":0..50=4,"light":"top|topRight|right|bottomRight|bottom|bottomLeft|left|topLeft","invert":bool,"foreground":json,"background":json}"#;
+ GraphicPen = "graphicPen", "Graphic Pen", "Sketch", r#"{"strokeLength":1..15=15,"lightDarkBalance":0..100=50,"strokeDirection":"rightDiagonal|horizontal|leftDiagonal|vertical","foreground":json,"background":json}"#;
+ HalftonePattern = "halftonePattern", "Halftone Pattern", "Sketch", r#"{"size":1..12=1,"contrast":0..50=5,"patternType":"dot|circle|line","foreground":json,"background":json}"#;
+ NotePaper = "notePaper", "Note Paper", "Sketch", r#"{"imageBalance":0..50=25,"graininess":0..20=10,"relief":0..25=11,"foreground":json,"background":json}"#;
+ Photocopy = "photocopy", "Photocopy", "Sketch", r#"{"detail":1..24=7,"darkness":1..50=8,"foreground":json,"background":json}"#;
+ Plaster = "plaster", "Plaster", "Sketch", r#"{"imageBalance":0..50=20,"smoothness":1..15=2,"light":"top|topRight|right|bottomRight|bottom|bottomLeft|left|topLeft","foreground":json,"background":json}"#;
+ Reticulation = "reticulation", "Reticulation", "Sketch", r#"{"density":0..50=12,"foregroundLevel":0..50=40,"backgroundLevel":0..50=5,"foreground":json,"background":json}"#;
+ Stamp = "stamp", "Stamp", "Sketch", r#"{"lightDarkBalance":0..50=25,"smoothness":1..50=5,"foreground":json,"background":json}"#;
+ TornEdges = "tornEdges", "Torn Edges", "Sketch", r#"{"imageBalance":0..50=25,"smoothness":1..15=11,"contrast":1..25=17,"foreground":json,"background":json}"#;
+ WaterPaper = "waterPaper", "Water Paper", "Sketch", r#"{"fiberLength":3..50=15,"brightness":0..100=60,"contrast":0..100=80}"#;
+ // ---- Stylize ----
+ GlowingEdges = "glowingEdges", "Glowing Edges", "Stylize", r#"{"edgeWidth":1..14=2,"edgeBrightness":0..20=6,"smoothness":1..15=5}"#;
+ // ---- Texture ----
+ Craquelure = "craquelure", "Craquelure", "Texture", r#"{"crackSpacing":2..100=15,"crackDepth":0..10=6,"crackBrightness":0..10=9}"#;
+ Grain = "grain", "Grain", "Texture", r#"{"intensity":0..100=40,"contrast":0..100=50,"grainType":"regular|soft|sprinkles|clumped|contrasty|enlarged|stippled|horizontal|vertical|speckle","foreground":json,"background":json}"#;
+ MosaicTiles = "mosaicTiles", "Mosaic Tiles", "Texture", r#"{"tileSize":2..100=12,"groutWidth":1..15=3,"lightenGrout":0..10=9}"#;
+ Patchwork = "patchwork", "Patchwork", "Texture", r#"{"squareSize":0..10=4,"relief":0..25=8}"#;
+ StainedGlass = "stainedGlass", "Stained Glass", "Texture", r#"{"cellSize":2..50=10,"borderThickness":1..20=4,"lightIntensity":0..10=3,"foreground":json}"#;
+ Texturizer = "texturizer", "Texturizer", "Texture", r#"{"texture":"canvas|brick|burlap|sandstone","scaling":50..200=100,"relief":0..50=4,"light":"top|topRight|right|bottomRight|bottom|bottomLeft|left|topLeft","invert":bool}"#;
+}
+
+/// The gallery's folders, in order.
+pub const GALLERY_CATEGORIES: [&str; 6] = ["Artistic", "Brush Strokes", "Distort", "Sketch", "Stylize", "Texture"];
+
+/// One parameter of a gallery filter.
+#[derive(Clone, Debug, PartialEq)]
+pub enum GalleryParamKind {
+ Range { min: f32, max: f32, default: f32 },
+ /// Choices; the first is the default. Stored as the index.
+ Choice(Vec<&'static str>),
+ Bool(bool),
+}
+
+/// A parsed parameter.
+#[derive(Clone, Debug, PartialEq)]
+pub struct GalleryParam {
+ pub key: &'static str,
+ pub kind: GalleryParamKind,
+}
+
+impl GalleryFilter {
+ /// Looks a filter up by key (`coloredPencil`), command id or display name.
+ pub fn from_key(k: &str) -> Option<GalleryFilter> {
+ let k = k.strip_prefix("filter.gallery.").unwrap_or(k);
+ Self::ALL.iter().copied().find(|f| f.key() == k || f.name().eq_ignore_ascii_case(k))
+ }
+
+ /// The numeric / choice / bool parameters (colours are not listed; they are fields of
+ /// [`GalleryEffect`]).
+ pub fn params(self) -> Vec<GalleryParam> {
+ let doc = self.params_doc();
+ let inner = doc.trim().trim_start_matches('{').trim_end_matches('}');
+ let mut out = Vec::new();
+ for part in inner.split(',') {
+ let Some((k, v)) = part.split_once(':') else { continue };
+ let key = k.trim().trim_matches('"');
+ let v = v.trim();
+ let kind = if let Some(body) = v.strip_prefix('"') {
+ GalleryParamKind::Choice(body.trim_end_matches('"').split('|').collect())
+ } else if v == "bool" {
+ GalleryParamKind::Bool(false)
+ } else if let Some((range, def)) = v.split_once('=') {
+ let (lo, hi) = range.split_once("..").unwrap_or(("0", "1"));
+ let p = |s: &str| s.trim().parse::<f32>().unwrap_or(0.0);
+ GalleryParamKind::Range { min: p(lo), max: p(hi), default: p(def) }
+ } else {
+ continue; // json (colours)
+ };
+ out.push(GalleryParam { key, kind });
+ }
+ out
+ }
+
+ /// Whether the filter reads the foreground / background colours.
+ pub fn uses_colours(self) -> bool {
+ self.params_doc().contains("\"foreground\"") || self.params_doc().contains("\"background\"")
+ }
+}
+
+/// Photoshop's default Neon Glow colour (a saturated sky blue).
+pub const NEON_DEFAULT: [f32; 4] = [0.0, 0.62, 1.0, 1.0];
+
+/// One effect layer of the gallery: a filter with its values. Choice values are indices into
+/// the filter's choice list; bools are 0/1. Colours are straight sRGB RGBA, 0–1.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GalleryEffect {
+ pub filter: GalleryFilter,
+ #[serde(default)]
+ pub values: BTreeMap<String, f32>,
+ #[serde(default = "black")]
+ pub foreground: [f32; 4],
+ #[serde(default = "white")]
+ pub background: [f32; 4],
+ #[serde(default = "neon")]
+ pub color: [f32; 4],
+}
+
+fn black() -> [f32; 4] {
+ [0.0, 0.0, 0.0, 1.0]
+}
+fn white() -> [f32; 4] {
+ [1.0, 1.0, 1.0, 1.0]
+}
+fn neon() -> [f32; 4] {
+ NEON_DEFAULT
+}
+
+impl GalleryEffect {
+ /// The filter with its default values, black ink on white paper.
+ pub fn new(filter: GalleryFilter) -> Self {
+ let mut values = BTreeMap::new();
+ for p in filter.params() {
+ let v = match p.kind {
+ GalleryParamKind::Range { default, .. } => default,
+ GalleryParamKind::Choice(_) => 0.0,
+ GalleryParamKind::Bool(b) => b as u8 as f32,
+ };
+ values.insert(p.key.to_string(), v);
+ }
+ GalleryEffect { filter, values, foreground: black(), background: white(), color: neon() }
+ }
+
+ /// Sets a numeric value (clamped to its range), a choice by index, or a bool.
+ pub fn set(&mut self, key: &str, v: f32) {
+ if let Some(p) = self.filter.params().into_iter().find(|p| p.key == key) {
+ let v = match p.kind {
+ GalleryParamKind::Range { min, max, .. } => v.clamp(min, max),
+ GalleryParamKind::Choice(c) => v.round().clamp(0.0, c.len() as f32 - 1.0),
+ GalleryParamKind::Bool(_) => (v != 0.0) as u8 as f32,
+ };
+ self.values.insert(key.to_string(), v);
+ }
+ }
+
+ /// Sets a choice by name; false if the name is not one of the choices.
+ pub fn set_choice(&mut self, key: &str, name: &str) -> bool {
+ let Some(GalleryParamKind::Choice(c)) = self.filter.params().into_iter().find(|p| p.key == key).map(|p| p.kind) else { return false };
+ match c.iter().position(|n| n.eq_ignore_ascii_case(name)) {
+ Some(i) => {
+ self.values.insert(key.to_string(), i as f32);
+ true
+ }
+ None => false,
+ }
+ }
+
+ /// A numeric value (default when unset).
+ pub fn get(&self, key: &str) -> f32 {
+ if let Some(v) = self.values.get(key) {
+ return *v;
+ }
+ match self.filter.params().into_iter().find(|p| p.key == key).map(|p| p.kind) {
+ Some(GalleryParamKind::Range { default, .. }) => default,
+ Some(GalleryParamKind::Bool(b)) => b as u8 as f32,
+ _ => 0.0,
+ }
+ }
+
+ /// A bool value.
+ pub fn flag(&self, key: &str) -> bool {
+ self.get(key) != 0.0
+ }
+
+ /// The chosen name of a choice parameter.
+ pub fn choice(&self, key: &str) -> &'static str {
+ match self.filter.params().into_iter().find(|p| p.key == key).map(|p| p.kind) {
+ Some(GalleryParamKind::Choice(c)) => c.get(self.get(key).max(0.0) as usize).copied().unwrap_or(c[0]),
+ _ => "",
+ }
+ }
+}
diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs
new file mode 100644
index 000000000..383c247ed
--- /dev/null
+++ b/crates/algo/src/artistic_fx.rs
@@ -0,0 +1,1225 @@
+//! Pixel work of the Filter Gallery ([`crate::artistic`]).
+//!
+//! Every effect runs on an sRGB working copy of the tile's input window (straight colour; the
+//! source alpha is kept) and may read up to [`effect_reach`] pixels around each output pixel,
+//! so a stack of effects reads the sum of their reaches. Noise, strokes and textures are
+//! functions of document coordinates, so results do not depend on the tiling.
+
+// Effects walk several per-pixel planes in lockstep; index loops read clearest.
+#![allow(clippy::needless_range_loop)]
+
+use std::f32::consts::PI;
+
+use photocraft_geom::Rect;
+
+use crate::Ctx;
+use crate::artistic::GalleryEffect;
+use crate::artistic::GalleryFilter as F;
+use crate::fxutil::{box_blur_n, cell_point, gauss_blur_n, gauss_box_radii, rgba, set_rgba};
+use crate::image::Image;
+use crate::noise::hash01;
+
+type Px = [f32; 3];
+
+/// The working window: sRGB colour of every pixel of `r`.
+pub(crate) struct Win {
+ r: Rect,
+ w: usize,
+ h: usize,
+ c: Vec<Px>,
+}
+
+impl Win {
+ #[inline]
+ fn xy(&self, i: usize) -> (i32, i32) {
+ (self.r.x0 + (i % self.w) as i32, self.r.y0 + (i / self.w) as i32)
+ }
+ fn lum(&self) -> Vec<f32> {
+ self.c.iter().map(lum).collect()
+ }
+ /// Bilinear sample at document coordinates (pixel centres at .5), clamped to the window.
+ fn sample(&self, x: f32, y: f32) -> Px {
+ let fx = (x - 0.5 - self.r.x0 as f32).clamp(0.0, (self.w - 1) as f32);
+ let fy = (y - 0.5 - self.r.y0 as f32).clamp(0.0, (self.h - 1) as f32);
+ let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
+ let (x1, y1) = ((x0 + 1).min(self.w - 1), (y0 + 1).min(self.h - 1));
+ let (ax, ay) = (fx - x0 as f32, fy - y0 as f32);
+ let g = |xx: usize, yy: usize| self.c[yy * self.w + xx];
+ let top = mix(g(x0, y0), g(x1, y0), ax);
+ let bot = mix(g(x0, y1), g(x1, y1), ax);
+ mix(top, bot, ay)
+ }
+ /// The pixel nearest to document `(x, y)`, clamped to the window.
+ fn at(&self, x: i32, y: i32) -> Px {
+ let xx = (x - self.r.x0).clamp(0, self.w as i32 - 1) as usize;
+ let yy = (y - self.r.y0).clamp(0, self.h as i32 - 1) as usize;
+ self.c[yy * self.w + xx]
+ }
+}
+
+/// Hermite step from `e0` to `e1`; `e0 > e1` gives the falling step.
+#[inline]
+fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
+ if (e1 - e0).abs() < 1e-9 {
+ return if x >= e1 { 1.0 } else { 0.0 };
+ }
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+#[inline]
+fn lum(p: &Px) -> f32 {
+ 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]
+}
+#[inline]
+fn mix(a: Px, b: Px, t: f32) -> Px {
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]
+}
+#[inline]
+fn map(p: Px, f: impl Fn(f32) -> f32) -> Px {
+ [f(p[0]), f(p[1]), f(p[2])]
+}
+#[inline]
+fn grey(v: f32) -> Px {
+ [v, v, v]
+}
+#[inline]
+fn rgb(c: [f32; 4]) -> Px {
+ [c[0], c[1], c[2]]
+}
+#[inline]
+fn clamp01(v: f32) -> f32 {
+ v.clamp(0.0, 1.0)
+}
+#[inline]
+fn posterize(v: f32, levels: f32) -> f32 {
+ let l = (levels - 1.0).max(1.0);
+ (clamp01(v) * l).round() / l
+}
+#[inline]
+fn saturate(p: Px, k: f32) -> Px {
+ let l = lum(&p);
+ map(p, |v| l + (v - l) * k)
+}
+
+/// Pixels a Gaussian blur of `sigma` reads (three box passes per axis).
+fn gs(sigma: f32) -> i32 {
+ if sigma < 0.3 { 0 } else { gauss_box_radii(sigma).iter().sum::<usize>() as i32 + 1 }
+}
+
+fn blur1(p: &mut [f32], w: usize, h: usize, sigma: f32) {
+ gauss_blur_n(p, w, h, 1, sigma);
+}
+fn blur3(c: &mut [Px], w: usize, h: usize, sigma: f32) {
+ gauss_blur_n(c.as_flattened_mut(), w, h, 3, sigma);
+}
+
+/// Sobel gradient (per pixel, edges clamped) of a plane.
+fn sobel(p: &[f32], w: usize, h: usize) -> (Vec<f32>, Vec<f32>) {
+ let at = |x: isize, y: isize| p[(y.clamp(0, h as isize - 1) as usize) * w + x.clamp(0, w as isize - 1) as usize];
+ let mut gx = vec![0.0; w * h];
+ let mut gy = vec![0.0; w * h];
+ for y in 0..h as isize {
+ for x in 0..w as isize {
+ let i = y as usize * w + x as usize;
+ gx[i] = ((at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1))) / 8.0;
+ gy[i] = ((at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1))) / 8.0;
+ }
+ }
+ (gx, gy)
+}
+
+fn grad_mag(p: &[f32], w: usize, h: usize) -> Vec<f32> {
+ let (gx, gy) = sobel(p, w, h);
+ gx.iter().zip(&gy).map(|(a, b)| (a * a + b * b).sqrt()).collect()
+}
+
+/// Running-mean blur of radius `r` steps along direction `d` ((1,0), (0,1), (1,1) or (1,-1))
+/// of an interleaved `n`-channel buffer.
+fn line_blur(buf: &mut [f32], n: usize, w: usize, h: usize, d: (i32, i32), r: usize) {
+ if r == 0 || w == 0 || h == 0 {
+ return;
+ }
+ let (wi, hi) = (w as i32, h as i32);
+ let inside = |x: i32, y: i32| x >= 0 && y >= 0 && x < wi && y < hi;
+ let norm = 1.0 / (2 * r + 1) as f64;
+ let mut idx = Vec::new();
+ let mut vals = Vec::new();
+ for sy in 0..hi {
+ for sx in 0..wi {
+ if inside(sx - d.0, sy - d.1) {
+ continue; // not the start of a line
+ }
+ idx.clear();
+ let (mut x, mut y) = (sx, sy);
+ while inside(x, y) {
+ idx.push((y as usize * w + x as usize) * n);
+ x += d.0;
+ y += d.1;
+ }
+ let m = idx.len() as isize;
+ for c in 0..n {
+ vals.clear();
+ vals.extend(idx.iter().map(|&o| buf[o + c] as f64));
+ let at = |k: isize| vals[k.clamp(0, m - 1) as usize];
+ let mut acc: f64 = (-(r as isize)..=r as isize).map(at).sum();
+ for (k, &o) in idx.iter().enumerate() {
+ buf[o + c] = (acc * norm) as f32;
+ acc += at(k as isize + r as isize + 1) - at(k as isize - r as isize);
+ }
+ }
+ }
+ }
+}
+
+fn line_blur3(c: &mut [Px], w: usize, h: usize, d: (i32, i32), r: usize) {
+ line_blur(c.as_flattened_mut(), 3, w, h, d, r);
+}
+
+fn direction(name: &str) -> (i32, i32) {
+ match name {
+ "horizontal" => (1, 0),
+ "vertical" => (0, 1),
+ "leftDiagonal" => (1, 1),
+ _ => (1, -1), // rightDiagonal: bottom-left to top-right
+ }
+}
+
+/// Kuwahara smoothing (the flattest of four quadrant means): the painterly base of several
+/// Artistic filters. Box means make the cost independent of `r`.
+fn kuwahara(win: &mut Win, r: usize) {
+ let h2 = r.div_ceil(2).max(1);
+ let (w, h) = (win.w, win.h);
+ let mut m: Vec<f32> = Vec::with_capacity(w * h * 5);
+ for p in &win.c {
+ let l = lum(p);
+ m.extend_from_slice(&[p[0], p[1], p[2], l, l * l]);
+ }
+ box_blur_n(&mut m, w, h, 5, h2);
+ let o = h2 as isize;
+ let get = |x: isize, y: isize| {
+ let i = ((y.clamp(0, h as isize - 1) as usize) * w + x.clamp(0, w as isize - 1) as usize) * 5;
+ &m[i..i + 5]
+ };
+ for y in 0..h as isize {
+ for x in 0..w as isize {
+ let mut best = f32::MAX;
+ let mut col = [0.0; 3];
+ for (dx, dy) in [(-o, -o), (o, -o), (-o, o), (o, o)] {
+ let q = get(x + dx, y + dy);
+ let var = q[4] - q[3] * q[3];
+ if var < best {
+ best = var;
+ col = [q[0], q[1], q[2]];
+ }
+ }
+ win.c[y as usize * w + x as usize] = col;
+ }
+ }
+}
+
+fn kuwahara_reach(r: usize) -> i32 {
+ 2 * r.div_ceil(2).max(1) as i32 + 1
+}
+
+fn unsharp(win: &mut Win, sigma: f32, amount: f32) {
+ if amount <= 0.0 {
+ return;
+ }
+ let mut b = win.c.clone();
+ blur3(&mut b, win.w, win.h, sigma);
+ for (p, q) in win.c.iter_mut().zip(&b) {
+ *p = [p[0] + (p[0] - q[0]) * amount, p[1] + (p[1] - q[1]) * amount, p[2] + (p[2] - q[2]) * amount];
+ }
+}
+
+/// Smooth value noise (0–1) on a unit lattice.
+fn vnoise(x: f32, y: f32, seed: u32) -> f32 {
+ let (ix, iy) = (x.floor() as i32, y.floor() as i32);
+ let (tx, ty) = (x - ix as f32, y - iy as f32);
+ let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));
+ let h = |a: i32, b: i32| hash01(a, b, 0, seed);
+ let top = h(ix, iy) + (h(ix + 1, iy) - h(ix, iy)) * sx;
+ let bot = h(ix, iy + 1) + (h(ix + 1, iy + 1) - h(ix, iy + 1)) * sx;
+ top + (bot - top) * sy
+}
+
+/// Three-octave value noise (0–1).
+fn fbm(x: f32, y: f32, seed: u32) -> f32 {
+ (vnoise(x, y, seed) * 0.57 + vnoise(x * 2.03, y * 2.03, seed ^ 0x51) * 0.29 + vnoise(x * 4.1, y * 4.1, seed ^ 0xa3) * 0.14) / 1.0
+}
+
+/// Stroke texture: value noise stretched `len` px along the direction `d` and `wid` px across.
+fn strokes(x: i32, y: i32, d: (i32, i32), len: f32, wid: f32, seed: u32) -> f32 {
+ let (dx, dy) = (d.0 as f32, d.1 as f32);
+ let l = (dx * dx + dy * dy).sqrt().max(1e-6);
+ let (ux, uy) = (dx / l, dy / l);
+ let (x, y) = (x as f32, y as f32);
+ let u = x * ux + y * uy;
+ let v = -x * uy + y * ux;
+ vnoise(u / len.max(0.5), v / wid.max(0.3), seed)
+}
+
+/// Unit vector toward the light in image coordinates (y down).
+fn light_dir(name: &str) -> (f32, f32) {
+ let s = std::f32::consts::FRAC_1_SQRT_2;
+ match name {
+ "bottom" => (0.0, 1.0),
+ "bottomLeft" => (-s, s),
+ "left" => (-1.0, 0.0),
+ "topLeft" => (-s, -s),
+ "topRight" => (s, -s),
+ "right" => (1.0, 0.0),
+ "bottomRight" => (s, s),
+ _ => (0.0, -1.0),
+ }
+}
+
+/// Lambert shading factor (1 = flat) of a height field with gradient `(gx, gy)`.
+#[inline]
+fn shade(gx: f32, gy: f32, light: (f32, f32), k: f32) -> f32 {
+ let (nx, ny, nz) = (-k * gx, -k * gy, 1.0);
+ let nl = (nx * nx + ny * ny + nz * nz).sqrt();
+ let (lx, ly, lz) = (light.0, light.1, 1.0);
+ let ll = (lx * lx + ly * ly + lz * lz).sqrt();
+ let d = (nx * lx + ny * ly + nz * lz) / (nl * ll);
+ d / (lz / ll)
+}
+
+/// Procedural textures (0–1 heights) at document coordinates; `s` scales them (1 = 100 %).
+fn texture(kind: &str, x: f32, y: f32, s: f32) -> f32 {
+ let (x, y) = (x / s, y / s);
+ match kind {
+ "brick" => {
+ let (bw, bh) = (24.0, 12.0);
+ let row = (y / bh).floor();
+ let xo = x + if row as i32 % 2 == 0 { 0.0 } else { bw / 2.0 };
+ let (u, v) = (xo.rem_euclid(bw), y.rem_euclid(bh));
+ let d = u.min(bw - u).min(v.min(bh - v));
+ smoothstep(0.6, 2.2, d) * (0.85 + 0.15 * vnoise(x / 3.0, y / 3.0, 91))
+ }
+ "burlap" => weave(x, y, 7.0, 0.35),
+ "canvas" => weave(x, y, 3.5, 0.18),
+ "sandstone" => fbm(x / 7.0, y / 7.0, 93) * 0.7 + hash01(x as i32, y as i32, 0, 94) * 0.3,
+ "blocks" => {
+ let b = 18.0;
+ let (u, v) = (x.rem_euclid(b) / b, y.rem_euclid(b) / b);
+ (u.min(1.0 - u).min(v.min(1.0 - v)) * 4.0).min(1.0)
+ }
+ "frosted" => fbm(x / 2.5, y / 2.5, 95),
+ "tinyLens" => {
+ let p = 12.0;
+ let (u, v) = ((x.rem_euclid(p) / p - 0.5) * 2.0, (y.rem_euclid(p) / p - 0.5) * 2.0);
+ (1.0 - (u * u + v * v)).max(0.0).sqrt()
+ }
+ _ => 0.5,
+ }
+}
+
+/// Basket weave of threads `p` px wide with `noise` irregularity.
+fn weave(x: f32, y: f32, p: f32, noise: f32) -> f32 {
+ let (cx, cy) = ((x / p).floor() as i32, (y / p).floor() as i32);
+ let over_h = (cx + cy).rem_euclid(2) == 0;
+ let (u, v) = (x.rem_euclid(p) / p, y.rem_euclid(p) / p);
+ // A thread is a rounded ridge across its cell.
+ let ridge = if over_h { (v * PI).sin() } else { (u * PI).sin() };
+ let n = vnoise(x / (p * 0.7), y / (p * 2.0), 97);
+ ridge * (1.0 - noise) + n * noise
+}
+
+/// Texturizer core: relief-shades the window with a procedural texture.
+fn texturize(win: &mut Win, kind: &str, scaling: f32, relief: f32, light: &str, invert: bool) {
+ if relief <= 0.0 {
+ return;
+ }
+ let s = (scaling / 100.0).clamp(0.5, 2.0);
+ let l = light_dir(light);
+ let k = relief / 50.0 * 3.0;
+ let sign = if invert { -1.0 } else { 1.0 };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32, y as f32);
+ let gx = (texture(kind, fx + 1.0, fy, s) - texture(kind, fx - 1.0, fy, s)) * 0.5 * sign;
+ let gy = (texture(kind, fx, fy + 1.0, s) - texture(kind, fx, fy - 1.0, s)) * 0.5 * sign;
+ let f = shade(gx, gy, l, k).clamp(0.0, 2.0);
+ win.c[i] = map(win.c[i], |v| v * f);
+ }
+}
+
+/// Closest and second-closest jittered cell points (distances and the closest point).
+fn voronoi(x: f32, y: f32, cell: f32, seed: u32) -> (f32, f32, (f32, f32)) {
+ let (cx, cy) = ((x / cell).floor() as i32, (y / cell).floor() as i32);
+ let (mut d1, mut d2, mut p1) = (f32::MAX, f32::MAX, (x, y));
+ for j in -1..=1 {
+ for i in -1..=1 {
+ let p = cell_point(cx + i, cy + j, cell, seed, (0.0, 0.0));
+ let d = ((p.0 - x).powi(2) + (p.1 - y).powi(2)).sqrt();
+ if d < d1 {
+ d2 = d1;
+ d1 = d;
+ p1 = p;
+ } else if d < d2 {
+ d2 = d;
+ }
+ }
+ }
+ (d1, d2, p1)
+}
+
+/// Brightens highlights (Film Grain / Smudge Stick "Highlight Area" and "Intensity").
+fn highlights(p: Px, l: f32, area: f32, intensity: f32) -> Px {
+ if area <= 0.0 {
+ return p;
+ }
+ let m = smoothstep(1.0 - area / 20.0 * 0.75, 1.02, l) * (1.0 - intensity / 10.0 * 0.6);
+ map(p, |v| v + (1.0 - v) * m)
+}
+
+/// Pixels an effect reads around an output pixel.
+pub(crate) fn effect_reach(e: &GalleryEffect) -> i32 {
+ let g = |k: &str| e.get(k);
+ match e.filter {
+ F::ColoredPencil => 2,
+ F::Cutout => gs(cutout_sigma(e)),
+ F::DryBrush | F::Fresco => kuwahara_reach(1 + g("brushSize") as usize) + gs(1.0) + 2,
+ F::FilmGrain | F::DiffuseGlow | F::ChalkCharcoal | F::Reticulation | F::Grain | F::MosaicTiles | F::Texturizer => 0,
+ F::RoughPastels => (g("strokeLength") / 2.0) as i32 + 2,
+ F::NeonGlow => gs(g("glowSize").abs() * 0.6 + 0.5),
+ F::PaintDaubs => kuwahara_reach(daubs_radius(e)) + gs(1.5) + 1,
+ F::PaletteKnife => kuwahara_reach((g("strokeSize") / 3.0).max(1.0) as usize) + gs(g("softness") * 0.5),
+ F::PlasticWrap => gs(plastic_sigma(e)) + 2,
+ F::PosterEdges => gs(0.6 + g("edgeThickness") * 0.6) + 2,
+ F::SmudgeStick => (g("strokeLength") * 1.5) as i32 + 2,
+ F::Sponge => kuwahara_reach(1 + g("brushSize") as usize),
+ F::Underpainting => gs(0.5 + g("brushSize") * 0.4),
+ F::Watercolor => kuwahara_reach(watercolor_radius(e)) + 2,
+ F::AccentedEdges => gs(0.4 + g("smoothness") * 0.3) + gs(g("edgeWidth") * 0.5) + 2,
+ F::AngledStrokes => (g("strokeLength") / 3.0) as i32 + gs(1.0) + 2,
+ F::Crosshatch => (g("strokeLength") / 3.0) as i32 + gs(1.0) + 2,
+ F::DarkStrokes => 9,
+ F::InkOutlines => (g("strokeLength") / 2.0) as i32 + 3,
+ F::Spatter => g("sprayRadius").ceil() as i32 + 2,
+ F::SprayedStrokes => g("sprayRadius").ceil() as i32 + (g("strokeLength") / 2.0) as i32 + 3,
+ F::SumiE => gs(g("strokeWidth") * 0.2) + (g("strokeWidth") / 2.0) as i32 + 2,
+ F::Glass => (g("distortion") * 2.0).ceil() as i32 + 2,
+ F::OceanRipple => (g("rippleMagnitude") * 0.9).ceil() as i32 + 2,
+ F::BasRelief => gs(basrelief_sigma(e)) + 2,
+ F::Charcoal => gs(1.0) + 2,
+ F::Chrome => gs(1.0 + g("smoothness") * 0.4) + 2,
+ F::ConteCrayon => 0,
+ F::GraphicPen => (g("strokeLength") / 2.0) as i32 + 2,
+ F::HalftonePattern => gs(0.5 + g("size") * 0.3),
+ F::NotePaper => gs(1.0) + gs(1.2) + 2,
+ F::Photocopy => gs(1.0 + g("detail") * 0.5),
+ F::Plaster => gs(0.5 + g("smoothness") * 0.8) + gs(1.5) + 2,
+ F::Stamp => gs(0.3 + g("smoothness") * 0.3),
+ F::TornEdges => gs(1.0),
+ F::WaterPaper => 2 * (g("fiberLength") / 6.0) as i32 + 2,
+ F::GlowingEdges => gs(0.3 + g("smoothness") * 0.25) + gs(g("edgeWidth") * 0.4) + 2,
+ F::Craquelure => 0,
+ F::Patchwork => patch_size(e).ceil() as i32 + 2,
+ F::StainedGlass => (glass_cell(e) * 2.5).ceil() as i32 + 2,
+ }
+}
+
+fn cutout_sigma(e: &GalleryEffect) -> f32 {
+ 0.5 + e.get("edgeSimplicity") * (1.1 - 0.3 * e.get("edgeFidelity"))
+}
+fn daubs_radius(e: &GalleryEffect) -> usize {
+ let wide = matches!(e.choice("brushType"), "wideSharp" | "wideBlurry");
+ let r = e.get("brushSize") / 2.0 * if wide { 1.5 } else { 1.0 };
+ r.max(1.0) as usize
+}
+fn plastic_sigma(e: &GalleryEffect) -> f32 {
+ 0.5 + e.get("smoothness") * 0.5 + (15.0 - e.get("detail")) * 0.2
+}
+fn watercolor_radius(e: &GalleryEffect) -> usize {
+ 1 + ((15.0 - e.get("brushDetail")) / 2.5) as usize
+}
+fn basrelief_sigma(e: &GalleryEffect) -> f32 {
+ 0.3 + e.get("smoothness") * 0.5 + (15.0 - e.get("detail")) * 0.12
+}
+fn patch_size(e: &GalleryEffect) -> f32 {
+ 3.0 + e.get("squareSize") * 1.5
+}
+fn glass_cell(e: &GalleryEffect) -> f32 {
+ e.get("cellSize") * 1.6 + 1.0
+}
+
+/// Total reach of a stack of effects.
+pub(crate) fn reach(effects: &[GalleryEffect]) -> i32 {
+ effects.iter().map(effect_reach).sum()
+}
+
+/// Runs a stack of effects over `out` (the source covers `out` grown by [`reach`]).
+pub(crate) fn run(effects: &[GalleryEffect], src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
+ let n = src.ch;
+ let r = src.rect;
+ let (w, h) = (r.width() as usize, r.height() as usize);
+ if effects.is_empty() || w == 0 || h == 0 {
+ return src.crop(out);
+ }
+ let mut win = Win { r, w, h, c: src.data.chunks_exact(n).map(|px| rgb(rgba(ctx, px))).collect() };
+ for e in effects {
+ apply(e, &mut win, ctx);
+ }
+ let mut res = src.crop(out);
+ let ow = out.width() as usize;
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (out.x0 + (i % ow) as i32, out.y0 + (i / ow) as i32);
+ let a = if ctx.alpha { px[n - 1] } else { 1.0 };
+ let c = win.at(x, y);
+ set_rgba(ctx, px, [clamp01(c[0]), clamp01(c[1]), clamp01(c[2]), a]);
+ if ctx.alpha {
+ px[n - 1] = a;
+ }
+ }
+ res
+}
+
+fn apply(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) {
+ let g = |k: &str| e.get(k);
+ let (w, h) = (win.w, win.h);
+ let (fg, bg) = (rgb(e.foreground), rgb(e.background));
+ match e.filter {
+ // ---------------- Artistic ----------------
+ F::ColoredPencil => {
+ let pw = g("pencilWidth");
+ let pressure = g("strokePressure") / 15.0;
+ let paper = map(bg, |v| v * (0.7 + 0.3 * g("paperBrightness") / 50.0));
+ let l = win.lum();
+ let e2 = grad_mag(&l, w, h);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let d = 1.0 - l[i];
+ let h1 = strokes(x, y, (1, 1), 5.0 + pw * 3.0, 0.5 + pw * 0.45, 11);
+ let h2 = strokes(x, y, (1, -1), 5.0 + pw * 3.0, 0.5 + pw * 0.45, 12);
+ let hatch = h1.max(h2 * smoothstep(0.3, 0.8, d));
+ let cov = clamp01(d * (0.55 + pressure) + e2[i] * 3.0 - (1.0 - hatch) * 0.8 + 0.25);
+ win.c[i] = mix(paper, map(win.c[i], |v| v * 0.88), cov);
+ }
+ }
+ F::Cutout => {
+ blur3(&mut win.c, w, h, cutout_sigma(e));
+ let levels = g("numberOfLevels").round();
+ for p in &mut win.c {
+ // Flat tones per luminance level, keeping each region's hue.
+ let l = lum(p).max(1e-4);
+ let k = posterize(l, levels) / l;
+ *p = map(*p, |v| posterize(clamp01(v * k), levels * 2.0));
+ }
+ }
+ F::DryBrush | F::Fresco => {
+ let fresco = e.filter == F::Fresco;
+ kuwahara(win, 1 + g("brushSize") as usize);
+ unsharp(win, 1.0, if fresco { 0.9 } else { 0.5 });
+ let levels = 3.0 + g("brushDetail");
+ let amp = 0.02 + (g("texture") - 1.0) * 0.05;
+ let l = if fresco { grad_mag(&win.lum(), w, h) } else { Vec::new() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = (hash01(x, y, 0, 21) - 0.5) * amp;
+ let mut p = map(win.c[i], |v| posterize(v, levels) * 0.6 + v * 0.4 + n);
+ if fresco {
+ p = map(p, |v| clamp01((v - 0.5) * 1.3 + 0.45).powf(1.15) * (1.0 - clamp01(l[i] * 2.5) * 0.6));
+ }
+ win.c[i] = p;
+ }
+ }
+ F::FilmGrain => {
+ let grain = g("grain") / 20.0;
+ let (area, inten) = (g("highlightArea"), g("intensity"));
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let l = lum(&win.c[i]);
+ let n = (hash01(x, y, 0, 31) - 0.5) * grain * 0.5 * (0.3 + 2.8 * l * (1.0 - l));
+ win.c[i] = highlights(map(win.c[i], |v| v + n), l, area, inten);
+ }
+ }
+ F::NeonGlow => {
+ let size = g("glowSize");
+ let br = g("glowBrightness") / 50.0;
+ let glow = rgb(e.color);
+ let l = win.lum();
+ let mut m: Vec<f32> = if size >= 0.0 { l.clone() } else { l.iter().map(|v| 1.0 - v).collect() };
+ blur1(&mut m, w, h, size.abs() * 0.6 + 0.5);
+ for i in 0..win.c.len() {
+ let base = mix(fg, bg, l[i]);
+ let k = clamp01(m[i] * 1.2) * br * 2.0;
+ win.c[i] = [0, 1, 2].map(|c| 1.0 - (1.0 - base[c]) * (1.0 - clamp01(glow[c] * k)));
+ }
+ }
+ F::PaintDaubs => {
+ let ty = e.choice("brushType");
+ kuwahara(win, daubs_radius(e));
+ let sharp = g("sharpness") / 40.0;
+ match ty {
+ "wideBlurry" => blur3(&mut win.c, w, h, 1.5),
+ "wideSharp" => unsharp(win, 1.5, sharp * 4.0),
+ _ => unsharp(win, 1.2, sharp * 2.5),
+ }
+ if matches!(ty, "lightRough" | "darkRough" | "sparkle") {
+ let edges = if ty == "sparkle" { grad_mag(&win.lum(), w, h) } else { Vec::new() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = fbm(x as f32 / 2.0, y as f32 / 2.0, 41) - 0.5;
+ win.c[i] = match ty {
+ "lightRough" => map(win.c[i], |v| v + n.max(0.0) * 0.35),
+ "darkRough" => map(win.c[i], |v| v * (1.0 - n.max(0.0) * 0.7)),
+ _ => map(win.c[i], |v| v + clamp01(edges[i] * 4.0) * smoothstep(0.75, 0.95, hash01(x, y, 0, 42)) * 0.8),
+ };
+ }
+ }
+ }
+ F::PaletteKnife => {
+ kuwahara(win, (g("strokeSize") / 3.0).max(1.0) as usize);
+ let levels = 2.0 + g("strokeDetail") * 3.0;
+ for p in &mut win.c {
+ *p = map(*p, |v| posterize(v, levels) * 0.5 + v * 0.5);
+ }
+ blur3(&mut win.c, w, h, g("softness") * 0.5);
+ }
+ F::PlasticWrap => {
+ let hs = g("highlightStrength") / 20.0;
+ let mut l = win.lum();
+ blur1(&mut l, w, h, plastic_sigma(e));
+ let (gx, gy) = sobel(&l, w, h);
+ let lv = normalize3([-0.45, -0.65, 1.0]);
+ let hv = normalize3([lv[0], lv[1], lv[2] + 1.0]);
+ for i in 0..win.c.len() {
+ let k = 14.0;
+ let n = normalize3([-k * gx[i], -k * gy[i], 1.0]);
+ let ndh = (n[0] * hv[0] + n[1] * hv[1] + n[2] * hv[2]).max(0.0);
+ let tilt = 1.0 - n[2];
+ let spec = ndh.powf(30.0) * smoothstep(0.01, 0.12, tilt) + smoothstep(0.25, 0.6, tilt) * 0.25;
+ win.c[i] = map(win.c[i], |v| v * 0.88 + spec * hs * 1.3);
+ }
+ }
+ F::PosterEdges => {
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 0.6 + g("edgeThickness") * 0.6);
+ let edge = grad_mag(&l, w, h);
+ let inten = g("edgeIntensity") / 10.0;
+ let levels = g("posterization") + 2.0;
+ for i in 0..win.c.len() {
+ let ink = smoothstep(0.015, 0.06, edge[i] * (1.0 + inten * 3.0)) * (0.55 + inten * 0.45);
+ win.c[i] = map(win.c[i], |v| posterize(v, levels) * (1.0 - ink));
+ }
+ }
+ F::RoughPastels => {
+ let len = g("strokeLength");
+ let det = g("strokeDetail") / 20.0;
+ let orig = win.c.clone();
+ line_blur3(&mut win.c, w, h, (1, -1), (len / 2.0) as usize);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = strokes(x, y, (1, -1), 3.0 + len * 0.8, 1.1, 51) - 0.5;
+ let p = mix(win.c[i], orig[i], det * 0.5);
+ win.c[i] = map(p, |v| v + n * 0.3);
+ }
+ texturize(win, e.choice("texture"), g("scaling"), g("relief"), e.choice("light"), e.flag("invert"));
+ }
+ F::SmudgeStick => {
+ line_blur3(&mut win.c, w, h, (1, 1), (g("strokeLength") * 1.5) as usize);
+ let (area, inten) = (g("highlightArea"), g("intensity"));
+ for p in &mut win.c {
+ let l = lum(p);
+ let q = map(*p, |v| v * (0.7 + 0.3 * l));
+ *p = highlights(q, l, area, inten);
+ }
+ }
+ F::Sponge => {
+ kuwahara(win, 1 + g("brushSize") as usize);
+ let def = g("definition") / 25.0;
+ let sc = 1.5 + g("smoothness") * 0.5;
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let s = fbm(x as f32 / sc, y as f32 / sc, 61);
+ let hole = smoothstep(0.58, 0.75, s);
+ win.c[i] = map(win.c[i], |v| clamp01((v - 0.5) * (1.0 + def * 0.6) + 0.5) * (1.0 - hole * def * 0.4));
+ }
+ }
+ F::Underpainting => {
+ let orig = win.c.clone();
+ blur3(&mut win.c, w, h, 0.5 + g("brushSize") * 0.4);
+ for (p, o) in win.c.iter_mut().zip(&orig) {
+ *p = saturate(mix(*o, *p, 0.8), 1.15);
+ }
+ let cov = g("textureCoverage") / 40.0;
+ texturize(win, e.choice("texture"), g("scaling"), g("relief") * (0.5 + cov * 1.5), e.choice("light"), e.flag("invert"));
+ }
+ F::Watercolor => {
+ kuwahara(win, watercolor_radius(e));
+ let sh = g("shadowIntensity") / 10.0;
+ let edge = grad_mag(&win.lum(), w, h);
+ let amp = (g("texture") - 1.0) * 0.04;
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = (fbm(x as f32 / 3.0, y as f32 / 3.0, 71) - 0.5) * amp;
+ let k = 1.0 - clamp01(edge[i] * (3.0 + sh * 8.0)) * 0.6;
+ win.c[i] = map(saturate(win.c[i], 1.2), |v| clamp01(v * k + n).powf(1.1 + sh * 0.6));
+ }
+ }
+ // ---------------- Brush Strokes ----------------
+ F::AccentedEdges => {
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 0.4 + g("smoothness") * 0.3);
+ let mut edge = grad_mag(&l, w, h);
+ blur1(&mut edge, w, h, g("edgeWidth") * 0.5);
+ let eb = g("edgeBrightness") / 50.0;
+ for i in 0..win.c.len() {
+ let k = clamp01(edge[i] * 6.0);
+ win.c[i] = if eb >= 0.5 { map(win.c[i], |v| v + (1.0 - v) * k * (eb - 0.5) * 2.0) } else { map(win.c[i], |v| v * (1.0 - k * (0.5 - eb) * 2.0)) };
+ }
+ }
+ F::AngledStrokes | F::Crosshatch => {
+ let len = g("strokeLength");
+ let r = (len / 3.0) as usize;
+ if e.filter == F::Crosshatch {
+ let st = g("strength");
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = (hash01(x, y, 0, 81) - 0.5) * 0.12 * st;
+ win.c[i] = map(win.c[i], |v| v + n);
+ }
+ }
+ let l = win.lum();
+ let mut a = win.c.clone();
+ line_blur3(&mut a, w, h, (1, 1), r);
+ line_blur3(&mut win.c, w, h, (1, -1), r);
+ if e.filter == F::AngledStrokes {
+ let bal = g("directionBalance") / 100.0;
+ for i in 0..win.c.len() {
+ win.c[i] = mix(a[i], win.c[i], smoothstep(1.0 - bal - 0.15, 1.0 - bal + 0.15, l[i]));
+ }
+ unsharp(win, 1.0, g("sharpness") / 10.0 * 1.5);
+ } else {
+ for i in 0..win.c.len() {
+ win.c[i] = mix(a[i], win.c[i], 0.5);
+ }
+ unsharp(win, 1.0, g("sharpness") / 20.0 * 3.0);
+ }
+ }
+ F::DarkStrokes => {
+ let (bal, bi, wi) = (g("balance") / 10.0, g("blackIntensity") / 10.0, g("whiteIntensity") / 10.0);
+ let l = win.lum();
+ let mut a = win.c.clone();
+ line_blur3(&mut a, w, h, (1, 1), 3);
+ line_blur3(&mut win.c, w, h, (1, -1), 8);
+ let t = 0.25 + bal * 0.5;
+ for i in 0..win.c.len() {
+ let d = map(a[i], |v| v * (1.0 - bi * 0.85));
+ let li = map(win.c[i], |v| v + (1.0 - v) * wi * 0.5);
+ win.c[i] = mix(d, li, smoothstep(t - 0.1, t + 0.1, l[i]));
+ }
+ }
+ F::InkOutlines => {
+ let (di, li) = (g("darkIntensity") / 50.0, g("lightIntensity") / 50.0);
+ let l = win.lum();
+ let edge = grad_mag(&l, w, h);
+ line_blur3(&mut win.c, w, h, (1, 1), (g("strokeLength") / 2.0) as usize);
+ for i in 0..win.c.len() {
+ let ink = clamp01(edge[i] * 5.0) * di * 1.5;
+ let (lt, dk) = (smoothstep(0.5, 1.0, l[i]) * li, smoothstep(0.5, 0.0, l[i]) * di * 0.8);
+ win.c[i] = map(win.c[i], |v| (v + (1.0 - v) * lt) * (1.0 - dk) * (1.0 - clamp01(ink)));
+ }
+ }
+ F::Spatter | F::SprayedStrokes => {
+ let rad = g("sprayRadius");
+ let sc = if e.filter == F::Spatter { 0.6 + g("smoothness") * 0.25 } else { 1.2 };
+ let src = Win { r: win.r, w, h, c: win.c.clone() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 / sc, y as f32 / sc);
+ let dx = (vnoise(fx, fy, 91) - 0.5) * 2.0 * rad;
+ let dy = (vnoise(fx, fy, 92) - 0.5) * 2.0 * rad;
+ win.c[i] = src.sample(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy);
+ }
+ if e.filter == F::SprayedStrokes {
+ line_blur3(&mut win.c, w, h, direction(e.choice("strokeDirection")), (g("strokeLength") / 2.0) as usize);
+ }
+ }
+ F::SumiE => {
+ let sw = g("strokeWidth");
+ let (pr, con) = (g("strokePressure") / 15.0, g("contrast") / 40.0);
+ blur3(&mut win.c, w, h, sw * 0.2);
+ line_blur3(&mut win.c, w, h, (1, 1), (sw / 2.0) as usize);
+ for p in &mut win.c {
+ let l = lum(p);
+ let ink = smoothstep(0.65, 0.15, l).powf(1.0 - pr * 0.5);
+ *p = map(*p, |v| clamp01((v - 0.5) * (1.0 + con) + 0.5) * (1.0 - ink * 0.9 * (0.5 + con)));
+ }
+ }
+ // ---------------- Distort ----------------
+ F::DiffuseGlow => {
+ let (gr, ga, ca) = (g("graininess") / 10.0, g("glowAmount") / 20.0, g("clearAmount") / 20.0);
+ let thr = 0.2 + ca * 0.7;
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let l = lum(&win.c[i]);
+ let mut m = smoothstep(thr - 0.3, thr + 0.1, l) * ga * 1.4;
+ if hash01(x, y, 0, 101) < gr * 0.3 * (m + 0.15) {
+ m += 0.5;
+ }
+ win.c[i] = mix(win.c[i], bg, clamp01(m));
+ }
+ }
+ F::Glass => {
+ let dist = g("distortion");
+ let step = 0.5 + g("smoothness") * 0.5;
+ let kind = e.choice("texture");
+ let s = (g("scaling") / 100.0).clamp(0.5, 2.0);
+ let sign = if e.flag("invert") { -1.0 } else { 1.0 };
+ let max = dist * 2.0;
+ let src = Win { r: win.r, w, h, c: win.c.clone() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32, y as f32);
+ let gx = texture(kind, fx + step, fy, s) - texture(kind, fx - step, fy, s);
+ let gy = texture(kind, fx, fy + step, s) - texture(kind, fx, fy - step, s);
+ let dx = (gx * sign * dist * 3.0).clamp(-max, max);
+ let dy = (gy * sign * dist * 3.0).clamp(-max, max);
+ win.c[i] = src.sample(fx + 0.5 + dx, fy + 0.5 + dy);
+ }
+ }
+ F::OceanRipple => {
+ let s = 2.0 + g("rippleSize") * 1.2;
+ let mag = g("rippleMagnitude") * 0.9;
+ let src = Win { r: win.r, w, h, c: win.c.clone() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 / s, y as f32 / s);
+ let dx = (vnoise(fx, fy, 111) - 0.5) * 2.0 * mag;
+ let dy = (vnoise(fx, fy, 112) - 0.5) * 2.0 * mag;
+ win.c[i] = src.sample(x as f32 + 0.5 + dx, y as f32 + 0.5 + dy);
+ }
+ }
+ // ---------------- Sketch ----------------
+ F::BasRelief => {
+ let mut l = win.lum();
+ let orig = l.clone();
+ blur1(&mut l, w, h, basrelief_sigma(e));
+ let (gx, gy) = sobel(&l, w, h);
+ let lt = light_dir(e.choice("light"));
+ let k = 3.0 + g("detail") * 0.4;
+ for i in 0..win.c.len() {
+ let t = clamp01(orig[i] * 0.5 + 0.25 + k * -(gx[i] * lt.0 + gy[i] * lt.1));
+ win.c[i] = mix(fg, bg, t);
+ }
+ }
+ F::ChalkCharcoal => {
+ let (ca, ch, pr) = (g("charcoalArea") / 20.0, g("chalkArea") / 20.0, g("strokePressure") / 5.0);
+ let mid = mix(fg, bg, 0.5);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let l = lum(&win.c[i]);
+ let cn = strokes(x, y, (1, 1), 9.0, 0.9, 121) - 0.5;
+ let kn = strokes(x, y, (1, -1), 9.0, 0.9, 122) - 0.5;
+ let cc = smoothstep(0.25, 0.6, (1.0 - l) * (0.4 + ca * 1.2) + cn * (0.6 + pr * 0.4) - 0.15);
+ let kc = smoothstep(0.25, 0.6, l * (0.4 + ch * 1.2) + kn * (0.6 + pr * 0.4) - 0.15);
+ win.c[i] = mix(mix(mid, fg, cc), bg, kc * (1.0 - cc));
+ }
+ }
+ F::Charcoal => {
+ let (th, det, bal) = (g("charcoalThickness"), g("detail") / 5.0, g("lightDarkBalance") / 100.0);
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 1.0);
+ let edge = grad_mag(&l, w, h);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let sn = strokes(x, y, (1, 1), 8.0 + th * 3.0, 0.6 + th * 0.5, 131) - 0.5;
+ let cov = smoothstep(1.0 - bal - 0.2, 1.0 - bal + 0.2, 1.0 - l[i] + sn * 0.6) + clamp01(edge[i] * det * 6.0);
+ win.c[i] = mix(bg, fg, clamp01(cov));
+ }
+ }
+ F::Chrome => {
+ let (det, sm) = (g("detail") / 10.0, g("smoothness") / 10.0);
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 1.0 + sm * 4.0);
+ let edge = grad_mag(&l, w, h);
+ for i in 0..win.c.len() {
+ let v = 0.5 + 0.5 * ((l[i] * (2.5 + det * 3.0) + edge[i] * 6.0) * 2.0 * PI).sin();
+ win.c[i] = grey(smoothstep(0.05, 0.95, v));
+ }
+ }
+ F::ConteCrayon => {
+ let (fl, bl) = (g("foregroundLevel") / 15.0, g("backgroundLevel") / 15.0);
+ let mid = mix(fg, bg, 0.5);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let l = lum(&win.c[i]);
+ let sn = strokes(x, y, (1, -1), 7.0, 1.0, 141) - 0.5;
+ let cf = clamp01((0.6 - l) * 2.0 * fl * 1.4 + sn * 0.5);
+ let cb = clamp01((l - 0.4) * 2.0 * bl * 1.4 - sn * 0.5);
+ win.c[i] = mix(mix(mid, fg, cf), bg, cb * (1.0 - cf));
+ }
+ texturize(win, e.choice("texture"), g("scaling"), g("relief"), e.choice("light"), e.flag("invert"));
+ }
+ F::GraphicPen => {
+ let r = (g("strokeLength") / 2.0) as usize;
+ let bal = g("lightDarkBalance") / 100.0;
+ let l = win.lum();
+ let mut n: Vec<f32> = (0..win.c.len()).map(|i| {
+ let (x, y) = win.xy(i);
+ hash01(x, y, 0, 151)
+ }).collect();
+ line_blur(&mut n, 1, w, h, direction(e.choice("strokeDirection")), r);
+ let sd = 0.2887 / ((2 * r + 1) as f32).sqrt();
+ for i in 0..win.c.len() {
+ let z = (n[i] - 0.5) / sd;
+ let t = l[i] + z * 0.16;
+ win.c[i] = mix(bg, fg, smoothstep(bal + 0.04, bal - 0.04, t));
+ }
+ }
+ F::HalftonePattern => {
+ let size = g("size");
+ let con = g("contrast") / 50.0;
+ let cell = 3.0 + size * 2.0;
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 0.5 + size * 0.3);
+ let b = ctx.bounds;
+ let (cx, cy) = ((b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0);
+ let ty = e.choice("patternType");
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let d = clamp01((1.0 - l[i] - 0.5) * (1.0 + con * 3.0) + 0.5);
+ let aa = 1.0 / cell;
+ let ink = match ty {
+ "circle" => {
+ let r = ((fx - cx).powi(2) + (fy - cy).powi(2)).sqrt() / cell;
+ let q = (r.fract() - 0.5).abs() * 2.0;
+ smoothstep(d + aa, d - aa, q)
+ }
+ "line" => {
+ let q = ((fy / cell).fract() - 0.5).abs() * 2.0;
+ smoothstep(d + aa, d - aa, q)
+ }
+ _ => {
+ let (u, v) = ((fx / cell).fract() - 0.5, (fy / cell).fract() - 0.5);
+ let q = (u * u + v * v).sqrt() * 2.0;
+ let rr = d.sqrt() * 1.15;
+ smoothstep(rr + aa, rr - aa, q)
+ }
+ };
+ win.c[i] = mix(bg, fg, ink);
+ }
+ }
+ F::NotePaper => {
+ let (bal, gr, rel) = (g("imageBalance") / 50.0, g("graininess") / 20.0, g("relief") / 25.0);
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 1.0);
+ let mut m: Vec<f32> = l.iter().map(|&v| smoothstep(bal - 0.05, bal + 0.05, v)).collect();
+ blur1(&mut m, w, h, 1.2);
+ let (gx, gy) = sobel(&m, w, h);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = (hash01(x, y, 0, 161) - 0.5) * gr * 0.3;
+ let f = shade(gx[i], gy[i], light_dir("topLeft"), rel * 6.0).clamp(0.0, 2.0);
+ win.c[i] = map(mix(fg, bg, m[i]), |v| (v + n) * f);
+ }
+ }
+ F::Photocopy => {
+ let (det, dk) = (g("detail"), g("darkness") / 50.0);
+ let l = win.lum();
+ let mut b = l.clone();
+ blur1(&mut b, w, h, 1.0 + det * 0.5);
+ for i in 0..win.c.len() {
+ let hp = l[i] - b[i];
+ let ink = smoothstep(0.0, 0.06, -hp * (1.0 + dk * 8.0)) + smoothstep(0.35, 0.05, l[i]) * dk * 1.5;
+ win.c[i] = mix(bg, fg, clamp01(ink));
+ }
+ }
+ F::Plaster => {
+ let bal = g("imageBalance") / 50.0;
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 0.5 + g("smoothness") * 0.8);
+ let mut m: Vec<f32> = l.iter().map(|&v| smoothstep(bal + 0.1, bal - 0.1, v)).collect();
+ blur1(&mut m, w, h, 1.5);
+ let (gx, gy) = sobel(&m, w, h);
+ let lt = light_dir(e.choice("light"));
+ for i in 0..win.c.len() {
+ let f = shade(gx[i], gy[i], lt, 6.0).clamp(0.0, 2.0);
+ win.c[i] = map(mix(bg, fg, m[i] * 0.6), |v| v * f);
+ }
+ }
+ F::Reticulation => {
+ let (den, fl, bl) = (g("density") / 50.0, g("foregroundLevel") / 50.0, g("backgroundLevel") / 50.0);
+ let ink_c = mix(bg, fg, 0.3 + fl * 0.7);
+ let paper = mix(bg, fg, bl * 0.6);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let n = 0.5 * hash01(x, y, 0, 171) + 0.5 * vnoise(x as f32 / 1.8, y as f32 / 1.8, 172);
+ let t = (1.0 - lum(&win.c[i])) + (n - 0.5) * (0.4 + den * 1.2);
+ win.c[i] = mix(paper, ink_c, smoothstep(0.45, 0.55, t));
+ }
+ }
+ F::Stamp => {
+ let bal = g("lightDarkBalance") / 50.0;
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 0.3 + g("smoothness") * 0.3);
+ for i in 0..win.c.len() {
+ win.c[i] = mix(bg, fg, smoothstep(bal + 0.02, bal - 0.02, l[i]));
+ }
+ }
+ F::TornEdges => {
+ let (bal, sm, con) = (g("imageBalance") / 50.0, g("smoothness"), g("contrast"));
+ let mut l = win.lum();
+ blur1(&mut l, w, h, 1.0);
+ let rough = (16.0 - sm) / 15.0 * 0.35;
+ let aa = 0.25 / con;
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let t = l[i] + (fbm(x as f32 / 2.0, y as f32 / 2.0, 181) - 0.5) * rough;
+ win.c[i] = mix(bg, fg, smoothstep(bal + aa, bal - aa, t));
+ }
+ }
+ F::WaterPaper => {
+ let fl = g("fiberLength");
+ let (br, co) = (g("brightness") / 100.0, g("contrast") / 100.0);
+ let r = (fl / 6.0) as usize;
+ line_blur3(&mut win.c, w, h, (1, 0), r);
+ line_blur3(&mut win.c, w, h, (0, 1), r);
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let fib = strokes(x, y, (1, 0), fl, 1.0, 191).max(strokes(x, y, (0, 1), fl, 1.0, 192));
+ win.c[i] = map(win.c[i], |v| (v * (0.85 + 0.25 * fib) - 0.5) * (co * 1.6 + 0.2) + 0.5 + (br - 0.5) * 0.8);
+ }
+ }
+ // ---------------- Stylize ----------------
+ F::GlowingEdges => {
+ blur3(&mut win.c, w, h, 0.3 + g("smoothness") * 0.25);
+ let mut e3 = vec![[0.0f32; 3]; win.c.len()];
+ for c in 0..3 {
+ let plane: Vec<f32> = win.c.iter().map(|p| p[c]).collect();
+ for (o, v) in e3.iter_mut().zip(grad_mag(&plane, w, h)) {
+ o[c] = v;
+ }
+ }
+ blur3(&mut e3, w, h, g("edgeWidth") * 0.4);
+ let k = 2.0 + g("edgeBrightness") * 1.2;
+ for (p, q) in win.c.iter_mut().zip(&e3) {
+ *p = map(*q, |v| clamp01(v * k));
+ }
+ }
+ // ---------------- Texture ----------------
+ F::Craquelure => {
+ let (sp, dep, bri) = (g("crackSpacing"), g("crackDepth") / 10.0, g("crackBrightness") / 10.0);
+ let cell = sp * 1.3 + 1.0;
+ let width = 0.8 + dep * 0.8;
+ let crack = |x: f32, y: f32| {
+ let (d1, d2, _) = voronoi(x, y, cell, 201);
+ 1.0 - smoothstep(0.0, width, d2 - d1)
+ };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let c0 = crack(fx, fy);
+ let (gx, gy) = (crack(fx + 1.0, fy) - c0, crack(fx, fy + 1.0) - c0);
+ let f = shade(-gx, -gy, light_dir("topLeft"), dep * 2.0).clamp(0.0, 2.0);
+ win.c[i] = map(win.c[i], |v| v * (0.55 + bri * 0.5) * (1.0 - c0 * dep * 0.6) * f);
+ }
+ }
+ F::Grain => {
+ let (it, co) = (g("intensity") / 100.0, g("contrast") / 100.0);
+ let ty = e.choice("grainType");
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let hc = |c: u32| hash01(x, y, c, 211) - 0.5;
+ let p = win.c[i];
+ let q = match ty {
+ "soft" => [p[0] + hc(0) * it * 0.4, p[1] + hc(1) * it * 0.4, p[2] + hc(2) * it * 0.4],
+ "sprinkles" => {
+ if hash01(x, y, 3, 211) < it * 0.15 { bg } else { p }
+ }
+ "clumped" => map(p, |v| v + (vnoise(x as f32 / 2.0, y as f32 / 2.0, 212) - 0.5) * it * 1.2),
+ "contrasty" => map(p, |v| (v - 0.5) * (1.0 + it * 2.0) + 0.5 + hc(4) * it * 0.5),
+ "enlarged" => {
+ let (fx, fy) = (x as f32 / 3.0, y as f32 / 3.0);
+ [p[0] + (vnoise(fx, fy, 213) - 0.5) * it, p[1] + (vnoise(fx, fy, 214) - 0.5) * it, p[2] + (vnoise(fx, fy, 215) - 0.5) * it]
+ }
+ "stippled" => {
+ let st = if lum(&p) > hash01(x, y, 5, 211) { bg } else { fg };
+ mix(p, st, 0.3 + it * 0.7)
+ }
+ "horizontal" => map(p, |v| v + (vnoise(x as f32 / 25.0, y as f32, 216) - 0.5) * it),
+ "vertical" => map(p, |v| v + (vnoise(x as f32, y as f32 / 25.0, 217) - 0.5) * it),
+ "speckle" => {
+ if hash01(x, y, 6, 211) < it * 0.1 { mix(p, fg, 0.85) } else { p }
+ }
+ _ => [p[0] + hc(0) * it * 0.8, p[1] + hc(1) * it * 0.8, p[2] + hc(2) * it * 0.8],
+ };
+ win.c[i] = map(q, |v| (v - 0.5) * (0.5 + co) + 0.5);
+ }
+ }
+ F::MosaicTiles => {
+ let (ts, gw, lg) = (g("tileSize"), g("groutWidth"), g("lightenGrout") / 10.0);
+ let edge = |x: f32, y: f32| {
+ let jx = x + (vnoise(x / ts * 0.7, y / ts * 0.7, 221) - 0.5) * ts * 0.3;
+ let jy = y + (vnoise(x / ts * 0.7, y / ts * 0.7, 222) - 0.5) * ts * 0.3;
+ let (u, v) = (jx.rem_euclid(ts), jy.rem_euclid(ts));
+ u.min(ts - u).min(v.min(ts - v))
+ };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let de = edge(fx, fy);
+ let grout = smoothstep(gw * 0.5 + 0.7, gw * 0.5 - 0.3, de);
+ let hgt = |xx: f32, yy: f32| smoothstep(gw * 0.5, gw * 0.5 + 2.5, edge(xx, yy));
+ let s = (hgt(fx - 1.0, fy - 1.0) - hgt(fx + 1.0, fy + 1.0)) * 0.35;
+ let l = lum(&win.c[i]);
+ let gc = grey(clamp01(l * 0.5 + lg * 0.45));
+ win.c[i] = mix(map(win.c[i], |v| v * (1.0 + s)), gc, grout);
+ }
+ }
+ F::Patchwork => {
+ let size = patch_size(e);
+ let rel = g("relief") / 25.0;
+ let src = Win { r: win.r, w, h, c: win.c.clone() };
+ let hv = |x: f32, y: f32| {
+ let (bx, by) = ((x / size).floor() as i32, (y / size).floor() as i32);
+ let (u, v) = (x.rem_euclid(size), y.rem_euclid(size));
+ let bevel = smoothstep(0.0, 1.5, u.min(size - u).min(v.min(size - v)));
+ hash01(bx, by, 0, 231) * bevel
+ };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (bx, by) = ((fx / size).floor(), (fy / size).floor());
+ let c = src.at(((bx + 0.5) * size) as i32, ((by + 0.5) * size) as i32);
+ let s = (hv(fx - 1.0, fy - 1.0) - hv(fx + 1.0, fy + 1.0)) * rel * 1.5;
+ win.c[i] = map(c, |v| v * (1.0 + s));
+ }
+ }
+ F::StainedGlass => {
+ let cell = glass_cell(e);
+ let bt = g("borderThickness");
+ let li = g("lightIntensity") / 10.0;
+ let b = ctx.bounds;
+ let (cx, cy) = ((b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0);
+ let half = (b.width().max(b.height()) as f32 / 2.0).max(1.0);
+ let src = Win { r: win.r, w, h, c: win.c.clone() };
+ for i in 0..win.c.len() {
+ let (x, y) = win.xy(i);
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let (d1, d2, p) = voronoi(fx, fy, cell, 241);
+ let border = smoothstep(bt * 0.5 + 0.6, bt * 0.5 - 0.4, (d2 - d1) * 0.5);
+ let dn = (((fx - cx).powi(2) + (fy - cy).powi(2)).sqrt() / half).min(1.0);
+ let col = map(src.at(p.0 as i32, p.1 as i32), |v| v * (1.0 + li * 0.6 * (1.0 - dn)));
+ win.c[i] = mix(col, fg, border);
+ }
+ }
+ F::Texturizer => texturize(win, e.choice("texture"), g("scaling"), g("relief"), e.choice("light"), e.flag("invert")),
+ }
+}
+
+fn normalize3(v: [f32; 3]) -> [f32; 3] {
+ let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-9);
+ [v[0] / l, v[1] / l, v[2] / l]
+}
+
+#[cfg(test)]
+mod tests {
+ use photocraft_color::{ColorMode, PixelFormat, SampleType};
+ use photocraft_raster::Surface;
+
+ use super::*;
+ use crate::{FilterParams, apply_tiled};
+
+ fn pattern(st: SampleType) -> Surface {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true));
+ for y in 0..40 {
+ for x in 0..56 {
+ let v = ((x * 7 + y * 3) % 23) as f32 / 22.0;
+ let px = if (x / 9 + y / 7) % 2 == 0 { [v, 0.3, 1.0 - v, 1.0] } else { [0.9, v * 0.5, 0.2, 1.0] };
+ s.write_pixel(x, y, &px);
+ }
+ }
+ s
+ }
+
+ #[test]
+ fn every_effect_changes_pixels_and_is_tile_independent() {
+ let b = Rect::new(0, 0, 56, 40);
+ for st in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let s = pattern(st);
+ let before = s.read_region(b);
+ for f in crate::GalleryFilter::ALL {
+ let fp = FilterParams::FilterGallery { effects: vec![GalleryEffect::new(*f)] };
+ let a = apply_tiled(&s, &fp, b, b, None, 256, Some(b)).read_region(b);
+ assert_ne!(a, before, "{} @{st:?} changed nothing", f.key());
+ assert!(a.iter().all(|v| v.is_finite()), "{}", f.key());
+ if st == SampleType::F32 {
+ let t = apply_tiled(&s, &fp, b, b, None, 16, Some(b)).read_region(b);
+ let worst = a.iter().zip(&t).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
+ assert!(worst < 1e-3, "{} differs across tilings by {worst}", f.key());
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn params_parse_and_clamp() {
+ for f in crate::GalleryFilter::ALL {
+ assert!(!f.params().is_empty(), "{}", f.key());
+ assert_eq!(crate::GalleryFilter::from_key(f.key()), Some(*f));
+ assert_eq!(crate::GalleryFilter::from_key(f.command_id()), Some(*f));
+ }
+ assert_eq!(crate::GalleryFilter::ALL.len(), 47);
+ let mut e = GalleryEffect::new(crate::GalleryFilter::Texturizer);
+ assert_eq!(e.choice("texture"), "canvas");
+ assert_eq!(e.choice("light"), "top");
+ assert!(e.set_choice("texture", "brick"));
+ assert_eq!(e.choice("texture"), "brick");
+ e.set("relief", 500.0);
+ assert_eq!(e.get("relief"), 50.0);
+ }
+
+ /// Release timing on 24 MP: `cargo test -p photocraft-algo --release bench_gallery -- --ignored --nocapture`.
+ #[test]
+ #[ignore]
+ fn bench_gallery() {
+ let (w, h) = (6000, 4000);
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
+ let b = Rect::new(0, 0, w, h);
+ s.fill_rect(b, &[0.5, 0.4, 0.3, 1.0]);
+ for y in (0..h).step_by(9) {
+ s.fill_rect(Rect::new(0, y, w, y + 3), &[0.9, 0.8, 0.2, 1.0]);
+ }
+ let t = std::time::Instant::now();
+ std::hint::black_box(crate::apply_in(&s, &FilterParams::AddNoise { amount: 10.0, distribution: crate::Distribution::Uniform, monochromatic: true, seed: 1 }, b, b, None, b));
+ println!("{:>18}: {:>7.0} ms", "(addNoise baseline)", t.elapsed().as_secs_f64() * 1000.0);
+ let mut total = 0.0;
+ for f in crate::GalleryFilter::ALL {
+ let fp = FilterParams::FilterGallery { effects: vec![GalleryEffect::new(*f)] };
+ let t = std::time::Instant::now();
+ std::hint::black_box(crate::apply_in(&s, &fp, b, b, None, b));
+ let ms = t.elapsed().as_secs_f64() * 1000.0;
+ total += ms;
+ println!("{:>18}: {ms:>7.0} ms", f.key());
+ }
+ println!("{:>18}: {total:>7.0} ms", "total");
+ }
+
+ /// Visual check: `GALLERY_RAW=src.raw GALLERY_W=480 GALLERY_H=322 cargo test -p photocraft-algo --release gallery_sheet -- --ignored`
+ /// writes `<key>.raw` (RGB8) beside the input for every filter.
+ #[test]
+ #[ignore]
+ fn gallery_sheet() {
+ let Ok(path) = std::env::var("GALLERY_RAW") else { return };
+ let w: i32 = std::env::var("GALLERY_W").unwrap().parse().unwrap();
+ let h: i32 = std::env::var("GALLERY_H").unwrap().parse().unwrap();
+ let bytes = std::fs::read(&path).unwrap();
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
+ let data: Vec<f32> = bytes.chunks(3).flat_map(|c| [c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0]).collect();
+ let b = Rect::new(0, 0, w, h);
+ s.write_region(b, &data);
+ let dir = std::path::Path::new(&path).parent().unwrap().to_path_buf();
+ for f in crate::GalleryFilter::ALL {
+ let fp = FilterParams::FilterGallery { effects: vec![GalleryEffect::new(*f)] };
+ let out = crate::apply_in(&s, &fp, b, b, None, b).read_region(b);
+ let raw: Vec<u8> = out.chunks(4).flat_map(|p| [p[0], p[1], p[2]].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect();
+ std::fs::write(dir.join(format!("{}.raw", f.key())), raw).unwrap();
+ }
+ }
+}
diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs
new file mode 100644
index 000000000..c29fc8e81
--- /dev/null
+++ b/crates/algo/src/camera_raw.rs
@@ -0,0 +1,932 @@
+//! Filter › Camera Raw Filter: a float develop pipeline over RGB pixels.
+//!
+//! Stages, in order (each skipped when its controls are neutral, so defaults are an identity):
+//!
+//! 1. **White balance and exposure** in linear light (the document's values decoded with the sRGB
+//! curve as a perceptual working encoding; encoding is undone exactly at the end).
+//! 2. **Dehaze**: K. He, J. Sun, X. Tang, *Single Image Haze Removal Using Dark Channel Prior*,
+//! CVPR 2009 (dark channel, atmospheric light from its brightest 0.1 %, transmission refined
+//! with the guided filter); negative amounts add haze toward the atmospheric light.
+//! 3. **Tone** on luminance with colour ratios kept: Highlights / Shadows as exposure changes
+//! weighted by an edge-preserving base layer (guided filter: K. He, J. Sun, X. Tang, *Guided
+//! Image Filtering*, ECCV 2010), so local contrast survives; Whites / Blacks move the ends of
+//! the curve; Contrast is an S-curve about middle grey; Clarity (large radius, midtone
+//! weighted) and Texture (small radius) add band-pass local contrast.
+//! 4. **Presence**: Vibrance (weighted toward less saturated colours) and Saturation.
+//! 5. **Tone Curve**: parametric regions (Highlights, Lights, Darks, Shadows with movable splits)
+//! then point curves (master and per channel), monotone cubic interpolation (F. Fritsch,
+//! R. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 1980).
+//! 6. **Color Mixer (HSL)**: eight hue bands (red, orange, yellow, green, aqua, blue, purple,
+//! magenta) with hat-function weights on the hue circle.
+//! 7. **Color Grading**: shadows / midtones / highlights / global wheels (hue, saturation,
+//! luminance) with Blending and Balance.
+//! 8. **Detail**: sharpening on luminance (unsharp mask with Detail as halo control and Masking as
+//! an edge mask) and noise reduction (luminance by guided filter, colour by chroma blur).
+//! 9. **Effects**: post-crop vignette (amount, midpoint, roundness, feather, highlights,
+//! style) and grain (amount, size, roughness; position-hashed, deterministic).
+
+#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels)
+
+use serde::{Deserialize, Serialize};
+
+use crate::photo_util::{hash01, linear_to_srgb, par_rows, srgb_to_linear};
+
+/// One colour grading wheel.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]
+#[serde(default)]
+pub struct Wheel {
+ /// Degrees 0..360.
+ pub hue: f32,
+ /// 0..=100.
+ pub sat: f32,
+ /// −100..=100.
+ pub lum: f32,
+}
+
+impl Wheel {
+ fn neutral(&self) -> bool {
+ self.sat == 0.0 && self.lum == 0.0
+ }
+}
+
+/// Camera Raw settings in Adobe Camera Raw's slider units.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct CameraRaw {
+ // Basic
+ pub temperature: f32,
+ pub tint: f32,
+ pub exposure: f32,
+ pub contrast: f32,
+ pub highlights: f32,
+ pub shadows: f32,
+ pub whites: f32,
+ pub blacks: f32,
+ pub texture: f32,
+ pub clarity: f32,
+ pub dehaze: f32,
+ pub vibrance: f32,
+ pub saturation: f32,
+ // Tone curve
+ pub curve_highlights: f32,
+ pub curve_lights: f32,
+ pub curve_darks: f32,
+ pub curve_shadows: f32,
+ /// Region splits (percent).
+ pub curve_splits: [f32; 3],
+ /// Point curves as `[input, output]` in 0..=255 (empty = linear).
+ pub point_curve: Vec<[f32; 2]>,
+ pub point_curve_red: Vec<[f32; 2]>,
+ pub point_curve_green: Vec<[f32; 2]>,
+ pub point_curve_blue: Vec<[f32; 2]>,
+ // Color mixer: red, orange, yellow, green, aqua, blue, purple, magenta.
+ pub hsl_hue: [f32; 8],
+ pub hsl_sat: [f32; 8],
+ pub hsl_lum: [f32; 8],
+ // Color grading
+ pub grade_shadows: Wheel,
+ pub grade_midtones: Wheel,
+ pub grade_highlights: Wheel,
+ pub grade_global: Wheel,
+ pub grade_blending: f32,
+ pub grade_balance: f32,
+ // Detail
+ pub sharpen_amount: f32,
+ pub sharpen_radius: f32,
+ pub sharpen_detail: f32,
+ pub sharpen_masking: f32,
+ pub noise_luminance: f32,
+ pub noise_luminance_detail: f32,
+ pub noise_color: f32,
+ pub noise_color_detail: f32,
+ // Effects
+ pub grain_amount: f32,
+ pub grain_size: f32,
+ pub grain_roughness: f32,
+ pub vignette_amount: f32,
+ pub vignette_midpoint: f32,
+ pub vignette_roundness: f32,
+ pub vignette_feather: f32,
+ pub vignette_highlights: f32,
+ /// `highlightPriority | colorPriority | paintOverlay`.
+ pub vignette_style: String,
+ pub seed: u32,
+ /// Pixel-size multiplier for previews on downsampled proxies (radii in px scale by it).
+ pub pixel_scale: f32,
+}
+
+impl Default for CameraRaw {
+ fn default() -> Self {
+ CameraRaw {
+ temperature: 0.0,
+ tint: 0.0,
+ exposure: 0.0,
+ contrast: 0.0,
+ highlights: 0.0,
+ shadows: 0.0,
+ whites: 0.0,
+ blacks: 0.0,
+ texture: 0.0,
+ clarity: 0.0,
+ dehaze: 0.0,
+ vibrance: 0.0,
+ saturation: 0.0,
+ curve_highlights: 0.0,
+ curve_lights: 0.0,
+ curve_darks: 0.0,
+ curve_shadows: 0.0,
+ curve_splits: [25.0, 50.0, 75.0],
+ point_curve: Vec::new(),
+ point_curve_red: Vec::new(),
+ point_curve_green: Vec::new(),
+ point_curve_blue: Vec::new(),
+ hsl_hue: [0.0; 8],
+ hsl_sat: [0.0; 8],
+ hsl_lum: [0.0; 8],
+ grade_shadows: Wheel::default(),
+ grade_midtones: Wheel::default(),
+ grade_highlights: Wheel::default(),
+ grade_global: Wheel::default(),
+ grade_blending: 50.0,
+ grade_balance: 0.0,
+ sharpen_amount: 0.0,
+ sharpen_radius: 1.0,
+ sharpen_detail: 25.0,
+ sharpen_masking: 0.0,
+ noise_luminance: 0.0,
+ noise_luminance_detail: 50.0,
+ noise_color: 0.0,
+ noise_color_detail: 50.0,
+ grain_amount: 0.0,
+ grain_size: 25.0,
+ grain_roughness: 50.0,
+ vignette_amount: 0.0,
+ vignette_midpoint: 50.0,
+ vignette_roundness: 0.0,
+ vignette_feather: 50.0,
+ vignette_highlights: 0.0,
+ vignette_style: "highlightPriority".into(),
+ seed: 0,
+ pixel_scale: 1.0,
+ }
+ }
+}
+
+/// Hue band centres of the Color Mixer (degrees).
+pub const HSL_BANDS: [f32; 8] = [0.0, 30.0, 60.0, 120.0, 180.0, 240.0, 270.0, 300.0];
+
+fn luma(c: [f32; 3]) -> f32 {
+ 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
+}
+
+fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+/// Box mean of a single-channel buffer (radius `r`, edge clamped) — parallel over rows/columns.
+fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {
+ if r == 0 {
+ return v.to_vec();
+ }
+ let mut tmp = vec![0.0f32; w * h];
+ par_rows(&mut tmp, w, 1, |y, row| {
+ let src = &v[y * w..(y + 1) * w];
+ let at = |k: i64| src[k.clamp(0, w as i64 - 1) as usize] as f64;
+ let mut acc: f64 = (-(r as i64)..=r as i64).map(at).sum();
+ let n = (2 * r + 1) as f64;
+ for (x, o) in row.iter_mut().enumerate() {
+ *o = (acc / n) as f32;
+ acc += at(x as i64 + r as i64 + 1) - at(x as i64 - r as i64);
+ }
+ });
+ // Columns via a transpose so rows stay contiguous.
+ let mut t = vec![0.0f32; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ t[x * h + y] = tmp[y * w + x];
+ }
+ }
+ let mut t2 = vec![0.0f32; w * h];
+ par_rows(&mut t2, h, 1, |x, row| {
+ let src = &t[x * h..(x + 1) * h];
+ let at = |k: i64| src[k.clamp(0, h as i64 - 1) as usize] as f64;
+ let mut acc: f64 = (-(r as i64)..=r as i64).map(at).sum();
+ let n = (2 * r + 1) as f64;
+ for (y, o) in row.iter_mut().enumerate() {
+ *o = (acc / n) as f32;
+ acc += at(y as i64 + r as i64 + 1) - at(y as i64 - r as i64);
+ }
+ });
+ for y in 0..h {
+ for x in 0..w {
+ tmp[y * w + x] = t2[x * h + y];
+ }
+ }
+ tmp
+}
+
+/// Approximate Gaussian (three box passes).
+fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
+ if sigma < 0.3 {
+ return v.to_vec();
+ }
+ let mut out = v.to_vec();
+ for r in crate::fxutil::gauss_box_radii(sigma) {
+ out = box_mean(&out, w, h, r);
+ }
+ out
+}
+
+/// Guided filter of `p` guided by `i` (He et al. 2010).
+fn guided(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec<f32> {
+ let mi = box_mean(i, w, h, r);
+ let mp = box_mean(p, w, h, r);
+ let ip: Vec<f32> = i.iter().zip(p).map(|(a, b)| a * b).collect();
+ let ii: Vec<f32> = i.iter().map(|a| a * a).collect();
+ let mip = box_mean(&ip, w, h, r);
+ let mii = box_mean(&ii, w, h, r);
+ let a: Vec<f32> = (0..w * h).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect();
+ let b: Vec<f32> = (0..w * h).map(|k| mp[k] - a[k] * mi[k]).collect();
+ let ma = box_mean(&a, w, h, r);
+ let mb = box_mean(&b, w, h, r);
+ (0..w * h).map(|k| ma[k] * i[k] + mb[k]).collect()
+}
+
+/// Monotone cubic (Fritsch–Carlson) through `pts` (x ascending, 0..=1), evaluated into a LUT.
+pub fn curve_lut(pts: &[[f32; 2]], n: usize) -> Vec<f32> {
+ let mut p: Vec<[f32; 2]> = pts.iter().map(|q| [q[0] / 255.0, q[1] / 255.0]).collect();
+ p.sort_by(|a, b| a[0].total_cmp(&b[0]));
+ p.dedup_by(|a, b| (a[0] - b[0]).abs() < 1e-6);
+ if p.len() < 2 {
+ return (0..n).map(|k| k as f32 / (n - 1) as f32).collect();
+ }
+ let m = p.len();
+ let d: Vec<f32> = (0..m - 1).map(|k| (p[k + 1][1] - p[k][1]) / (p[k + 1][0] - p[k][0]).max(1e-6)).collect();
+ let mut t = vec![0.0f32; m];
+ t[0] = d[0];
+ t[m - 1] = d[m - 2];
+ for k in 1..m - 1 {
+ t[k] = if d[k - 1] * d[k] <= 0.0 { 0.0 } else { (d[k - 1] + d[k]) / 2.0 };
+ }
+ for k in 0..m - 1 {
+ if d[k] == 0.0 {
+ t[k] = 0.0;
+ t[k + 1] = 0.0;
+ continue;
+ }
+ let (a, b) = (t[k] / d[k], t[k + 1] / d[k]);
+ let s = a * a + b * b;
+ if s > 9.0 {
+ let tau = 3.0 / s.sqrt();
+ t[k] = tau * a * d[k];
+ t[k + 1] = tau * b * d[k];
+ }
+ }
+ (0..n)
+ .map(|i| {
+ let x = i as f32 / (n - 1) as f32;
+ if x <= p[0][0] {
+ return p[0][1];
+ }
+ if x >= p[m - 1][0] {
+ return p[m - 1][1];
+ }
+ let k = p.windows(2).position(|wv| x <= wv[1][0]).unwrap_or(m - 2);
+ let hh = p[k + 1][0] - p[k][0];
+ let s = (x - p[k][0]) / hh;
+ let (h00, h10, h01, h11) = (2.0 * s * s * s - 3.0 * s * s + 1.0, s * s * s - 2.0 * s * s + s, -2.0 * s * s * s + 3.0 * s * s, s * s * s - s * s);
+ (h00 * p[k][1] + h10 * hh * t[k] + h01 * p[k + 1][1] + h11 * hh * t[k + 1]).clamp(0.0, 1.0)
+ })
+ .collect()
+}
+
+fn lut_eval(lut: &[f32], v: f32) -> f32 {
+ if !(0.0..=1.0).contains(&v) {
+ // Extend linearly outside (float documents).
+ return if v < 0.0 { v + lut[0] } else { lut[lut.len() - 1] + (v - 1.0) };
+ }
+ let x = v * (lut.len() - 1) as f32;
+ let i = (x as usize).min(lut.len() - 2);
+ let t = x - i as f32;
+ lut[i] + (lut[i + 1] - lut[i]) * t
+}
+
+/// Parametric tone curve as a LUT (regions split at `splits`, each slider ±100 moves its region
+/// by up to a quarter of the range, smoothly).
+fn parametric_lut(p: &CameraRaw, n: usize) -> Vec<f32> {
+ let s = p.curve_splits.map(|v| v.clamp(5.0, 95.0) / 100.0);
+ let centres = [s[0] / 2.0, (s[0] + s[1]) / 2.0, (s[1] + s[2]) / 2.0, (s[2] + 1.0) / 2.0];
+ let amounts = [p.curve_shadows, p.curve_darks, p.curve_lights, p.curve_highlights];
+ let widths = [s[0].max(0.1), (s[1] - s[0]).max(0.1), (s[2] - s[1]).max(0.1), (1.0 - s[2]).max(0.1)];
+ let mut lut: Vec<f32> = (0..n)
+ .map(|i| {
+ let x = i as f32 / (n - 1) as f32;
+ let mut y = x;
+ for k in 0..4 {
+ let d = (x - centres[k]) / (widths[k] * 1.2);
+ let bump = (-d * d * 2.0).exp() * x * (1.0 - x) * 4.0;
+ y += amounts[k] / 100.0 * 0.25 * bump;
+ }
+ y.clamp(0.0, 1.0)
+ })
+ .collect();
+ // Keep it monotone.
+ for i in 1..n {
+ lut[i] = lut[i].max(lut[i - 1]);
+ }
+ lut
+}
+
+fn rgb_to_hsv(c: [f32; 3]) -> [f32; 3] {
+ let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));
+ let d = mx - mn;
+ let h = if d <= 1e-9 {
+ 0.0
+ } else if mx == c[0] {
+ 60.0 * (((c[1] - c[2]) / d).rem_euclid(6.0))
+ } else if mx == c[1] {
+ 60.0 * ((c[2] - c[0]) / d + 2.0)
+ } else {
+ 60.0 * ((c[0] - c[1]) / d + 4.0)
+ };
+ [h, if mx > 1e-9 { d / mx } else { 0.0 }, mx]
+}
+
+fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] {
+ let h = h.rem_euclid(360.0) / 60.0;
+ let c = v * s;
+ let x = c * (1.0 - ((h % 2.0) - 1.0).abs());
+ let (r, g, b) = match h as u32 {
+ 0 => (c, x, 0.0),
+ 1 => (x, c, 0.0),
+ 2 => (0.0, c, x),
+ 3 => (0.0, x, c),
+ 4 => (x, 0.0, c),
+ _ => (c, 0.0, x),
+ };
+ let m = v - c;
+ [r + m, g + m, b + m]
+}
+
+/// Weights of the eight HSL bands at hue `h` (hat functions between neighbouring centres).
+pub fn band_weights(h: f32) -> [f32; 8] {
+ let mut w = [0.0f32; 8];
+ for k in 0..8 {
+ let (c, prev, next) = (HSL_BANDS[k], HSL_BANDS[(k + 7) % 8], HSL_BANDS[(k + 1) % 8]);
+ let diff = ((h - c + 540.0) % 360.0) - 180.0;
+ let span = if diff >= 0.0 { (next - c).rem_euclid(360.0) } else { (c - prev).rem_euclid(360.0) };
+ w[k] = (1.0 - diff.abs() / span.max(1e-3)).max(0.0);
+ }
+ w
+}
+
+impl CameraRaw {
+ fn wb_neutral(&self) -> bool {
+ self.temperature == 0.0 && self.tint == 0.0 && self.exposure == 0.0
+ }
+ fn tone_neutral(&self) -> bool {
+ [self.contrast, self.highlights, self.shadows, self.whites, self.blacks, self.texture, self.clarity].iter().all(|v| *v == 0.0)
+ }
+ fn hsl_neutral(&self) -> bool {
+ self.hsl_hue.iter().chain(&self.hsl_sat).chain(&self.hsl_lum).all(|v| *v == 0.0)
+ }
+ fn grade_neutral(&self) -> bool {
+ self.grade_shadows.neutral() && self.grade_midtones.neutral() && self.grade_highlights.neutral() && self.grade_global.neutral()
+ }
+ fn curves_neutral(&self) -> bool {
+ [self.curve_highlights, self.curve_lights, self.curve_darks, self.curve_shadows].iter().all(|v| *v == 0.0)
+ && [&self.point_curve, &self.point_curve_red, &self.point_curve_green, &self.point_curve_blue].iter().all(|c| is_linear(c))
+ }
+ /// True when every control is neutral (the filter is an identity).
+ pub fn is_identity(&self) -> bool {
+ self.wb_neutral()
+ && self.tone_neutral()
+ && self.dehaze == 0.0
+ && self.vibrance == 0.0
+ && self.saturation == 0.0
+ && self.curves_neutral()
+ && self.hsl_neutral()
+ && self.grade_neutral()
+ && self.sharpen_amount == 0.0
+ && self.noise_luminance == 0.0
+ && self.noise_color == 0.0
+ && self.grain_amount == 0.0
+ && self.vignette_amount == 0.0
+ }
+}
+
+fn is_linear(c: &[[f32; 2]]) -> bool {
+ c.len() < 2 || c.iter().all(|p| (p[0] - p[1]).abs() < 1e-3)
+}
+
+/// Runs the Camera Raw pipeline on straight RGBA pixels (`w × h`, display-encoded RGB).
+/// `float` keeps values above 1 (32-bit documents).
+pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bool) {
+ if px.is_empty() || p.is_identity() {
+ return;
+ }
+ let ps = p.pixel_scale.clamp(0.01, 1.0);
+ let long = w.max(h) as f32;
+ // 1. White balance + exposure in linear light.
+ if !p.wb_neutral() {
+ let t = p.temperature / 100.0;
+ let tn = p.tint / 100.0;
+ let mut g = [1.0 + 0.35 * t, 1.0 - 0.25 * tn, 1.0 - 0.35 * t];
+ let norm = luma(g);
+ g = g.map(|v| v / norm * 2f32.powf(p.exposure));
+ par_rows(px, w, 1, |_, row| {
+ for q in row.iter_mut() {
+ for c in 0..3 {
+ q[c] = linear_to_srgb((srgb_to_linear(q[c]) * g[c]).max(0.0));
+ }
+ }
+ });
+ }
+ // 2. Dehaze.
+ if p.dehaze != 0.0 {
+ dehaze(px, w, h, p.dehaze / 100.0);
+ }
+ // 3. Tone on luminance.
+ if !p.tone_neutral() {
+ let l: Vec<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]]).max(0.0)).collect();
+ let lc: Vec<f32> = l.iter().map(|v| v.min(1.0)).collect();
+ let base = if p.highlights != 0.0 || p.shadows != 0.0 {
+ let r = ((long * 0.015) as usize).max(2);
+ Some(guided(&lc, &lc, w, h, r, 0.02))
+ } else {
+ None
+ };
+ let clar = (p.clarity != 0.0).then(|| guided(&lc, &lc, w, h, ((long * 0.02) as usize).max(3), 0.005));
+ let tex = (p.texture != 0.0).then(|| gauss(&lc, w, h, (long * 0.002).max(1.5 * ps)));
+ let k_con = p.contrast / 100.0 * 0.6;
+ let tau = std::f32::consts::TAU;
+ par_rows(px, w, 1, |y, row| {
+ for (x, q) in row.iter_mut().enumerate() {
+ let i = y * w + x;
+ let l0 = l[i];
+ let mut lv = lc[i];
+ if let Some(b) = &base {
+ let bv = b[i].clamp(0.0, 1.0);
+ let hm = smoothstep(0.45, 0.95, bv);
+ let sm = 1.0 - smoothstep(0.05, 0.5, bv);
+ lv *= 2f32.powf(p.highlights / 100.0 * 1.2 * hm + p.shadows / 100.0 * 1.4 * sm);
+ }
+ if let Some(c) = &clar {
+ let mw = 1.0 - (2.0 * lv.clamp(0.0, 1.0) - 1.0).powi(2);
+ lv += p.clarity / 100.0 * 0.8 * (lc[i] - c[i]) * mw;
+ }
+ if let Some(t) = &tex {
+ lv += p.texture / 100.0 * 0.9 * (lc[i] - t[i]).clamp(-0.1, 0.1);
+ }
+ if p.whites != 0.0 {
+ lv += p.whites / 100.0 * 0.25 * smoothstep(0.4, 1.0, lv);
+ }
+ if p.blacks != 0.0 {
+ lv += p.blacks / 100.0 * 0.15 * (1.0 - smoothstep(0.0, 0.45, lv));
+ }
+ if k_con != 0.0 {
+ let xx = lv.clamp(0.0, 1.0);
+ lv += -k_con * (tau * xx).sin() / tau;
+ }
+ let lv = lv.max(0.0) + (l0 - lc[i]);
+ let ratio = if l0 > 1e-5 { lv / l0 } else { 1.0 };
+ for c in 0..3 {
+ q[c] = if l0 > 1e-5 { q[c] * ratio } else { q[c] + (lv - l0) };
+ }
+ }
+ });
+ }
+ // 4–7: per-pixel colour stages.
+ let need_color = p.vibrance != 0.0 || p.saturation != 0.0 || !p.curves_neutral() || !p.hsl_neutral() || !p.grade_neutral();
+ if need_color {
+ let par = (!(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0)).then(|| parametric_lut(p, 1024));
+ let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, 1024));
+ let (master, cr, cg, cb) = (pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue));
+ let hsl = !p.hsl_neutral();
+ let grade = !p.grade_neutral();
+ let wheel_tint = |wh: &Wheel| -> [f32; 3] {
+ let c = hsv_to_rgb(wh.hue, 1.0, 1.0);
+ let l = luma(c);
+ [c[0] - l, c[1] - l, c[2] - l].map(|v| v * wh.sat / 100.0 * 0.3)
+ };
+ let tints = [wheel_tint(&p.grade_shadows), wheel_tint(&p.grade_midtones), wheel_tint(&p.grade_highlights), wheel_tint(&p.grade_global)];
+ let blend = 0.15 + p.grade_blending.clamp(0.0, 100.0) / 100.0 * 0.35;
+ let bal = p.grade_balance.clamp(-100.0, 100.0) / 100.0 * 0.25;
+ par_rows(px, w, 1, |_, row| {
+ for q in row.iter_mut() {
+ let mut c = [q[0], q[1], q[2]];
+ if p.vibrance != 0.0 || p.saturation != 0.0 {
+ let l = luma(c);
+ let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));
+ let sat = if mx > 1e-6 { (mx - mn) / mx } else { 0.0 };
+ // Vibrance protects skin-ish hues (oranges) a little, like ACR.
+ let hue = rgb_to_hsv(c)[0];
+ let skin = (1.0 - ((hue - 25.0).abs() / 25.0)).clamp(0.0, 1.0) * 0.5;
+ let k = 1.0 + p.saturation / 100.0 + p.vibrance / 100.0 * (1.0 - sat) * (1.0 - skin);
+ c = c.map(|v| l + (v - l) * k.max(0.0));
+ }
+ if let Some(lut) = &par {
+ c = c.map(|v| lut_eval(lut, v));
+ }
+ if let Some(lut) = &master {
+ c = c.map(|v| lut_eval(lut, v));
+ }
+ for (ch, lut) in [&cr, &cg, &cb].iter().enumerate() {
+ if let Some(lut) = lut {
+ c[ch] = lut_eval(lut, c[ch]);
+ }
+ }
+ if hsl {
+ let [hh, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0)));
+ if s > 1e-4 {
+ let wts = band_weights(hh);
+ let (mut dh, mut ds, mut dl) = (0.0f32, 0.0f32, 0.0f32);
+ for k in 0..8 {
+ dh += wts[k] * p.hsl_hue[k];
+ ds += wts[k] * p.hsl_sat[k];
+ dl += wts[k] * p.hsl_lum[k];
+ }
+ let nh = hh + dh / 100.0 * 30.0;
+ let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0);
+ let mut out = hsv_to_rgb(nh, ns, v);
+ // Keep the luminance, then apply the luminance shift weighted by saturation.
+ let (l0, l1) = (luma(c), luma(out));
+ if l1 > 1e-6 {
+ out = out.map(|x| x * l0 / l1);
+ }
+ let k = 2f32.powf(dl / 100.0 * 1.0 * s);
+ c = out.map(|x| x * k);
+ }
+ }
+ if grade {
+ let l = luma(c).clamp(0.0, 1.0);
+ let sh = 1.0 - smoothstep(0.0, 0.5 + bal + blend, l);
+ let hi = smoothstep(0.5 + bal - blend, 1.0, l);
+ let mid = (1.0 - sh - hi).max(0.0);
+ let masks = [sh, mid, hi, 1.0];
+ let lums = [p.grade_shadows.lum, p.grade_midtones.lum, p.grade_highlights.lum, p.grade_global.lum];
+ for k in 0..4 {
+ for ch in 0..3 {
+ c[ch] += masks[k] * tints[k][ch];
+ }
+ if lums[k] != 0.0 {
+ let f = 2f32.powf(masks[k] * lums[k] / 100.0 * 0.6);
+ c = c.map(|x| x * f);
+ }
+ }
+ }
+ q[0] = c[0];
+ q[1] = c[1];
+ q[2] = c[2];
+ }
+ });
+ }
+ // 8. Detail.
+ if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 {
+ detail(px, w, h, p, ps);
+ }
+ // 9. Effects.
+ if p.vignette_amount != 0.0 {
+ vignette(px, w, h, p);
+ }
+ if p.grain_amount > 0.0 {
+ let cell = 1.0 + p.grain_size / 25.0;
+ let rough = p.grain_roughness / 100.0;
+ let amt = p.grain_amount / 100.0 * 0.12;
+ let seed = p.seed as u64;
+ let pscale = 1.0 / ps;
+ par_rows(px, w, 1, |y, row| {
+ for (x, q) in row.iter_mut().enumerate() {
+ // Sample in full-resolution coordinates so previews match the result.
+ let (fx, fy) = (x as f32 * pscale / cell, y as f32 * pscale / cell);
+ let n = value_noise(fx, fy, seed) * (1.0 - rough) + (value_noise(fx * 2.3, fy * 2.3, seed + 7) - 0.0) * rough;
+ let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0);
+ let g = (n - 0.5) * 2.0 * amt * (0.4 + 2.4 * l * (1.0 - l));
+ for c in 0..3 {
+ q[c] += g;
+ }
+ }
+ });
+ }
+ if !float {
+ for q in px.iter_mut() {
+ for c in 0..3 {
+ q[c] = q[c].clamp(0.0, 1.0);
+ }
+ }
+ }
+}
+
+fn value_noise(x: f32, y: f32, seed: u64) -> f32 {
+ let (xi, yi) = (x.floor(), y.floor());
+ let (tx, ty) = (x - xi, y - yi);
+ let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));
+ let h = |dx: i64, dy: i64| hash01(xi as i64 + dx, yi as i64 + dy, seed);
+ let top = h(0, 0) + (h(1, 0) - h(0, 0)) * sx;
+ let bot = h(0, 1) + (h(1, 1) - h(0, 1)) * sx;
+ top + (bot - top) * sy
+}
+
+fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, amount: f32) {
+ // Transmission on a ≤ 768 px proxy, upsampled.
+ let k = w.max(h).div_ceil(768).max(1);
+ let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
+ let mut small = vec![[0.0f32; 3]; sw * sh];
+ let mut cnt = vec![0f32; sw * sh];
+ for y in 0..h {
+ for x in 0..w {
+ let i = (y / k) * sw + x / k;
+ for c in 0..3 {
+ small[i][c] += px[y * w + x][c].clamp(0.0, 1.0);
+ }
+ cnt[i] += 1.0;
+ }
+ }
+ for (s, c) in small.iter_mut().zip(&cnt) {
+ *s = s.map(|v| v / c.max(1.0));
+ }
+ let r = (sw.max(sh) / 60).max(2);
+ let min_filter = |v: &[f32]| -> Vec<f32> {
+ let mut a = vec![0.0f32; sw * sh];
+ for y in 0..sh {
+ for x in 0..sw {
+ let (x0, x1) = (x.saturating_sub(r), (x + r).min(sw - 1));
+ a[y * sw + x] = (x0..=x1).map(|xx| v[y * sw + xx]).fold(f32::MAX, f32::min);
+ }
+ }
+ let mut b = vec![0.0f32; sw * sh];
+ for y in 0..sh {
+ for x in 0..sw {
+ let (y0, y1) = (y.saturating_sub(r), (y + r).min(sh - 1));
+ b[y * sw + x] = (y0..=y1).map(|yy| a[yy * sw + x]).fold(f32::MAX, f32::min);
+ }
+ }
+ b
+ };
+ let dark = min_filter(&small.iter().map(|c| c[0].min(c[1]).min(c[2])).collect::<Vec<_>>());
+ // Atmospheric light: mean colour of the brightest 0.1 % of the dark channel.
+ let mut idx: Vec<usize> = (0..sw * sh).collect();
+ idx.sort_by(|&a, &b| dark[b].total_cmp(&dark[a]));
+ let top = (sw * sh / 1000).max(1);
+ let mut air = [0.0f32; 3];
+ for &i in &idx[..top] {
+ for c in 0..3 {
+ air[c] += small[i][c] / top as f32;
+ }
+ }
+ let air = air.map(|v| v.max(0.2));
+ let norm_dark = min_filter(&small.iter().map(|c| (c[0] / air[0]).min(c[1] / air[1]).min(c[2] / air[2])).collect::<Vec<_>>());
+ let t_raw: Vec<f32> = norm_dark.iter().map(|d| 1.0 - 0.95 * d).collect();
+ let guide: Vec<f32> = small.iter().map(|c| luma(*c)).collect();
+ let t = guided(&guide, &t_raw, sw, sh, r * 2, 1e-3);
+ let ks = k as f32;
+ par_rows(px, w, 1, |y, row| {
+ for (x, q) in row.iter_mut().enumerate() {
+ let tv = crate::photo_util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(0.1, 1.0);
+ for c in 0..3 {
+ let i = q[c];
+ let j = (i - air[c]) / tv + air[c];
+ q[c] = if amount >= 0.0 { i + (j - i) * amount } else { i + (air[c] - i) * (-amount) * 0.5 * (1.0 - tv * 0.5) };
+ }
+ }
+ });
+}
+
+fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) {
+ // Work in Y + chroma (BT.709 luma, B−Y, R−Y).
+ let mut y: Vec<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect();
+ let mut cb: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect();
+ let mut cr: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect();
+ if p.noise_luminance > 0.0 {
+ let n = p.noise_luminance / 100.0;
+ let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize;
+ let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6);
+ let keep = p.noise_luminance_detail / 100.0 * 0.5;
+ for i in 0..w * h {
+ y[i] = smooth[i] + (y[i] - smooth[i]) * keep;
+ }
+ }
+ if p.noise_color > 0.0 {
+ let sigma = (p.noise_color / 100.0 * 6.0 * ps).max(0.3);
+ let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma));
+ let keep = p.noise_color_detail / 100.0 * 0.3;
+ for i in 0..w * h {
+ cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep;
+ cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep;
+ }
+ }
+ if p.sharpen_amount > 0.0 {
+ let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3);
+ let blur = gauss(&y, w, h, sigma);
+ // Masking: an edge mask from the gradient of a smoothed luminance.
+ let mask: Option<Vec<f32>> = (p.sharpen_masking > 0.0).then(|| {
+ let s = gauss(&y, w, h, 1.0 * ps.max(0.5));
+ let t = p.sharpen_masking / 100.0 * 0.08;
+ (0..w * h)
+ .map(|i| {
+ let (x, yy) = (i % w, i / w);
+ let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)];
+ let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x];
+ smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy))
+ })
+ .collect()
+ });
+ let amt = p.sharpen_amount / 100.0 * 1.2;
+ let det = p.sharpen_detail / 100.0;
+ for i in 0..w * h {
+ let hp = y[i] - blur[i];
+ // Low Detail damps large (halo-producing) differences.
+ let limit = 0.03 + det * 0.3;
+ let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det);
+ let m = mask.as_ref().map_or(1.0, |m| m[i]);
+ y[i] += amt * hp * m;
+ }
+ }
+ for i in 0..w * h {
+ let (l, b, r) = (y[i], cb[i], cr[i]);
+ let (rr, bb) = (r + l, b + l);
+ let g = (l - 0.2126 * rr - 0.0722 * bb) / 0.7152;
+ px[i][0] = rr;
+ px[i][1] = g;
+ px[i][2] = bb;
+ }
+}
+
+fn vignette(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw) {
+ let amt = p.vignette_amount / 100.0;
+ let mid = p.vignette_midpoint.clamp(0.0, 100.0) / 100.0;
+ let feather = p.vignette_feather.clamp(0.0, 100.0) / 100.0;
+ let round = p.vignette_roundness.clamp(-100.0, 100.0) / 100.0;
+ let hl = p.vignette_highlights.clamp(0.0, 100.0) / 100.0;
+ let style = p.vignette_style.as_str();
+ let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
+ // Roundness: 0 follows the frame's aspect, +1 a circle, −1 a rounded rectangle.
+ let (ax, ay) = if round >= 0.0 {
+ let r = cx.min(cy) + (cx.max(cy) - cx.min(cy)) * (1.0 - round);
+ (if cx >= cy { r } else { cx }, if cy > cx { r } else { cy })
+ } else {
+ (cx, cy)
+ };
+ let pw = 2.0 + (-round).max(0.0) * 6.0;
+ let inner = 1.0 - mid * 0.8;
+ let edge0 = inner - feather * 0.5 * inner;
+ let edge1 = inner + feather * 0.5 * (1.4 - inner) + 0.02;
+ par_rows(px, w, 1, |y, row| {
+ for (x, q) in row.iter_mut().enumerate() {
+ let (dx, dy) = (((x as f32 + 0.5 - cx) / ax).abs(), ((y as f32 + 0.5 - cy) / ay).abs());
+ let r = (dx.powf(pw) + dy.powf(pw)).powf(1.0 / pw);
+ let m = smoothstep(edge0, edge1, r);
+ if m <= 0.0 {
+ continue;
+ }
+ let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0);
+ match style {
+ "paintOverlay" => {
+ let target = if amt < 0.0 { 0.0 } else { 1.0 };
+ let k = m * amt.abs();
+ for c in 0..3 {
+ q[c] += (target - q[c]) * k;
+ }
+ }
+ _ => {
+ let mut k = 2f32.powf(amt * 2.0 * m);
+ if amt < 0.0 && hl > 0.0 {
+ // Highlights: let bright areas punch through a darkening vignette.
+ let protect = smoothstep(0.6, 1.0, l) * hl;
+ k += (1.0 - k) * protect;
+ }
+ if style == "colorPriority" {
+ let nl = l * k;
+ for c in 0..3 {
+ q[c] += nl - l;
+ }
+ } else {
+ for c in 0..3 {
+ q[c] *= k;
+ }
+ }
+ }
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn img(w: usize, h: usize) -> Vec<[f32; 4]> {
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32);
+ [0.2 + 0.6 * x, 0.3 + 0.4 * y, 0.5 - 0.3 * x * y, 1.0]
+ })
+ .collect()
+ }
+
+ fn mean(px: &[[f32; 4]], c: usize) -> f32 {
+ px.iter().map(|q| q[c]).sum::<f32>() / px.len() as f32
+ }
+
+ #[test]
+ fn defaults_are_identity() {
+ let mut a = img(40, 30);
+ let b = a.clone();
+ develop(&mut a, 40, 30, &CameraRaw::default(), false);
+ assert_eq!(a, b);
+ }
+
+ #[test]
+ fn basic_panel_moves_the_right_way() {
+ let (w, h) = (64, 48);
+ let base = img(w, h);
+ let run = |p: CameraRaw| {
+ let mut a = base.clone();
+ develop(&mut a, w, h, &p, false);
+ a
+ };
+ let warm = run(CameraRaw { temperature: 50.0, ..Default::default() });
+ assert!(mean(&warm, 0) > mean(&base, 0) && mean(&warm, 2) < mean(&base, 2));
+ let bright = run(CameraRaw { exposure: 1.0, ..Default::default() });
+ assert!(mean(&bright, 1) > mean(&base, 1) + 0.1);
+ let shadows = run(CameraRaw { shadows: 100.0, ..Default::default() });
+ let dark_px = |a: &[[f32; 4]]| a[0][1];
+ assert!(dark_px(&shadows) > dark_px(&base));
+ let hl = run(CameraRaw { highlights: -100.0, ..Default::default() });
+ assert!(hl[w * h - 1][0] < base[w * h - 1][0]);
+ let con = run(CameraRaw { contrast: 100.0, ..Default::default() });
+ // More contrast: darker darks, brighter brights.
+ assert!(con[0][1] < base[0][1] && con[w * h - 1][0] > base[w * h - 1][0]);
+ let desat = run(CameraRaw { saturation: -100.0, ..Default::default() });
+ assert!(desat.iter().all(|q| (q[0] - q[1]).abs() < 1e-4 && (q[1] - q[2]).abs() < 1e-4));
+ let vib = run(CameraRaw { vibrance: 100.0, ..Default::default() });
+ let spread = |q: [f32; 4]| q[0].max(q[1]).max(q[2]) - q[0].min(q[1]).min(q[2]);
+ assert!(spread(vib[w * h / 2]) > spread(base[w * h / 2]));
+ for p in [CameraRaw { clarity: 80.0, ..Default::default() }, CameraRaw { texture: 80.0, ..Default::default() }, CameraRaw { dehaze: 60.0, ..Default::default() }, CameraRaw { dehaze: -60.0, ..Default::default() }, CameraRaw { whites: 50.0, blacks: -50.0, ..Default::default() }] {
+ let out = run(p.clone());
+ assert!(out.iter().all(|q| q[..3].iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))), "{p:?}");
+ assert_ne!(out, base);
+ }
+ }
+
+ #[test]
+ fn curves_hsl_grading_detail_effects() {
+ // Monotone cubic LUT through the points.
+ let lut = curve_lut(&[[0.0, 0.0], [64.0, 40.0], [192.0, 220.0], [255.0, 255.0]], 256);
+ assert!((lut[64] - 40.0 / 255.0).abs() < 0.01 && (lut[192] - 220.0 / 255.0).abs() < 0.01);
+ assert!(lut.windows(2).all(|p| p[1] >= p[0]));
+ // Band weights sum to one everywhere.
+ for hh in (0..360).step_by(7) {
+ let s: f32 = band_weights(hh as f32).iter().sum();
+ assert!((s - 1.0).abs() < 1e-4, "{hh}: {s}");
+ }
+ let (w, h) = (48, 32);
+ let reds: Vec<[f32; 4]> = vec![[0.8, 0.2, 0.2, 1.0]; w * h];
+ let mut a = reds.clone();
+ let mut hs = [0.0; 8];
+ hs[0] = -100.0;
+ develop(&mut a, w, h, &CameraRaw { hsl_sat: hs, ..Default::default() }, false);
+ assert!(a[0][0] - a[0][1] < 0.1, "reds desaturated: {:?}", a[0]);
+ let blues: Vec<[f32; 4]> = vec![[0.2, 0.2, 0.8, 1.0]; w * h];
+ let mut b = blues.clone();
+ develop(&mut b, w, h, &CameraRaw { hsl_sat: hs, ..Default::default() }, false);
+ assert!((b[0][2] - 0.8).abs() < 1e-4, "blues untouched");
+ // Grading: blue shadows tint dark pixels, leave bright ones nearly alone.
+ let mut g: Vec<[f32; 4]> = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]];
+ develop(&mut g, 2, 1, &CameraRaw { grade_shadows: Wheel { hue: 220.0, sat: 80.0, lum: 0.0 }, ..Default::default() }, false);
+ assert!(g[0][2] > g[0][0] + 0.05 && (g[1][2] - g[1][0]).abs() < 0.02, "{g:?}");
+ // Point curve + parametric.
+ let mut c = img(w, h);
+ develop(&mut c, w, h, &CameraRaw { point_curve: vec![[0.0, 30.0], [255.0, 255.0]], curve_shadows: 50.0, ..Default::default() }, false);
+ assert!(c.iter().all(|q| q[1] >= 30.0 / 255.0 - 1e-4));
+ // Noise reduction reduces variance; sharpening increases it; grain is deterministic.
+ let noisy: Vec<[f32; 4]> = (0..w * h).map(|i| { let n = hash01(i as i64, 0, 3) * 0.2; [0.4 + n, 0.4 + n, 0.4 + n, 1.0] }).collect();
+ let var = |a: &[[f32; 4]]| { let m = mean(a, 1); a.iter().map(|q| (q[1] - m).powi(2)).sum::<f32>() / a.len() as f32 };
+ let mut nr = noisy.clone();
+ develop(&mut nr, w, h, &CameraRaw { noise_luminance: 80.0, ..Default::default() }, false);
+ assert!(var(&nr) < var(&noisy) * 0.5);
+ let mut sh = noisy.clone();
+ develop(&mut sh, w, h, &CameraRaw { sharpen_amount: 100.0, ..Default::default() }, false);
+ assert!(var(&sh) > var(&noisy));
+ let mut g1 = img(w, h);
+ let mut g2 = img(w, h);
+ let gp = CameraRaw { grain_amount: 50.0, seed: 4, ..Default::default() };
+ develop(&mut g1, w, h, &gp, false);
+ develop(&mut g2, w, h, &gp, false);
+ assert_eq!(g1, g2);
+ assert_ne!(g1, img(w, h));
+ // Post-crop vignette darkens corners, leaves the centre.
+ let flat = vec![[0.5f32, 0.5, 0.5, 1.0]; w * h];
+ let mut v = flat.clone();
+ develop(&mut v, w, h, &CameraRaw { vignette_amount: -80.0, ..Default::default() }, false);
+ assert!(v[0][0] < 0.35 && (v[(h / 2) * w + w / 2][0] - 0.5).abs() < 0.01, "{:?}", v[0]);
+ }
+
+ #[test]
+ fn float_documents_keep_overrange() {
+ let mut a = vec![[2.0f32, 1.5, 0.5, 1.0]; 16];
+ develop(&mut a, 4, 4, &CameraRaw { exposure: 0.5, ..Default::default() }, true);
+ assert!(a[0][0] > 2.0);
+ }
+}
diff --git a/crates/algo/src/exif.rs b/crates/algo/src/exif.rs
new file mode 100644
index 000000000..445f51498
--- /dev/null
+++ b/crates/algo/src/exif.rs
@@ -0,0 +1,240 @@
+//! Minimal EXIF reader for the camera settings the photography commands use (exposure, aperture,
+//! ISO, focal length, camera and lens names). Input is the raw TIFF-structured EXIF payload
+//! (`II*\0` / `MM\0*`, as stored in `Document.metadata.exif`); malformed data yields `None`
+//! fields, never a panic. Tag numbers are from the EXIF 2.32 specification (CIPA DC-008).
+
+/// Camera settings read from EXIF.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct CameraInfo {
+ pub make: Option<String>,
+ pub model: Option<String>,
+ pub lens: Option<String>,
+ /// Seconds.
+ pub exposure_time: Option<f64>,
+ pub f_number: Option<f64>,
+ pub iso: Option<f64>,
+ /// Millimetres.
+ pub focal_length: Option<f64>,
+ /// 35 mm-equivalent focal length in millimetres.
+ pub focal_length_35mm: Option<f64>,
+}
+
+impl CameraInfo {
+ /// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene).
+ pub fn exposure_factor(&self) -> Option<f64> {
+ let t = self.exposure_time?;
+ let n = self.f_number.unwrap_or(1.0).max(0.1);
+ Some(t * self.iso.unwrap_or(100.0) / 100.0 / (n * n))
+ }
+}
+
+struct Tiff<'a> {
+ b: &'a [u8],
+ le: bool,
+}
+
+impl Tiff<'_> {
+ fn u16(&self, o: usize) -> Option<u16> {
+ let s = self.b.get(o..o + 2)?;
+ Some(if self.le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) })
+ }
+ fn u32(&self, o: usize) -> Option<u32> {
+ let s = self.b.get(o..o + 4)?;
+ let a = [s[0], s[1], s[2], s[3]];
+ Some(if self.le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) })
+ }
+ /// Entries of the IFD at `off`: (tag, type, count, value offset field position).
+ fn ifd(&self, off: usize) -> Vec<(u16, u16, u32, usize)> {
+ let Some(n) = self.u16(off) else { return Vec::new() };
+ (0..n as usize)
+ .filter_map(|k| {
+ let e = off + 2 + k * 12;
+ Some((self.u16(e)?, self.u16(e + 2)?, self.u32(e + 4)?, e + 8))
+ })
+ .collect()
+ }
+ fn data_at(&self, typ: u16, count: u32, field: usize) -> Option<usize> {
+ let size = match typ {
+ 1 | 2 | 6 | 7 => 1,
+ 3 | 8 => 2,
+ 4 | 9 | 11 => 4,
+ 5 | 10 | 12 => 8,
+ _ => return None,
+ } * count as usize;
+ if size <= 4 { Some(field) } else { self.u32(field).map(|v| v as usize) }
+ }
+ fn number(&self, typ: u16, count: u32, field: usize) -> Option<f64> {
+ let at = self.data_at(typ, count, field)?;
+ match typ {
+ 3 => self.u16(at).map(f64::from),
+ 4 => self.u32(at).map(f64::from),
+ 5 => {
+ let (n, d) = (self.u32(at)?, self.u32(at + 4)?);
+ (d != 0).then(|| n as f64 / d as f64)
+ }
+ 10 => {
+ let (n, d) = (self.u32(at)? as i32, self.u32(at + 4)? as i32);
+ (d != 0).then(|| n as f64 / d as f64)
+ }
+ _ => None,
+ }
+ }
+ fn text(&self, typ: u16, count: u32, field: usize) -> Option<String> {
+ if typ != 2 {
+ return None;
+ }
+ let at = self.data_at(typ, count, field)?;
+ let s = self.b.get(at..at + count as usize)?;
+ let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string();
+ (!s.is_empty()).then_some(s)
+ }
+}
+
+/// Reads [`CameraInfo`] from a TIFF-structured EXIF payload (an `Exif\0\0` prefix is skipped).
+pub fn read(exif: &[u8]) -> CameraInfo {
+ let b = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif);
+ let mut info = CameraInfo::default();
+ let le = match b.get(..4) {
+ Some([b'I', b'I', 42, 0]) => true,
+ Some([b'M', b'M', 0, 42]) => false,
+ _ => return info,
+ };
+ let t = Tiff { b, le };
+ let Some(ifd0) = t.u32(4) else { return info };
+ let mut queue = vec![ifd0 as usize];
+ let mut seen = Vec::new();
+ while let Some(off) = queue.pop() {
+ if seen.contains(&off) || seen.len() > 8 {
+ continue;
+ }
+ seen.push(off);
+ for (tag, typ, count, field) in t.ifd(off) {
+ match tag {
+ 0x010F => info.make = t.text(typ, count, field),
+ 0x0110 => info.model = t.text(typ, count, field),
+ 0x829A => info.exposure_time = t.number(typ, count, field),
+ 0x829D => info.f_number = t.number(typ, count, field),
+ 0x8827 => info.iso = t.number(typ, count, field),
+ 0x920A => info.focal_length = t.number(typ, count, field),
+ 0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0),
+ 0xA434 => info.lens = t.text(typ, count, field),
+ 0x8769 => {
+ if let Some(p) = t.u32(field) {
+ queue.push(p as usize);
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ info
+}
+
+/// Builds a little-endian EXIF payload (used by tests and by synthetic fixtures).
+pub fn build(info: &CameraInfo) -> Vec<u8> {
+ // IFD0: Make, Model, ExifIFD pointer; Exif IFD: the rest. Data area after the IFDs.
+ let mut ifd0: Vec<(u16, u16, u32, Vec<u8>)> = Vec::new();
+ let mut exif: Vec<(u16, u16, u32, Vec<u8>)> = Vec::new();
+ let text = |s: &str| {
+ let mut v = s.as_bytes().to_vec();
+ v.push(0);
+ v
+ };
+ let rational = |v: f64| {
+ let d = 10000u32;
+ let mut b = ((v * d as f64).round() as u32).to_le_bytes().to_vec();
+ b.extend_from_slice(&d.to_le_bytes());
+ b
+ };
+ if let Some(s) = &info.make {
+ ifd0.push((0x010F, 2, s.len() as u32 + 1, text(s)));
+ }
+ if let Some(s) = &info.model {
+ ifd0.push((0x0110, 2, s.len() as u32 + 1, text(s)));
+ }
+ if let Some(v) = info.exposure_time {
+ exif.push((0x829A, 5, 1, rational(v)));
+ }
+ if let Some(v) = info.f_number {
+ exif.push((0x829D, 5, 1, rational(v)));
+ }
+ if let Some(v) = info.iso {
+ exif.push((0x8827, 3, 1, (v as u16).to_le_bytes().to_vec()));
+ }
+ if let Some(v) = info.focal_length {
+ exif.push((0x920A, 5, 1, rational(v)));
+ }
+ if let Some(v) = info.focal_length_35mm {
+ exif.push((0xA405, 3, 1, (v as u16).to_le_bytes().to_vec()));
+ }
+ if let Some(s) = &info.lens {
+ exif.push((0xA434, 2, s.len() as u32 + 1, text(s)));
+ }
+ let ifd_len = |n: usize| 2 + 12 * n + 4;
+ let ifd0_off = 8usize;
+ let n0 = ifd0.len() + 1;
+ let exif_off = ifd0_off + ifd_len(n0);
+ let mut data_off = exif_off + ifd_len(exif.len());
+ let mut out = b"II*\0".to_vec();
+ out.extend_from_slice(&(ifd0_off as u32).to_le_bytes());
+ let mut data = Vec::new();
+ let mut write_ifd = |out: &mut Vec<u8>, entries: &[(u16, u16, u32, Vec<u8>)], extra: Option<u32>| {
+ let n = entries.len() + usize::from(extra.is_some());
+ out.extend_from_slice(&(n as u16).to_le_bytes());
+ for (tag, typ, count, bytes) in entries {
+ out.extend_from_slice(&tag.to_le_bytes());
+ out.extend_from_slice(&typ.to_le_bytes());
+ out.extend_from_slice(&count.to_le_bytes());
+ if bytes.len() <= 4 {
+ let mut f = bytes.clone();
+ f.resize(4, 0);
+ out.extend_from_slice(&f);
+ } else {
+ out.extend_from_slice(&(data_off as u32).to_le_bytes());
+ data.extend_from_slice(bytes);
+ data_off += bytes.len();
+ }
+ }
+ if let Some(p) = extra {
+ out.extend_from_slice(&0x8769u16.to_le_bytes());
+ out.extend_from_slice(&4u16.to_le_bytes());
+ out.extend_from_slice(&1u32.to_le_bytes());
+ out.extend_from_slice(&p.to_le_bytes());
+ }
+ out.extend_from_slice(&0u32.to_le_bytes());
+ };
+ write_ifd(&mut out, &ifd0, Some(exif_off as u32));
+ write_ifd(&mut out, &exif, None);
+ out.extend_from_slice(&data);
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trips_and_survives_garbage() {
+ let info = CameraInfo {
+ make: Some("Generic".into()),
+ model: Some("Camera 1".into()),
+ lens: Some("24-70mm".into()),
+ exposure_time: Some(0.004),
+ f_number: Some(8.0),
+ iso: Some(200.0),
+ focal_length: Some(35.0),
+ focal_length_35mm: Some(52.0),
+ };
+ let b = build(&info);
+ let r = read(&b);
+ assert_eq!(r, info);
+ assert!((r.exposure_factor().unwrap() - 0.004 * 2.0 / 64.0).abs() < 1e-9);
+ let mut prefixed = b"Exif\0\0".to_vec();
+ prefixed.extend_from_slice(&b);
+ assert_eq!(read(&prefixed), info);
+ assert_eq!(read(b"nonsense"), CameraInfo::default());
+ for cut in [5, 12, 30, b.len() - 3] {
+ let _ = read(&b[..cut]);
+ }
+ }
+}
diff --git a/crates/algo/src/hdr.rs b/crates/algo/src/hdr.rs
new file mode 100644
index 000000000..25600f9c4
--- /dev/null
+++ b/crates/algo/src/hdr.rs
@@ -0,0 +1,532 @@
+//! File › Automate › Merge to HDR Pro: exposure estimation, alignment, camera response recovery,
+//! radiance merge, ghost removal and the 16/8-bit tone mapping methods.
+//!
+//! * **Alignment**: G. Ward, *Fast, Robust Image Registration for Compositing High Dynamic Range
+//! Photographs from Hand-Held Exposures*, JGT 2003 — median threshold bitmaps (invariant to
+//! exposure) with an exclusion band around the median, XOR-counted over an image pyramid.
+//! * **Response curve**: P. Debevec, J. Malik, *Recovering High Dynamic Range Radiance Maps from
+//! Photographs*, SIGGRAPH 1997 — `g(Z) = ln E + ln Δt` solved by weighted linear least squares
+//! with a smoothness term and `g(128) = 0`, per channel, on stratified sample pixels.
+//! * **Merge**: the hat-weighted average of `g(Z) − ln Δt` over the exposures.
+//! * **Ghosts**: where the per-exposure radiance estimates disagree (high weighted variance of
+//! their logarithms) the result comes from one base exposure only, as Photoshop's *Remove
+//! ghosts* does; the mask is feathered.
+//! * **Tone mapping** for 16/8-bit output: Local Adaptation ([`crate::tone::hdr_toning`]),
+//! Exposure and Gamma, Highlight Compression (E. Reinhard et al., *Photographic Tone
+//! Reproduction for Digital Images*, SIGGRAPH 2002, global operator) and Equalize Histogram
+//! (histogram equalisation of log luminance, after G. Ward Larson et al., *A Visibility
+//! Matching Tone Reproduction Operator*, TVCG 1997, without the ceiling).
+//!
+//! Pixels are straight RGBA in `0..=1` (display-encoded inputs); radiance is linear.
+
+#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels)
+
+use crate::photo_util::{Normal, linear_to_srgb, par_rows, srgb_to_linear};
+use crate::tone::HdrToning;
+
+fn luma(c: [f32; 4]) -> f32 {
+ 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
+}
+
+/// Hat weight on a 0..=255 code value.
+fn hat(z: f64) -> f64 {
+ if z <= 127.5 { z } else { 255.0 - z }.max(0.0)
+}
+
+/// Relative exposures (linear factors, the darkest = 1) estimated from the images themselves:
+/// consecutive images (sorted by brightness) are compared on pixels well exposed in both.
+pub fn estimate_exposures(imgs: &[&[[f32; 4]]]) -> Vec<f64> {
+ let n = imgs.len();
+ let mean: Vec<f64> = imgs.iter().map(|im| im.iter().map(|p| luma(*p) as f64).sum::<f64>() / im.len().max(1) as f64).collect();
+ let mut order: Vec<usize> = (0..n).collect();
+ order.sort_by(|&a, &b| mean[a].total_cmp(&mean[b]));
+ let mut ex = vec![1.0f64; n];
+ for k in 1..n {
+ let (a, b) = (order[k - 1], order[k]);
+ let mut ratios: Vec<f64> = imgs[a]
+ .iter()
+ .zip(imgs[b].iter())
+ .step_by(7)
+ .filter_map(|(pa, pb)| {
+ let (la, lb) = (luma(*pa), luma(*pb));
+ ((0.08..0.92).contains(&la) && (0.08..0.92).contains(&lb)).then(|| srgb_to_linear(lb) as f64 / srgb_to_linear(la).max(1e-6) as f64)
+ })
+ .collect();
+ ratios.sort_by(f64::total_cmp);
+ let r = if ratios.is_empty() { 2.0 } else { ratios[ratios.len() / 2].max(1.0) };
+ ex[b] = ex[a] * r;
+ }
+ ex
+}
+
+// ---------- alignment ----------
+
+fn shrink(w: usize, h: usize, g: &[f32]) -> (usize, usize, Vec<f32>) {
+ let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
+ let mut out = vec![0.0f32; nw * nh];
+ for y in 0..nh {
+ for x in 0..nw {
+ let p = |xx: usize, yy: usize| g[yy.min(h - 1) * w + xx.min(w - 1)];
+ out[y * nw + x] = 0.25 * (p(2 * x, 2 * y) + p(2 * x + 1, 2 * y) + p(2 * x, 2 * y + 1) + p(2 * x + 1, 2 * y + 1));
+ }
+ }
+ (nw, nh, out)
+}
+
+fn bitmaps(g: &[f32]) -> (Vec<bool>, Vec<bool>) {
+ let mut s: Vec<f32> = g.to_vec();
+ s.sort_by(f32::total_cmp);
+ let med = s[s.len() / 2];
+ (g.iter().map(|v| *v > med).collect(), g.iter().map(|v| (v - med).abs() > 4.0 / 255.0).collect())
+}
+
+/// Translation `(dx, dy)` that aligns grey image `img` to `reference` (Ward's MTB), searching
+/// up to `2^levels` px.
+pub fn mtb_offset(w: usize, h: usize, reference: &[f32], img: &[f32], levels: usize) -> (i32, i32) {
+ if levels == 0 || w < 16 || h < 16 {
+ return (0, 0);
+ }
+ let (cur_x, cur_y) = {
+ let (sw, sh, sr) = shrink(w, h, reference);
+ let (_, _, si) = shrink(w, h, img);
+ let (x, y) = mtb_offset(sw, sh, &sr, &si, levels - 1);
+ (x * 2, y * 2)
+ };
+ let (tr, er) = bitmaps(reference);
+ let (ti, ei) = bitmaps(img);
+ let mut best = (u64::MAX, 0, 0);
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let (ox, oy) = (cur_x + dx, cur_y + dy);
+ let mut err = 0u64;
+ for y in 0..h as i32 {
+ let sy = y - oy;
+ if sy < 0 || sy >= h as i32 {
+ continue;
+ }
+ for x in 0..w as i32 {
+ let sx = x - ox;
+ if sx < 0 || sx >= w as i32 {
+ continue;
+ }
+ let (a, b) = ((y as usize) * w + x as usize, (sy as usize) * w + sx as usize);
+ if (tr[a] != ti[b]) && er[a] && ei[b] {
+ err += 1;
+ }
+ }
+ }
+ if err < best.0 {
+ best = (err, ox, oy);
+ }
+ }
+ }
+ (best.1, best.2)
+}
+
+// ---------- response curve ----------
+
+/// Sample pixel indices for response recovery: a spatial grid filtered to pixels whose
+/// neighbourhood is flat in the middle exposure (robust to small misalignment), stratified by
+/// its intensity.
+pub fn sample_pixels(w: usize, h: usize, middle: &[[f32; 4]], count: usize) -> Vec<usize> {
+ let mut by_bin: Vec<Vec<usize>> = vec![Vec::new(); 32];
+ let step = ((w * h / (count * 40).max(1)) as f64).sqrt().max(1.0) as usize;
+ for y in (2..h.saturating_sub(2)).step_by(step) {
+ for x in (2..w.saturating_sub(2)).step_by(step) {
+ let i = y * w + x;
+ let l = luma(middle[i]);
+ let flat = [i - 2, i + 2, i - 2 * w, i + 2 * w].iter().all(|&j| (luma(middle[j]) - l).abs() < 0.04);
+ if flat {
+ by_bin[((l * 31.99) as usize).min(31)].push(i);
+ }
+ }
+ }
+ // Round-robin over the bins so every intensity is represented.
+ let mut out = Vec::new();
+ let mut k = 0;
+ while out.len() < count && by_bin.iter().any(|b| k < b.len()) {
+ for b in &by_bin {
+ if let Some(&i) = b.get(k * 7 % b.len().max(1)).filter(|_| k < b.len()) {
+ out.push(i);
+ if out.len() >= count {
+ break;
+ }
+ }
+ }
+ k += 1;
+ }
+ out.sort_unstable();
+ out.dedup();
+ out
+}
+
+/// Debevec–Malik response curve: `z[j][i]` is the code value (0..=255) of sample `i` in exposure
+/// `j`; returns `g(0..=255)` (log exposure per code value, `g(128) = 0`), smoothed by `lambda`.
+pub fn response_curve(z: &[Vec<u8>], log_dt: &[f64], lambda: f64) -> Vec<f64> {
+ let p = z.len();
+ let n = z.first().map_or(0, Vec::len);
+ let mut ne = Normal::new(256 + n);
+ for j in 0..p {
+ for i in 0..n {
+ let zz = z[j][i] as usize;
+ let w = hat(zz as f64) + 1.0;
+ ne.add(&[(zz, 1.0), (256 + i, -1.0)], log_dt[j], w);
+ }
+ }
+ ne.add(&[(128, 1.0)], 0.0, 100.0);
+ for k in 1..255 {
+ let w = lambda.sqrt() * (hat(k as f64) + 1.0);
+ ne.add(&[(k - 1, 1.0), (k, -2.0), (k + 1, 1.0)], 0.0, w);
+ }
+ let Some(x) = ne.solve() else {
+ // Fall back to the sRGB curve.
+ return (0..256).map(|k| (srgb_to_linear(k as f32 / 255.0).max(1e-5) as f64).ln() - (srgb_to_linear(128.0 / 255.0) as f64).ln()).collect();
+ };
+ let mut g: Vec<f64> = x[..256].to_vec();
+ // Enforce monotonicity (noise at the extremes can fold the curve).
+ for k in (0..128).rev() {
+ g[k] = g[k].min(g[k + 1] - 1e-4);
+ }
+ for k in 129..256 {
+ g[k] = g[k].max(g[k - 1] + 1e-4);
+ }
+ g
+}
+
+fn g_at(g: &[f64], v: f32) -> f64 {
+ let x = (v.clamp(0.0, 1.0) * 255.0) as f64;
+ let i = (x.floor() as usize).min(254);
+ let t = x - i as f64;
+ g[i] * (1.0 - t) + g[i + 1] * t
+}
+
+/// Merge options.
+#[derive(Clone, Debug)]
+pub struct MergeOptions {
+ /// Linear exposure factors (time × gain), one per image.
+ pub exposures: Vec<f64>,
+ pub remove_ghosts: bool,
+ /// Exposure used where ghosts are removed (`None`: the one with most well-exposed pixels).
+ pub ghost_base: Option<usize>,
+ /// Response curves per channel (`None`: recovered from the images).
+ pub response: Option<[Vec<f64>; 3]>,
+}
+
+/// Result of [`merge`].
+#[derive(Clone, Debug)]
+pub struct Merged {
+ /// Linear radiance, straight RGBA.
+ pub px: Vec<[f32; 4]>,
+ pub response: [Vec<f64>; 3],
+ pub ghost_base: usize,
+ /// Fraction of pixels handled as ghosts.
+ pub ghost_fraction: f64,
+ /// Dynamic range of the result in stops (1st..99.9th percentile of luminance).
+ pub stops: f64,
+}
+
+/// Merges aligned exposures (`w × h` each) into a radiance map, scaled so the base exposure's
+/// well-exposed pixels keep their linear values.
+pub fn merge(w: usize, h: usize, imgs: &[&[[f32; 4]]], opts: &MergeOptions) -> Merged {
+ let p = imgs.len();
+ let log_dt: Vec<f64> = opts.exposures.iter().map(|e| e.max(1e-12).ln()).collect();
+ let well = |im: &[[f32; 4]]| im.iter().step_by(3).filter(|q| (0.1..0.9).contains(&luma(**q))).count();
+ let base = opts.ghost_base.filter(|b| *b < p).unwrap_or_else(|| (0..p).max_by_key(|&j| well(imgs[j])).unwrap_or(0));
+ let response = opts.response.clone().unwrap_or_else(|| {
+ let mut order: Vec<usize> = (0..p).collect();
+ order.sort_by(|&a, &b| opts.exposures[a].total_cmp(&opts.exposures[b]));
+ let mid = order[p / 2];
+ let samples = sample_pixels(w, h, imgs[mid], 160);
+ std::array::from_fn(|c| {
+ let z: Vec<Vec<u8>> = imgs.iter().map(|im| samples.iter().map(|&i| (im[i][c].clamp(0.0, 1.0) * 255.0).round() as u8).collect()).collect();
+ response_curve(&z, &log_dt, 40.0)
+ })
+ });
+ let mut px = vec![[0.0f32; 4]; w * h];
+ let mut ghost = vec![0.0f32; w * h];
+ let resp = &response;
+ par_rows(&mut px, w, 1, |y, row| {
+ for (x, out) in row.iter_mut().enumerate() {
+ let i = y * w + x;
+ let mut alpha = 0.0f32;
+ for c in 0..3 {
+ let (mut num, mut den) = (0.0f64, 0.0f64);
+ for j in 0..p {
+ let v = imgs[j][i][c];
+ let wt = hat(v.clamp(0.0, 1.0) as f64 * 255.0);
+ num += wt * (g_at(&resp[c], v) - log_dt[j]);
+ den += wt;
+ }
+ let le = if den > 1e-6 {
+ num / den
+ } else {
+ // Saturated everywhere: darkest exposure if bright, brightest if dark.
+ let bright = imgs.iter().map(|im| im[i][c]).sum::<f32>() / p as f32 > 0.5;
+ let j = (0..p).min_by(|&a, &b| if bright { log_dt[a].total_cmp(&log_dt[b]) } else { log_dt[b].total_cmp(&log_dt[a]) }).unwrap_or(0);
+ g_at(&resp[c], imgs[j][i][c]) - log_dt[j]
+ };
+ out[c] = le.exp() as f32;
+ }
+ for im in imgs {
+ alpha = alpha.max(im[i][3]);
+ }
+ out[3] = alpha;
+ }
+ });
+ let mut ghost_fraction = 0.0;
+ if opts.remove_ghosts && p > 1 {
+ // Weighted variance of per-exposure log radiance (luminance).
+ let score: Vec<f32> = (0..w * h)
+ .map(|i| {
+ let (mut s, mut s2, mut sw) = (0.0f64, 0.0f64, 0.0f64);
+ for j in 0..p {
+ let q = imgs[j][i];
+ let l = luma(q);
+ let wt = hat(l as f64 * 255.0);
+ if wt < 20.0 {
+ continue;
+ }
+ let lr = (0..3).map(|c| 0.33 * (g_at(&response[c], q[c]) - log_dt[j])).sum::<f64>();
+ s += wt * lr;
+ s2 += wt * lr * lr;
+ sw += wt;
+ }
+ if sw <= 0.0 {
+ return 0.0;
+ }
+ let m = s / sw;
+ ((s2 / sw - m * m).max(0.0)).sqrt() as f32
+ })
+ .collect();
+ for i in 0..w * h {
+ ghost[i] = if score[i] > 0.35 { 1.0 } else { 0.0 };
+ }
+ // Grow and feather the mask.
+ let r = (w.max(h) as f32 / 200.0).max(2.0);
+ crate::fxutil::gauss_blur_n(&mut ghost, w, h, 1, r);
+ for g in ghost.iter_mut() {
+ *g = (*g * 3.0).min(1.0);
+ }
+ ghost_fraction = ghost.iter().filter(|g| **g > 0.5).count() as f64 / (w * h).max(1) as f64;
+ let ld = log_dt[base];
+ for i in 0..w * h {
+ if ghost[i] <= 0.0 {
+ continue;
+ }
+ let q = imgs[base][i];
+ for c in 0..3 {
+ let e = (g_at(&response[c], q[c]) - ld).exp() as f32;
+ px[i][c] = px[i][c] * (1.0 - ghost[i]) + e * ghost[i];
+ }
+ }
+ }
+ // Scale per channel so the base exposure's well-exposed pixels map to their linear values.
+ for c in 0..3 {
+ let mut r: Vec<f64> = (0..w * h)
+ .step_by(5)
+ .filter_map(|i| {
+ let v = imgs[base][i][c];
+ ((0.15..0.85).contains(&v) && px[i][c] > 0.0).then(|| srgb_to_linear(v) as f64 / (px[i][c] as f64 * opts.exposures[base]))
+ })
+ .collect();
+ r.sort_by(f64::total_cmp);
+ let k = if r.is_empty() { 1.0 } else { r[r.len() / 2] } * opts.exposures[base];
+ for q in px.iter_mut() {
+ q[c] = (q[c] as f64 * k) as f32;
+ }
+ }
+ let mut l: Vec<f32> = px.iter().filter(|q| q[3] > 0.0).map(|q| luma(*q).max(1e-9)).collect();
+ l.sort_by(f32::total_cmp);
+ let stops = if l.is_empty() { 0.0 } else { (l[(l.len() as f64 * 0.999) as usize % l.len()] as f64 / l[l.len() / 100] as f64).log2() };
+ Merged { px, response, ghost_base: base, ghost_fraction, stops }
+}
+
+// ---------- tone mapping ----------
+
+/// The four 16/8-bit conversion methods of Merge to HDR Pro / HDR Toning.
+#[derive(Clone, Debug, PartialEq)]
+pub enum ToneMethod {
+ LocalAdaptation(HdrToning),
+ ExposureGamma { exposure: f32, gamma: f32 },
+ HighlightCompression,
+ EqualizeHistogram,
+}
+
+/// Tone maps linear radiance to display-encoded (sRGB curve) values in `0..=1`.
+pub fn tone_map(px: &mut [[f32; 4]], w: usize, h: usize, method: &ToneMethod) {
+ let n = px.iter().filter(|q| q[3] > 0.0).count().max(1);
+ let log_mean = (px.iter().filter(|q| q[3] > 0.0).map(|q| (luma(*q).max(1e-6) as f64).ln()).sum::<f64>() / n as f64).exp() as f32;
+ match method {
+ ToneMethod::LocalAdaptation(p) => {
+ // Key the scene to middle grey, compress in log luminance, then encode.
+ let k = 0.18 / log_mean.max(1e-6);
+ for q in px.iter_mut() {
+ for c in 0..3 {
+ q[c] *= k;
+ }
+ }
+ crate::tone::hdr_toning(px, w, h, p);
+ for q in px.iter_mut() {
+ for c in 0..3 {
+ q[c] = linear_to_srgb(q[c].clamp(0.0, 1.0));
+ }
+ }
+ }
+ ToneMethod::ExposureGamma { exposure, gamma } => {
+ let k = 2f32.powf(*exposure);
+ let g = gamma.clamp(0.1, 10.0);
+ for q in px.iter_mut() {
+ for c in 0..3 {
+ q[c] = linear_to_srgb((q[c] * k).clamp(0.0, 1.0)).powf(1.0 / g);
+ }
+ }
+ }
+ ToneMethod::HighlightCompression => {
+ let k = 0.18 / log_mean.max(1e-6);
+ for q in px.iter_mut() {
+ let l = luma(*q) * k;
+ let ld = l / (1.0 + l);
+ let r = if l > 1e-9 { ld / l * k } else { 0.0 };
+ for c in 0..3 {
+ q[c] = linear_to_srgb((q[c] * r).clamp(0.0, 1.0));
+ }
+ }
+ }
+ ToneMethod::EqualizeHistogram => {
+ const BINS: usize = 1024;
+ let lv: Vec<f32> = px.iter().map(|q| luma(*q).max(1e-7).ln()).collect();
+ let (lo, hi) = lv.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).fold((f32::MAX, f32::MIN), |(a, b), (v, _)| (a.min(*v), b.max(*v)));
+ let span = (hi - lo).max(1e-6);
+ let mut hist = vec![0f64; BINS];
+ for (v, q) in lv.iter().zip(px.iter()) {
+ if q[3] > 0.0 {
+ hist[(((v - lo) / span) * (BINS - 1) as f32) as usize] += 1.0;
+ }
+ }
+ let total: f64 = hist.iter().sum::<f64>().max(1.0);
+ let mut cdf = vec![0f32; BINS];
+ let mut acc = 0.0;
+ for b in 0..BINS {
+ acc += hist[b];
+ cdf[b] = (acc / total) as f32;
+ }
+ for (v, q) in lv.iter().zip(px.iter_mut()) {
+ let target = cdf[(((v - lo) / span).clamp(0.0, 1.0) * (BINS - 1) as f32) as usize];
+ // Display value from the CDF (encoded), keep colour ratios in linear light.
+ let tl = srgb_to_linear(target);
+ let l = luma(*q).max(1e-7);
+ for c in 0..3 {
+ q[c] = linear_to_srgb((q[c] / l * tl).clamp(0.0, 1.0));
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A radiance map with a wide range, the camera's response a gamma-ish curve.
+ fn scene(w: usize, h: usize) -> Vec<[f32; 3]> {
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32);
+ let base = 0.002 * 2f32.powf(x * 12.0); // 12 stops left to right
+ let tex = 1.0 + 0.3 * ((y * 40.0).sin());
+ [base * tex, base * tex * 0.8, base * tex * 0.6]
+ })
+ .collect()
+ }
+
+ fn camera(e: f32) -> f32 {
+ // A smooth non-sRGB response.
+ (e.max(0.0).powf(0.45)).min(1.0)
+ }
+
+ fn shoot(sc: &[[f32; 3]], dt: f32) -> Vec<[f32; 4]> {
+ sc.iter().map(|r| [camera(r[0] * dt), camera(r[1] * dt), camera(r[2] * dt), 1.0]).map(|p| p.map(|v| (v * 255.0).round() / 255.0)).collect()
+ }
+
+ #[test]
+ fn exposure_estimation_and_merge_recover_radiance() {
+ let (w, h) = (192usize, 64usize);
+ let sc = scene(w, h);
+ let dts = [0.25f32, 1.0, 4.0, 16.0];
+ let shots: Vec<Vec<[f32; 4]>> = dts.iter().map(|d| shoot(&sc, *d)).collect();
+ let refs: Vec<&[[f32; 4]]> = shots.iter().map(Vec::as_slice).collect();
+ let est = estimate_exposures(&refs);
+ // Ratios between consecutive exposures are 4× (estimated through an sRGB guess, so loose).
+ for k in 1..4 {
+ let r = est[k] / est[k - 1];
+ assert!((2.0..8.0).contains(&r), "ratio {r} ({est:?})");
+ }
+ let m = merge(w, h, &refs, &MergeOptions { exposures: dts.iter().map(|d| *d as f64).collect(), remove_ghosts: false, ghost_base: None, response: None });
+ // Radiance proportional to the scene: check log-ratios across the 12-stop ramp.
+ let probe = |x: usize| m.px[(h / 2) * w + x][1] as f64 / sc[(h / 2) * w + x][1] as f64;
+ let k0 = probe(w / 2);
+ // Within the bracket's range (brighter pixels clip in every exposure).
+ for x in [10, 50, 100, 150, 170] {
+ let r = probe(x) / k0;
+ assert!((r.ln()).abs() < 0.25, "x {x}: ratio {r}");
+ }
+ assert!(m.stops > 9.0, "stops {}", m.stops);
+ // The recovered response is monotonic.
+ assert!(m.response[0].windows(2).all(|p| p[1] > p[0]));
+ }
+
+ #[test]
+ fn ghosts_come_from_the_base_exposure() {
+ let (w, h) = (64usize, 64usize);
+ let sc: Vec<[f32; 3]> = vec![[0.2, 0.2, 0.2]; w * h];
+ let mut shots: Vec<Vec<[f32; 4]>> = [0.5f32, 1.0, 2.0].iter().map(|d| shoot(&sc, *d)).collect();
+ // A "person" only in the third exposure.
+ for y in 20..40 {
+ for x in 20..40 {
+ shots[2][y * w + x] = [0.2, 0.2, 0.2, 1.0];
+ }
+ }
+ let refs: Vec<&[[f32; 4]]> = shots.iter().map(Vec::as_slice).collect();
+ let opts = |g| MergeOptions { exposures: vec![0.5, 1.0, 2.0], remove_ghosts: g, ghost_base: Some(1), response: None };
+ let plain = merge(w, h, &refs, &opts(false));
+ let clean = merge(w, h, &refs, &opts(true));
+ let at = |m: &Merged, x: usize, y: usize| m.px[y * w + x][1];
+ let bg = at(&clean, 5, 5);
+ assert!((at(&clean, 30, 30) / bg - 1.0).abs() < 0.15, "ghost kept: {} vs {}", at(&clean, 30, 30), bg);
+ assert!((at(&plain, 30, 30) / at(&plain, 5, 5) - 1.0).abs() > 0.2);
+ assert!(clean.ghost_fraction > 0.05 && clean.ghost_base == 1);
+ }
+
+ #[test]
+ fn mtb_finds_shifts() {
+ let (w, h) = (128usize, 96usize);
+ let img: Vec<f32> = (0..w * h).map(|i| { let (x, y) = ((i % w) as f32, (i / w) as f32); 0.5 + 0.4 * ((x * 0.21).sin() * (y * 0.17).cos()) }).collect();
+ let (dx, dy) = (5i32, -3i32);
+ let shifted: Vec<f32> = (0..w * h)
+ .map(|i| {
+ let (x, y) = ((i % w) as i32 - dx, (i / w) as i32 - dy);
+ // Darker exposure of the same scene, shifted.
+ img[(y.clamp(0, h as i32 - 1) as usize) * w + x.clamp(0, w as i32 - 1) as usize] * 0.6
+ })
+ .collect();
+ let (ox, oy) = mtb_offset(w, h, &shifted, &img, 4);
+ assert_eq!((ox, oy), (dx, dy));
+ }
+
+ #[test]
+ fn tone_mapping_methods_produce_display_range() {
+ let (w, h) = (96usize, 32usize);
+ let sc = scene(w, h);
+ for method in [ToneMethod::LocalAdaptation(HdrToning { radius: 7.0, strength: 0.52, ..Default::default() }), ToneMethod::ExposureGamma { exposure: 0.0, gamma: 1.0 }, ToneMethod::HighlightCompression, ToneMethod::EqualizeHistogram] {
+ let mut px: Vec<[f32; 4]> = sc.iter().map(|r| [r[0], r[1], r[2], 1.0]).collect();
+ tone_map(&mut px, w, h, &method);
+ assert!(px.iter().all(|q| q[..3].iter().all(|v| (0.0..=1.0).contains(v))));
+ let row = |x: usize| px[(h / 2) * w + x][1];
+ assert!(row(w - 2) > row(2), "{method:?}: not increasing");
+ if !matches!(method, ToneMethod::ExposureGamma { .. }) {
+ // Compression keeps both ends of a 12-stop ramp visible.
+ assert!(row(4) > 0.01 && row(w - 4) < 0.999, "{method:?}: {} {}", row(4), row(w - 4));
+ }
+ }
+ }
+}
diff --git a/crates/algo/src/lens.rs b/crates/algo/src/lens.rs
new file mode 100644
index 000000000..f77b9f450
--- /dev/null
+++ b/crates/algo/src/lens.rs
@@ -0,0 +1,518 @@
+//! Filter › Lens Correction (and File › Automate › Lens Correction): geometric distortion,
+//! chromatic aberration, vignetting and perspective / rotation / scale, with Photoshop's edge
+//! modes.
+//!
+//! The model is the classical one:
+//!
+//! * **Distortion**: Brown–Conrady radial terms (D. C. Brown, *Decentering Distortion of Lenses*,
+//! Photogrammetric Engineering 1966; A. Conrady 1919): an output point at normalised radius
+//! `r` (1 = half the frame diagonal) samples the source at `r·(1 + k1·r² + k2·r⁴)`, plus the
+//! tangential `p1, p2` terms. Photoshop's *Remove Distortion* slider adds to `k1`
+//! (positive values correct barrel distortion).
+//! * **Chromatic aberration** (lateral): the red and blue planes are scaled radially about the
+//! centre relative to green (*Fix Red/Cyan Fringe*, *Fix Blue/Yellow Fringe*).
+//! * **Vignetting**: the lens profile's `1 + v1·r² + v2·r⁴ + v3·r⁶` falloff is divided out, then
+//! the *Vignette Amount / Midpoint* sliders apply an exposure change ramping in from the
+//! midpoint.
+//! * **Transform**: vertical / horizontal perspective as a keystone homography about the frame
+//! centre, then the angle and the scale.
+//!
+//! The geometry runs as an inverse map per output pixel (bicubic, premultiplied when there is
+//! alpha), per output tile in parallel. A few generic profiles stand in for manufacturer data
+//! (which is proprietary): [`generic_profile`] interpolates typical distortion and vignetting
+//! over the 35 mm-equivalent focal length.
+
+use photocraft_color::{ColorMode, PixelFormat};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde::{Deserialize, Serialize};
+
+use crate::photo_util::{catmull_rom, par_map};
+
+/// What fills the output where the corrected image doesn't reach.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum EdgeMode {
+ /// Repeat the edge pixels.
+ Extension,
+ #[default]
+ Transparency,
+ /// A solid colour (straight RGBA in the document's model via `to_rgba` conventions).
+ Color([f32; 4]),
+}
+
+/// A lens profile (distortion, vignetting and lateral CA coefficients).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
+pub struct LensProfile {
+ pub name: String,
+ pub k1: f64,
+ pub k2: f64,
+ pub p1: f64,
+ pub p2: f64,
+ /// Vignetting falloff `1 + v1 r² + v2 r⁴ + v3 r⁶`.
+ pub vignette: [f64; 3],
+ /// Radial scale of red / blue relative to green (`1 + ca`).
+ pub ca_red: f64,
+ pub ca_blue: f64,
+}
+
+/// Generic profile for a 35 mm-equivalent focal length (typical zoom-lens behaviour: barrel
+/// distortion and strong vignetting at the wide end, mild pincushion at the long end).
+pub fn generic_profile(focal_35mm: f64) -> LensProfile {
+ // (focal, k1, k2, v1, v2)
+ const TABLE: [(f64, f64, f64, f64, f64); 7] = [
+ (12.0, -0.16, 0.04, -0.60, 0.15),
+ (16.0, -0.11, 0.025, -0.50, 0.12),
+ (24.0, -0.06, 0.012, -0.38, 0.08),
+ (35.0, -0.025, 0.004, -0.28, 0.05),
+ (50.0, 0.0, 0.0, -0.22, 0.04),
+ (85.0, 0.012, 0.0, -0.16, 0.02),
+ (200.0, 0.02, 0.0, -0.10, 0.01),
+ ];
+ let f = focal_35mm.clamp(TABLE[0].0, TABLE[6].0);
+ let k = TABLE.windows(2).position(|w| f <= w[1].0).unwrap_or(5);
+ let (a, b) = (TABLE[k], TABLE[k + 1]);
+ // Interpolate on log focal length.
+ let t = (f.ln() - a.0.ln()) / (b.0.ln() - a.0.ln());
+ let l = |x: f64, y: f64| x + (y - x) * t;
+ LensProfile {
+ name: format!("Generic Lens ({focal_35mm:.0} mm equivalent)"),
+ k1: l(a.1, b.1),
+ k2: l(a.2, b.2),
+ vignette: [l(a.3, b.3), l(a.4, b.4), 0.0],
+ ..Default::default()
+ }
+}
+
+/// Lens Correction parameters in Photoshop's dialog units.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct LensCorrection {
+ /// Profile applied first (Auto Correction tab).
+ pub profile: Option<LensProfile>,
+ pub correct_distortion: bool,
+ pub correct_vignette: bool,
+ pub correct_ca: bool,
+ /// Remove Distortion −100..=100.
+ pub distortion: f64,
+ /// Fix Red/Cyan Fringe −100..=100.
+ pub red_cyan: f64,
+ /// Fix Blue/Yellow Fringe −100..=100.
+ pub blue_yellow: f64,
+ /// Vignette Amount −100..=100 (positive lightens the corners).
+ pub vignette_amount: f64,
+ /// Vignette Midpoint 0..=100.
+ pub vignette_midpoint: f64,
+ /// Vertical Perspective −100..=100.
+ pub vertical: f64,
+ /// Horizontal Perspective −100..=100.
+ pub horizontal: f64,
+ /// Angle in degrees (positive turns the image clockwise).
+ pub angle: f64,
+ /// Scale in percent (50..=150).
+ pub scale: f64,
+ pub edge: EdgeMode,
+}
+
+impl Default for LensCorrection {
+ fn default() -> Self {
+ LensCorrection {
+ profile: None,
+ correct_distortion: true,
+ correct_vignette: true,
+ correct_ca: true,
+ distortion: 0.0,
+ red_cyan: 0.0,
+ blue_yellow: 0.0,
+ vignette_amount: 0.0,
+ vignette_midpoint: 50.0,
+ vertical: 0.0,
+ horizontal: 0.0,
+ angle: 0.0,
+ scale: 100.0,
+ edge: EdgeMode::Transparency,
+ }
+ }
+}
+
+/// Where an output pixel samples the source: green (and alpha / non-RGB channels) at `p`,
+/// red at `pr`, blue at `pb`, then the colour is multiplied by `gain`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Sample {
+ pub p: [f64; 2],
+ pub pr: [f64; 2],
+ pub pb: [f64; 2],
+ pub gain: f32,
+}
+
+/// The inverse map of a [`LensCorrection`] over a frame.
+pub struct LensMap {
+ c: [f64; 2],
+ /// Half diagonal (radius normaliser).
+ r: f64,
+ k1: f64,
+ k2: f64,
+ p1: f64,
+ p2: f64,
+ ca_r: f64,
+ ca_b: f64,
+ vig_profile: [f64; 3],
+ vig_amount: f64,
+ vig_mid: f64,
+ /// Inverse keystone (normalised coords).
+ hinv: [f64; 9],
+ rot: (f64, f64),
+ scale: f64,
+}
+
+impl LensMap {
+ pub fn new(lc: &LensCorrection, frame: Rect) -> LensMap {
+ let c = [(frame.x0 + frame.x1) as f64 / 2.0, (frame.y0 + frame.y1) as f64 / 2.0];
+ let r = (frame.width() as f64).hypot(frame.height() as f64).max(2.0) / 2.0;
+ let prof = lc.profile.clone().unwrap_or_default();
+ let (pk1, pk2, pp1, pp2) = if lc.correct_distortion { (prof.k1, prof.k2, prof.p1, prof.p2) } else { (0.0, 0.0, 0.0, 0.0) };
+ // Keystone x' = x / (1 + h x + g y), y' = y / (1 + h x + g y) (normalised by r).
+ let g = -lc.vertical / 100.0 * 0.5;
+ let h = -lc.horizontal / 100.0 * 0.5;
+ // Inverse of [[1,0,0],[0,1,0],[h,g,1]] is [[1,0,0],[0,1,0],[-h,-g,1]].
+ let hinv = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, -h, -g, 1.0];
+ let a = lc.angle.to_radians();
+ LensMap {
+ c,
+ r,
+ k1: pk1 - lc.distortion / 100.0 * 0.25,
+ k2: pk2,
+ p1: pp1,
+ p2: pp2,
+ ca_r: if lc.correct_ca { prof.ca_red } else { 0.0 } - lc.red_cyan * 4e-5,
+ ca_b: if lc.correct_ca { prof.ca_blue } else { 0.0 } - lc.blue_yellow * 4e-5,
+ vig_profile: if lc.correct_vignette { prof.vignette } else { [0.0; 3] },
+ vig_amount: lc.vignette_amount / 100.0,
+ vig_mid: lc.vignette_midpoint.clamp(0.0, 100.0) / 100.0,
+ hinv,
+ rot: (a.sin(), a.cos()),
+ scale: (lc.scale / 100.0).clamp(0.05, 20.0),
+ }
+ }
+
+ /// Output px → where to sample (`None` when the keystone sends it to infinity).
+ pub fn sample(&self, x: f64, y: f64) -> Option<Sample> {
+ // Undo scale and rotation (about the centre).
+ let (dx, dy) = ((x - self.c[0]) / self.scale, (y - self.c[1]) / self.scale);
+ let (s, co) = self.rot;
+ let (rx, ry) = (co * dx + s * dy, -s * dx + co * dy);
+ // Undo the keystone.
+ let (nx, ny) = (rx / self.r, ry / self.r);
+ let m = &self.hinv;
+ let w = m[6] * nx + m[7] * ny + m[8];
+ if w <= 0.05 {
+ return None;
+ }
+ let (ux, uy) = (nx / w, ny / w);
+ // Lens distortion (Brown–Conrady).
+ let r2 = ux * ux + uy * uy;
+ let radial = 1.0 + self.k1 * r2 + self.k2 * r2 * r2;
+ let sx = ux * radial + 2.0 * self.p1 * ux * uy + self.p2 * (r2 + 2.0 * ux * ux);
+ let sy = uy * radial + self.p1 * (r2 + 2.0 * uy * uy) + 2.0 * self.p2 * ux * uy;
+ let to_px = |k: f64| [self.c[0] + sx * k * self.r, self.c[1] + sy * k * self.r];
+ // Vignetting on the source radius.
+ let rs2 = sx * sx + sy * sy;
+ let [v1, v2, v3] = self.vig_profile;
+ let falloff = (1.0 + v1 * rs2 + v2 * rs2 * rs2 + v3 * rs2 * rs2 * rs2).max(0.05);
+ let start = (1.0 - self.vig_mid) * 0.9;
+ let t = ((rs2.sqrt() - start) / (1.0 - start + 1e-9)).clamp(0.0, 1.0);
+ let ramp = t * t * (3.0 - 2.0 * t);
+ let gain = 2f64.powf(self.vig_amount * 1.5 * ramp) / falloff;
+ Some(Sample { p: to_px(1.0), pr: to_px(1.0 + self.ca_r), pb: to_px(1.0 + self.ca_b), gain: gain as f32 })
+ }
+}
+
+/// Smallest scale (percent) at which the corrected image covers the whole frame (Auto Scale).
+pub fn auto_scale(lc: &LensCorrection, frame: Rect) -> f64 {
+ let covers = |scale: f64| {
+ let m = LensMap::new(&LensCorrection { scale, ..lc.clone() }, frame);
+ let (x0, y0, x1, y1) = (frame.x0 as f64, frame.y0 as f64, frame.x1 as f64, frame.y1 as f64);
+ (0..=40).all(|i| {
+ let t = i as f64 / 40.0;
+ [(x0 + t * (x1 - x0), y0), (x0 + t * (x1 - x0), y1), (x0, y0 + t * (y1 - y0)), (x1, y0 + t * (y1 - y0))].iter().all(|&(x, y)| {
+ m.sample(x, y).is_some_and(|s| s.p[0] >= x0 - 0.5 && s.p[0] <= x1 + 0.5 && s.p[1] >= y0 - 0.5 && s.p[1] <= y1 + 0.5)
+ })
+ })
+ };
+ if covers(lc.scale) {
+ // Shrink while it still covers (never below the user's 100 % baseline when it covers).
+ return lc.scale;
+ }
+ let (mut lo, mut hi) = (lc.scale, lc.scale);
+ while !covers(hi) && hi < 400.0 {
+ hi *= 1.25;
+ }
+ for _ in 0..30 {
+ let mid = (lo + hi) / 2.0;
+ if covers(mid) { hi = mid } else { lo = mid }
+ }
+ hi
+}
+
+/// Angle (degrees, for [`LensCorrection::angle`]) that makes the line `a → b` horizontal or
+/// vertical, whichever it is closer to (the Straighten tool).
+pub fn straighten_angle(a: [f64; 2], b: [f64; 2]) -> f64 {
+ let deg = (b[1] - a[1]).atan2(b[0] - a[0]).to_degrees();
+ // Nearest multiple of 90°.
+ let target = (deg / 90.0).round() * 90.0;
+ -(deg - target)
+}
+
+const TILE: i32 = 128;
+
+/// Resamples `src` through an inverse map over `out_area`. `frame` is the image the map refers
+/// to: samples clamp to it, and pixels mapping outside it take the edge mode. `map` returns where
+/// each output pixel centre samples (`None` = outside).
+pub fn remap(src: &Surface, frame: Rect, out_area: Rect, edge: EdgeMode, map: &(dyn Fn(f64, f64) -> Option<Sample> + Sync)) -> Surface {
+ let sfmt = src.format();
+ let needs_alpha = matches!(edge, EdgeMode::Transparency) && !sfmt.alpha;
+ let ofmt = if needs_alpha { PixelFormat::new(sfmt.mode, sfmt.sample, true) } else { sfmt };
+ let mut out = Surface::new(ofmt);
+ if out_area.is_empty() || frame.is_empty() {
+ return out;
+ }
+ let n_in = sfmt.channels();
+ let n_out = ofmt.channels();
+ let cc = sfmt.mode.color_channels();
+ let rgb = matches!(sfmt.mode, ColorMode::Rgb | ColorMode::Indexed) && cc == 3;
+ let subtractive = sfmt.mode == ColorMode::Cmyk;
+ let lab = sfmt.mode == ColorMode::Lab;
+ let edge_px: Vec<f32> = match edge {
+ EdgeMode::Color(c) => photocraft_raster::from_rgba(&ofmt, c),
+ _ => vec![0.0; n_out],
+ };
+ let mut tiles = Vec::new();
+ let mut ty = out_area.y0;
+ while ty < out_area.y1 {
+ let mut tx = out_area.x0;
+ while tx < out_area.x1 {
+ tiles.push(Rect::new(tx, ty, (tx + TILE).min(out_area.x1), (ty + TILE).min(out_area.y1)));
+ tx += TILE;
+ }
+ ty += TILE;
+ }
+ let results = par_map(tiles.len(), |k| {
+ let t = tiles[k];
+ let (tw, th) = (t.width() as usize, t.height() as usize);
+ let samples: Vec<Option<Sample>> = (0..tw * th).map(|i| map(t.x0 as f64 + (i % tw) as f64 + 0.5, t.y0 as f64 + (i / tw) as f64 + 0.5)).collect();
+ // Source window: bbox of every sample, clamped to the frame.
+ let (mut bx0, mut by0, mut bx1, mut by1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for s in samples.iter().flatten() {
+ for p in [s.p, s.pr, s.pb] {
+ bx0 = bx0.min(p[0]);
+ by0 = by0.min(p[1]);
+ bx1 = bx1.max(p[0]);
+ by1 = by1.max(p[1]);
+ }
+ }
+ let mut data = vec![0.0f32; tw * th * n_out];
+ let win = if bx0 > bx1 {
+ Rect::EMPTY
+ } else {
+ let clamp_x = |v: f64| (v as i32).clamp(frame.x0, frame.x1);
+ let clamp_y = |v: f64| (v as i32).clamp(frame.y0, frame.y1);
+ Rect::new(clamp_x(bx0.floor() - 3.0), clamp_y(by0.floor() - 3.0), clamp_x(bx1.ceil() + 4.0), clamp_y(by1.ceil() + 4.0))
+ };
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let mut buf = if win.is_empty() { Vec::new() } else { src.read_region(win) };
+ // Premultiply colour by alpha so transparent pixels don't bleed.
+ if sfmt.alpha {
+ for px in buf.chunks_exact_mut(n_in) {
+ let a = px[n_in - 1];
+ for v in &mut px[..n_in - 1] {
+ *v *= a;
+ }
+ }
+ }
+ let fx0 = frame.x0 as f64;
+ let fy0 = frame.y0 as f64;
+ let fx1 = frame.x1 as f64;
+ let fy1 = frame.y1 as f64;
+ let bicubic = |c: usize, p: [f64; 2]| -> f32 {
+ // Pixel centres at +0.5; clamp to the frame (edge extension).
+ let x = (p[0] - 0.5).clamp(fx0, fx1 - 1.0);
+ let y = (p[1] - 0.5).clamp(fy0, fy1 - 1.0);
+ let (xi, yi) = (x.floor(), y.floor());
+ let (wx, wy) = (catmull_rom((x - xi) as f32), catmull_rom((y - yi) as f32));
+ let mut acc = 0.0f32;
+ for (j, wyv) in wy.iter().enumerate() {
+ let yy = ((yi as i32 + j as i32 - 1).clamp(win.y0, win.y1 - 1) - win.y0) as usize;
+ for (i, wxv) in wx.iter().enumerate() {
+ let xx = ((xi as i32 + i as i32 - 1).clamp(win.x0, win.x1 - 1) - win.x0) as usize;
+ acc += wxv * wyv * buf[(yy * ww + xx) * n_in + c];
+ }
+ }
+ acc
+ };
+ for (i, s) in samples.iter().enumerate() {
+ let o = &mut data[i * n_out..(i + 1) * n_out];
+ let Some(s) = s.filter(|_| ww > 0 && wh > 0) else {
+ o.copy_from_slice(&edge_px);
+ continue;
+ };
+ // Inside-frame weight (1 px soft edge) unless edges extend.
+ let inside = if matches!(edge, EdgeMode::Extension) {
+ 1.0
+ } else {
+ let fx = ((s.p[0] - fx0).min(fx1 - s.p[0]) + 0.5).clamp(0.0, 1.0);
+ let fy = ((s.p[1] - fy0).min(fy1 - s.p[1]) + 0.5).clamp(0.0, 1.0);
+ (fx * fy) as f32
+ };
+ let alpha = if sfmt.alpha { bicubic(n_in - 1, s.p).clamp(0.0, 1.0) } else { 1.0 };
+ let mut col = [0.0f32; 8];
+ for (c, v) in col.iter_mut().enumerate().take(cc) {
+ let p = if rgb && c == 0 { s.pr } else if rgb && c == 2 { s.pb } else { s.p };
+ let pm = bicubic(c, p);
+ let straight = if sfmt.alpha { if alpha > 1e-6 { pm / alpha } else { 0.0 } } else { pm };
+ let g = s.gain;
+ *v = if subtractive {
+ 1.0 - (1.0 - straight) * g
+ } else if lab {
+ if c == 0 { straight * g } else { straight }
+ } else {
+ straight * g
+ };
+ if sfmt.sample != photocraft_color::SampleType::F32 {
+ *v = v.clamp(0.0, 1.0);
+ }
+ }
+ let a_out = alpha * inside;
+ match edge {
+ EdgeMode::Color(_) if inside < 1.0 => {
+ // Blend towards the edge colour by the outside share.
+ let ea = if ofmt.alpha { edge_px[n_out - 1] } else { 1.0 };
+ let oa = alpha * inside + ea * (1.0 - inside);
+ for c in 0..cc {
+ let mixed = col[c] * alpha * inside + edge_px[c] * ea * (1.0 - inside);
+ o[c] = if oa > 1e-6 { mixed / oa } else { 0.0 };
+ }
+ if ofmt.alpha {
+ o[n_out - 1] = oa;
+ }
+ }
+ _ => {
+ o[..cc].copy_from_slice(&col[..cc]);
+ if ofmt.alpha {
+ o[n_out - 1] = a_out;
+ }
+ }
+ }
+ }
+ (t, data)
+ });
+ for (t, data) in results {
+ out.write_region(t, &data);
+ }
+ out.prune();
+ out
+}
+
+/// Applies a lens correction to `src` over `frame` (normally the canvas).
+pub fn correct(src: &Surface, frame: Rect, lc: &LensCorrection) -> Surface {
+ let map = LensMap::new(lc, frame);
+ remap(src, frame, frame, lc.edge, &|x, y| map.sample(x, y))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::SampleType;
+
+ fn grid_surface(fmt: PixelFormat, w: i32, h: i32) -> Surface {
+ let mut s = Surface::new(fmt);
+ let n = fmt.channels();
+ let mut row = vec![0.0f32; w as usize * n];
+ for y in 0..h {
+ for x in 0..w {
+ let v = if x % 16 < 2 || y % 16 < 2 { 0.9 } else { 0.3 };
+ let px = photocraft_raster::from_rgba(&fmt, [v, v * 0.8, v * 0.6, 1.0]);
+ row[x as usize * n..(x as usize + 1) * n].copy_from_slice(&px);
+ }
+ s.write_region(Rect::new(0, y, w, y + 1), &row);
+ }
+ s
+ }
+
+ #[test]
+ fn identity_is_lossless_at_all_depths() {
+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let fmt = PixelFormat::new(ColorMode::Rgb, sample, true);
+ let s = grid_surface(fmt, 96, 64);
+ let out = correct(&s, Rect::new(0, 0, 96, 64), &LensCorrection::default());
+ let (a, b) = (s.read_region(Rect::new(0, 0, 96, 64)), out.read_region(Rect::new(0, 0, 96, 64)));
+ let err = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);
+ assert!(err < 2.0 / 255.0, "{sample:?}: {err}");
+ }
+ }
+
+ #[test]
+ fn distortion_round_trip_and_edges() {
+ let frame = Rect::new(0, 0, 200, 100);
+ // A barrel-distorting profile then its correction map back the centre exactly.
+ let lc = LensCorrection { distortion: 50.0, ..Default::default() };
+ let m = LensMap::new(&lc, frame);
+ let s = m.sample(100.0, 50.0).unwrap();
+ assert!((s.p[0] - 100.0).abs() < 1e-9 && (s.p[1] - 50.0).abs() < 1e-9);
+ // Positive Remove Distortion samples corners closer to the centre (pincushion correction).
+ let c = m.sample(0.0, 0.0).unwrap();
+ assert!(c.p[0] > 5.0 && c.p[1] > 2.0, "{c:?}");
+ // Transparency leaves the uncovered corners clear; extension and colour fill them.
+ let src = grid_surface(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false), 200, 100);
+ let neg = LensCorrection { distortion: -60.0, ..Default::default() };
+ let t = correct(&src, frame, &neg);
+ assert!(t.format().alpha);
+ assert!(t.pixel(0, 0)[3] < 0.01 && t.pixel(100, 50)[3] > 0.99);
+ let e = correct(&src, frame, &LensCorrection { edge: EdgeMode::Extension, ..neg.clone() });
+ assert!(!e.format().alpha);
+ let col = correct(&src, frame, &LensCorrection { edge: EdgeMode::Color([1.0, 0.0, 0.0, 1.0]), ..neg });
+ let p = col.pixel(0, 0);
+ assert!(p[0] > 0.99 && p[1] < 0.01, "{p:?}");
+ }
+
+ #[test]
+ fn vignette_ca_perspective_and_straighten() {
+ let frame = Rect::new(0, 0, 300, 200);
+ let m = LensMap::new(&LensCorrection { vignette_amount: 100.0, ..Default::default() }, frame);
+ assert!((m.sample(150.0, 100.0).unwrap().gain - 1.0).abs() < 1e-6);
+ assert!(m.sample(1.0, 1.0).unwrap().gain > 2.0);
+ let d = LensMap::new(&LensCorrection { vignette_amount: -100.0, ..Default::default() }, frame);
+ assert!(d.sample(1.0, 1.0).unwrap().gain < 0.5);
+ // Lateral CA scales red outward relative to green.
+ let ca = LensMap::new(&LensCorrection { red_cyan: -100.0, ..Default::default() }, frame).sample(10.0, 10.0).unwrap();
+ assert!(ca.pr[0] < ca.p[0]);
+ // Vertical perspective −: the top edge samples a narrower source span (widens the top).
+ let v = LensMap::new(&LensCorrection { vertical: -50.0, ..Default::default() }, frame);
+ let (tl, tr) = (v.sample(0.0, 0.0).unwrap().p, v.sample(300.0, 0.0).unwrap().p);
+ let (bl, br) = (v.sample(0.0, 200.0).unwrap().p, v.sample(300.0, 200.0).unwrap().p);
+ assert!(tr[0] - tl[0] < br[0] - bl[0], "top {} bottom {}", tr[0] - tl[0], br[0] - bl[0]);
+ // Straighten a line tilted by 5° → −5° correction, and Auto Scale hides the corners.
+ let a = straighten_angle([0.0, 0.0], [100.0, 100.0 * 5f64.to_radians().tan()]);
+ assert!((a + 5.0).abs() < 1e-9, "{a}");
+ assert!((straighten_angle([0.0, 0.0], [3.0, 100.0]) - 1.718).abs() < 0.01);
+ let lc = LensCorrection { angle: 5.0, ..Default::default() };
+ let s = auto_scale(&lc, frame);
+ assert!(s > 105.0 && s < 130.0, "{s}");
+ let rot = LensMap::new(&LensCorrection { scale: s, ..lc }, frame);
+ assert!((0.0..=300.0).contains(&rot.sample(0.0, 0.0).unwrap().p[0]));
+ }
+
+ #[test]
+ fn generic_profiles_and_cmyk() {
+ let wide = generic_profile(16.0);
+ let tele = generic_profile(135.0);
+ assert!(wide.k1 < -0.05 && tele.k1 > 0.0 && wide.vignette[0] < tele.vignette[0]);
+ let mid = generic_profile(30.0);
+ assert!(mid.k1 < -0.025 && mid.k1 > -0.06);
+ // CMYK vignette lightening reduces ink.
+ let fmt = PixelFormat::new(ColorMode::Cmyk, SampleType::U8, false);
+ let mut s = Surface::new(fmt);
+ s.fill_rect(Rect::new(0, 0, 40, 40), &[0.5, 0.5, 0.5, 0.5]);
+ let out = correct(&s, Rect::new(0, 0, 40, 40), &LensCorrection { vignette_amount: 100.0, edge: EdgeMode::Extension, ..Default::default() });
+ assert!(out.pixel(0, 0)[0] < 0.4 && (out.pixel(20, 20)[0] - 0.5).abs() < 0.02, "{:?}", out.pixel(0, 0));
+ }
+}
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs
index 1af4eff3f..ad61a94e6 100644
--- a/crates/algo/src/lib.rs
+++ b/crates/algo/src/lib.rs
@@ -17,6 +17,8 @@
//! rayon on native targets; single-threaded on wasm).
#![forbid(unsafe_code)]
+mod artistic;
+mod artistic_fx;
mod blur;
mod blur2;
mod denoise;
@@ -29,6 +31,7 @@ mod oil;
mod other2;
mod pixelate;
mod render;
+pub mod render2;
mod stylize2;
mod video;
mod noise;
@@ -53,9 +56,19 @@ pub mod seam;
pub mod content_aware;
pub mod features;
pub mod pyramid;
+pub mod panorama;
+pub mod hdr;
+pub mod exif;
+pub mod lens;
+pub mod wideangle;
+pub mod scancrop;
+pub mod camera_raw;
+pub mod vanishing;
+mod photo_util;
mod sharpen;
mod stylize;
+pub use artistic::{GALLERY_CATEGORIES, GalleryEffect, GalleryFilter, GalleryParam, GalleryParamKind};
pub use image::{Edge, Image};
pub use params_ext::*;
@@ -290,6 +303,8 @@ pub enum FilterParams {
/// Removes the even (or odd) lines and rebuilds them by interpolation (or duplication).
DeInterlace { eliminate_even: bool, interpolate: bool },
NtscColors,
+ /// Filter Gallery: a stack of gallery effects applied in order.
+ FilterGallery { effects: Vec<GalleryEffect> },
}
impl FilterParams {
@@ -388,6 +403,10 @@ impl FilterParams {
FilterParams::HsbHsl { .. } => "HSB/HSL",
FilterParams::DeInterlace { .. } => "De-Interlace",
FilterParams::NtscColors => "NTSC Colors",
+ FilterParams::FilterGallery { effects } => match effects.as_slice() {
+ [one] => one.filter.name(),
+ _ => "Filter Gallery",
+ },
}
}
}
@@ -422,6 +441,7 @@ fn halo_ext(p: &FilterParams) -> Halo {
FilterParams::PathBlur { paths } => r(paths.iter().map(|p| p.speed.abs()).fold(0.0, f32::max) / 2.0 + 1.0),
FilterParams::Custom { .. } => r(2.0),
FilterParams::DeInterlace { .. } => r(1.0),
+ FilterParams::FilterGallery { effects } => Halo::Radius(artistic_fx::reach(effects)),
_ => Halo::Radius(0),
}
}
@@ -548,6 +568,7 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f
FilterParams::HsbHsl { input, output } => other2::hsb_hsl(src, out, ctx, *input, *output),
FilterParams::DeInterlace { eliminate_even, interpolate } => video::deinterlace(src, out, ctx, *eliminate_even, *interpolate),
FilterParams::NtscColors => video::ntsc(src, out, ctx),
+ FilterParams::FilterGallery { effects } => artistic_fx::run(effects, src, out, ctx),
}
}
diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs
new file mode 100644
index 000000000..5328a0a67
--- /dev/null
+++ b/crates/algo/src/panorama.rs
@@ -0,0 +1,1410 @@
+//! Panorama stitching for File › Automate › Photomerge and Edit › Auto-Align / Auto-Blend Layers.
+//!
+//! The pipeline follows M. Brown, D. G. Lowe, *Automatic Panoramic Image Stitching using
+//! Invariant Features*, IJCV 2007, with classical parts throughout:
+//!
+//! 1. **Features**: Harris corners + steered BRIEF ([`crate::features`]).
+//! 2. **Pair matching**: ratio-test matches, RANSAC homography, and Brown–Lowe's probabilistic
+//! verification (`inliers > 8 + 0.3·matches`).
+//! 3. **Focal length** (for cylindrical / spherical layouts): from the pairwise homographies of
+//! a rotating camera (H. Shum, R. Szeliski, *Construction of Panoramic Image Mosaics with
+//! Global and Local Alignment*, IJCV 2000: `H = K R K⁻¹` makes the columns and rows of
+//! `K⁻¹HK` orthonormal), or from EXIF.
+//! 4. **Projection + motion model** per layout: Perspective (plane, homography), Cylindrical
+//! and Spherical (keypoints mapped onto the cylinder / sphere, rigid motion there), Collage
+//! (similarity), Reposition (translation). Auto picks perspective unless the result is too
+//! stretched, then cylindrical or spherical (Photoshop's rule of thumb).
+//! 5. **Chained alignment + bundle adjustment**: a maximum spanning tree over the match graph
+//! from the reference image gives initial transforms; Levenberg–Marquardt then minimises
+//! the distance between all matched points in the panorama (optionally refining one radial
+//! distortion coefficient, Photoshop's *Geometric Distortion Correction*, and the focal
+//! length of the cylinder / sphere).
+//! 6. **Photometric**: gain compensation (Brown–Lowe §6) jointly with a radial vignetting model
+//! `log V(r) = a·r² + b·r⁴` shared by all images (D. Goldman, *Vignette and Exposure
+//! Calibration and Compensation*, PAMI 2010), solved by linear least squares in log space.
+//! 7. **Seams**: per new image, a minimum-cost path (dynamic programming, as in seam carving:
+//! S. Avidan, A. Shamir, SIGGRAPH 2007) through its overlap with the composite on the colour
+//! difference, so seams avoid places where the images disagree (moving objects, parallax).
+//! 8. **Multi-band blending**: Laplacian pyramids (P. Burt, E. Adelson, *A Multiresolution
+//! Spline with Application to Image Mosaics*, ACM TOG 1983) of each image (holes filled by
+//! push-pull so edges don't darken) weighted by the Gaussian pyramid of its seam mask.
+//!
+//! Everything is deterministic. Registration works on luminance in `0..=1` at a reduced scale;
+//! [`Placement::scaled`] maps the result back to full resolution.
+
+#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels)
+
+use crate::features::{self, Descriptor, Model};
+use crate::photo_util::{Normal, Rng, par_map, solve_dense};
+use crate::transform::Homography;
+
+/// Photomerge layouts.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Layout {
+ Auto,
+ Perspective,
+ Cylindrical,
+ Spherical,
+ Collage,
+ Reposition,
+}
+
+impl Layout {
+ pub fn parse(s: &str) -> Option<Layout> {
+ Some(match s {
+ "auto" => Layout::Auto,
+ "perspective" => Layout::Perspective,
+ "cylindrical" => Layout::Cylindrical,
+ "spherical" => Layout::Spherical,
+ "collage" => Layout::Collage,
+ "reposition" => Layout::Reposition,
+ _ => return None,
+ })
+ }
+ pub fn name(self) -> &'static str {
+ match self {
+ Layout::Auto => "auto",
+ Layout::Perspective => "perspective",
+ Layout::Cylindrical => "cylindrical",
+ Layout::Spherical => "spherical",
+ Layout::Collage => "collage",
+ Layout::Reposition => "reposition",
+ }
+ }
+ fn projection(self) -> Projection {
+ match self {
+ Layout::Cylindrical => Projection::Cylinder,
+ Layout::Spherical => Projection::Sphere,
+ _ => Projection::Plane,
+ }
+ }
+ fn motion(self) -> Motion {
+ match self {
+ Layout::Auto | Layout::Perspective => Motion::Homography,
+ Layout::Cylindrical | Layout::Spherical => Motion::Euclidean,
+ Layout::Collage => Motion::Similarity,
+ Layout::Reposition => Motion::Translation,
+ }
+ }
+}
+
+/// Surface an image is projected onto before its 2-D motion.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Projection {
+ Plane,
+ Cylinder,
+ Sphere,
+}
+
+/// 2-D motion models in projected space.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Motion {
+ Translation,
+ /// Rotation + translation.
+ Euclidean,
+ /// Rotation, uniform scale, translation.
+ Similarity,
+ Homography,
+}
+
+impl Motion {
+ fn min_points(self) -> usize {
+ match self {
+ Motion::Translation => 1,
+ Motion::Euclidean | Motion::Similarity => 2,
+ Motion::Homography => 4,
+ }
+ }
+ fn n_params(self) -> usize {
+ match self {
+ Motion::Translation => 2,
+ Motion::Euclidean => 3,
+ Motion::Similarity => 4,
+ Motion::Homography => 8,
+ }
+ }
+ fn to_params(self, h: &Homography) -> Vec<f64> {
+ let m = h.0.map(|v| v / h.0[8]);
+ match self {
+ Motion::Translation => vec![m[2], m[5]],
+ Motion::Euclidean => vec![m[3].atan2(m[0]), m[2], m[5]],
+ Motion::Similarity => vec![m[0], m[3], m[2], m[5]],
+ Motion::Homography => m[..8].to_vec(),
+ }
+ }
+ fn to_homography(self, p: &[f64]) -> Homography {
+ match self {
+ Motion::Translation => Homography([1.0, 0.0, p[0], 0.0, 1.0, p[1], 0.0, 0.0, 1.0]),
+ Motion::Euclidean => {
+ let (s, c) = p[0].sin_cos();
+ Homography([c, -s, p[1], s, c, p[2], 0.0, 0.0, 1.0])
+ }
+ Motion::Similarity => Homography([p[0], -p[1], p[2], p[1], p[0], p[3], 0.0, 0.0, 1.0]),
+ Motion::Homography => Homography([p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], 1.0]),
+ }
+ }
+}
+
+/// Least-squares fit of `motion` mapping `src[i]` → `dst[i]`.
+pub fn fit_motion(motion: Motion, src: &[[f64; 2]], dst: &[[f64; 2]]) -> Option<Homography> {
+ match motion {
+ Motion::Translation => features::fit(Model::Translation, src, dst),
+ Motion::Similarity => features::fit(Model::Similarity, src, dst),
+ Motion::Homography => features::fit(Model::Homography, src, dst),
+ Motion::Euclidean => {
+ let n = src.len();
+ if n < 2 {
+ return None;
+ }
+ let nf = n as f64;
+ let cs = src.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0] / nf, a[1] + p[1] / nf]);
+ let cd = dst.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0] / nf, a[1] + p[1] / nf]);
+ let (mut sxx, mut sxy) = (0.0, 0.0);
+ for (s, d) in src.iter().zip(dst) {
+ let (a, b) = ([s[0] - cs[0], s[1] - cs[1]], [d[0] - cd[0], d[1] - cd[1]]);
+ sxx += a[0] * b[0] + a[1] * b[1];
+ sxy += a[0] * b[1] - a[1] * b[0];
+ }
+ let th = sxy.atan2(sxx);
+ let (s, c) = th.sin_cos();
+ Some(Homography([c, -s, cd[0] - (c * cs[0] - s * cs[1]), s, c, cd[1] - (s * cs[0] + c * cs[1]), 0.0, 0.0, 1.0]))
+ }
+ }
+}
+
+/// RANSAC over [`Motion`] models; returns the refit model and its inlier indices.
+pub fn ransac_motion(motion: Motion, src: &[[f64; 2]], dst: &[[f64; 2]], iters: usize, threshold: f64, seed: u64) -> Option<(Homography, Vec<usize>)> {
+ let k = motion.min_points();
+ let n = src.len();
+ if n < k {
+ return None;
+ }
+ let mut rng = Rng(seed ^ 0x5EED_0FA1);
+ let inliers_of = |h: &Homography| -> Vec<usize> {
+ (0..n)
+ .filter(|&i| {
+ let (x, y) = h.apply(src[i][0], src[i][1]);
+ x.is_finite() && (x - dst[i][0]).hypot(y - dst[i][1]) <= threshold
+ })
+ .collect()
+ };
+ let mut best: Option<(Homography, Vec<usize>)> = None;
+ for _ in 0..iters.max(1) {
+ let mut idx: Vec<usize> = Vec::with_capacity(k);
+ if n == k {
+ idx = (0..k).collect();
+ }
+ while idx.len() < k {
+ let i = rng.below(n);
+ if !idx.contains(&i) {
+ idx.push(i);
+ }
+ }
+ let (s, d): (Vec<[f64; 2]>, Vec<[f64; 2]>) = idx.iter().map(|&i| (src[i], dst[i])).unzip();
+ let Some(h) = fit_motion(motion, &s, &d) else { continue };
+ let inl = inliers_of(&h);
+ if best.as_ref().is_none_or(|(_, b)| inl.len() > b.len()) {
+ best = Some((h, inl));
+ }
+ }
+ let (h, inl) = best?;
+ if inl.len() < k {
+ return None;
+ }
+ let (s, d): (Vec<[f64; 2]>, Vec<[f64; 2]>) = inl.iter().map(|&i| (src[i], dst[i])).unzip();
+ let h2 = fit_motion(motion, &s, &d).unwrap_or(h);
+ let inl2 = inliers_of(&h2);
+ Some(if inl2.len() >= inl.len() { (h2, inl2) } else { (h, inl) })
+}
+
+/// Where one image lands in the panorama: image px → (undistort) → projection → 2-D motion.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Placement {
+ pub projection: Projection,
+ /// Focal length in px (the projection radius).
+ pub focal: f64,
+ /// Projection centre in image px (the image centre).
+ pub center: [f64; 2],
+ /// Radial distortion `k1` on radii normalised by the focal length (0 = none).
+ pub k1: f64,
+ /// Projected coordinates → panorama coordinates.
+ pub h: Homography,
+}
+
+impl Placement {
+ /// Image px → projected coordinates (centred, in px of the focal length).
+ pub fn project(&self, x: f64, y: f64) -> [f64; 2] {
+ let (mut dx, mut dy) = (x - self.center[0], y - self.center[1]);
+ if self.k1 != 0.0 {
+ let s = 1.0 + self.k1 * (dx * dx + dy * dy) / (self.focal * self.focal);
+ dx *= s;
+ dy *= s;
+ }
+ let f = self.focal;
+ match self.projection {
+ Projection::Plane => [dx, dy],
+ Projection::Cylinder => [f * dx.atan2(f), f * dy / dx.hypot(f)],
+ Projection::Sphere => [f * dx.atan2(f), f * dy.atan2(dx.hypot(f))],
+ }
+ }
+
+ /// Projected → image px (`None` outside the valid hemisphere).
+ pub fn unproject(&self, a: f64, b: f64) -> Option<(f64, f64)> {
+ let f = self.focal;
+ let (mut dx, mut dy) = match self.projection {
+ Projection::Plane => (a, b),
+ Projection::Cylinder => {
+ let th = a / f;
+ if th.abs() >= 1.55 {
+ return None;
+ }
+ (f * th.tan(), b / th.cos())
+ }
+ Projection::Sphere => {
+ let (th, ph) = (a / f, b / f);
+ if th.abs() >= 1.55 || ph.abs() >= 1.55 {
+ return None;
+ }
+ (f * th.tan(), f * ph.tan() / th.cos())
+ }
+ };
+ if self.k1 != 0.0 {
+ // Invert r_u = r_d (1 + k1 r_d² / f²) by Newton steps on r_d.
+ let ru = dx.hypot(dy);
+ if ru > 1e-9 {
+ let mut rd = ru;
+ for _ in 0..8 {
+ let g = rd * (1.0 + self.k1 * rd * rd / (f * f)) - ru;
+ let dg = 1.0 + 3.0 * self.k1 * rd * rd / (f * f);
+ if dg.abs() < 1e-9 {
+ break;
+ }
+ rd -= g / dg;
+ }
+ if !(rd.is_finite() && rd > 0.0) {
+ return None;
+ }
+ dx *= rd / ru;
+ dy *= rd / ru;
+ }
+ }
+ Some((dx + self.center[0], dy + self.center[1]))
+ }
+
+ /// Image px → panorama px.
+ pub fn forward(&self, x: f64, y: f64) -> (f64, f64) {
+ let p = self.project(x, y);
+ self.h.apply(p[0], p[1])
+ }
+
+ /// Panorama px → image px.
+ pub fn inverse(&self, u: f64, v: f64) -> Option<(f64, f64)> {
+ let inv = self.h.inverse()?;
+ let m = &inv.0;
+ let w = m[6] * u + m[7] * v + m[8];
+ if w <= 1e-12 {
+ return None;
+ }
+ let (a, b) = inv.apply(u, v);
+ self.unproject(a, b)
+ }
+
+ /// The same placement for images `k×` larger (registration ran at `1/k` scale).
+ pub fn scaled(&self, k: f64) -> Placement {
+ let s = Homography([k, 0.0, 0.0, 0.0, k, 0.0, 0.0, 0.0, 1.0]);
+ let si = Homography([1.0 / k, 0.0, 0.0, 0.0, 1.0 / k, 0.0, 0.0, 0.0, 1.0]);
+ Placement { projection: self.projection, focal: self.focal * k, center: [self.center[0] * k, self.center[1] * k], k1: self.k1, h: s.mul(&self.h).mul(&si) }
+ }
+
+ /// Shifted in the panorama.
+ pub fn translated(&self, dx: f64, dy: f64) -> Placement {
+ let t = Homography([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]);
+ Placement { h: t.mul(&self.h), ..self.clone() }
+ }
+
+ /// Bounds `[x0, y0, x1, y1]` of a `w × h` image in the panorama (sampled along its edges).
+ pub fn bounds(&self, w: f64, h: f64) -> [f64; 4] {
+ let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
+ let n = 32;
+ for i in 0..=n {
+ let t = i as f64 / n as f64;
+ for (x, y) in [(t * w, 0.0), (t * w, h), (0.0, t * h), (w, t * h)] {
+ let (u, v) = self.forward(x, y);
+ if u.is_finite() && v.is_finite() {
+ b = [b[0].min(u), b[1].min(v), b[2].max(u), b[3].max(v)];
+ }
+ }
+ }
+ b
+ }
+}
+
+/// Keypoints and descriptors of one image (registration scale).
+#[derive(Clone, Debug, Default)]
+pub struct ImageFeatures {
+ pub w: usize,
+ pub h: usize,
+ pub points: Vec<[f64; 2]>,
+ pub desc: Vec<Descriptor>,
+}
+
+/// Detects up to `max` corners of a `w × h` luminance image and describes them.
+pub fn detect(w: usize, h: usize, luma: &[f32], valid: Option<&[bool]>, max: usize) -> ImageFeatures {
+ let min_dist = (w.max(h) as f32 / 70.0).clamp(3.0, 20.0);
+ let corners = features::harris(w, h, luma, max, min_dist, valid);
+ let desc = features::describe(w, h, luma, &corners, false);
+ ImageFeatures { w, h, points: corners.iter().map(|c| [c.x as f64, c.y as f64]).collect(), desc }
+}
+
+/// One image for [`detect_many`]: `(w, h, luma, valid)`.
+pub type PreparedImage = (usize, usize, Vec<f32>, Option<Vec<bool>>);
+
+/// [`detect`] for several images `(w, h, luma, valid)` in parallel.
+pub fn detect_many(imgs: &[PreparedImage], max: usize) -> Vec<ImageFeatures> {
+ par_map(imgs.len(), |i| {
+ let (w, h, l, v) = &imgs[i];
+ detect(*w, *h, l, v.as_deref(), max)
+ })
+}
+
+/// A verified image pair: point correspondences (image `a` px, image `b` px).
+#[derive(Clone, Debug)]
+pub struct PairMatch {
+ pub a: usize,
+ pub b: usize,
+ pub pts_a: Vec<[f64; 2]>,
+ pub pts_b: Vec<[f64; 2]>,
+ /// Homography `b → a` in image px.
+ pub homography: Homography,
+}
+
+/// Matches every pair and keeps those that pass RANSAC + the Brown–Lowe verification.
+pub fn match_pairs(feats: &[ImageFeatures]) -> Vec<PairMatch> {
+ let n = feats.len();
+ let pairs: Vec<(usize, usize)> = (0..n).flat_map(|a| (a + 1..n).map(move |b| (a, b))).collect();
+ let out = par_map(pairs.len(), |k| {
+ let (a, b) = pairs[k];
+ let (fa, fb) = (&feats[a], &feats[b]);
+ if fa.points.len() < 6 || fb.points.len() < 6 {
+ return None;
+ }
+ let m = features::match_descriptors(&fb.desc, &fa.desc, 0.8);
+ if m.len() < 8 {
+ return None;
+ }
+ let src: Vec<[f64; 2]> = m.iter().map(|&(i, _)| fb.points[i]).collect();
+ let dst: Vec<[f64; 2]> = m.iter().map(|&(_, j)| fa.points[j]).collect();
+ let thr = (fa.w.max(fa.h) as f64 / 300.0).clamp(1.5, 4.0);
+ let (hm, inl) = ransac_motion(Motion::Homography, &src, &dst, 1200, thr, (a * 131 + b) as u64)?;
+ if (inl.len() as f64) < 8.0 + 0.3 * m.len() as f64 || inl.len() < 10 {
+ return None;
+ }
+ Some(PairMatch { a, b, pts_a: inl.iter().map(|&i| dst[i]).collect(), pts_b: inl.iter().map(|&i| src[i]).collect(), homography: hm })
+ });
+ out.into_iter().flatten().collect()
+}
+
+/// Focal length (px) of a rotating camera from a homography between two of its images (image
+/// px, both centred at `c`), or `None` when the homography doesn't constrain it.
+pub fn focal_from_homography(h: &Homography, ca: [f64; 2], cb: [f64; 2]) -> Option<f64> {
+ let ta = Homography([1.0, 0.0, -ca[0], 0.0, 1.0, -ca[1], 0.0, 0.0, 1.0]);
+ let tb = Homography([1.0, 0.0, cb[0], 0.0, 1.0, cb[1], 0.0, 0.0, 1.0]);
+ let m = ta.mul(h).mul(&tb).0;
+ let pick = |c1: (f64, f64), c2: (f64, f64)| -> Option<f64> {
+ // Each candidate is (numerator, denominator) of f²; prefer the better-conditioned one.
+ let ok = |(n, d): (f64, f64)| (d.abs() > 1e-12 && n / d > 0.0).then_some((n / d, d.abs()));
+ match (ok(c1), ok(c2)) {
+ (Some(a), Some(b)) => Some(if a.1 >= b.1 { a.0 } else { b.0 }),
+ (Some(a), None) | (None, Some(a)) => Some(a.0),
+ _ => None,
+ }
+ };
+ // Columns of K⁻¹HK orthogonal and of equal norm (focal of b) …
+ let f1 = pick((-(m[0] * m[1] + m[3] * m[4]), m[6] * m[7]), (m[1] * m[1] + m[4] * m[4] - m[0] * m[0] - m[3] * m[3], m[6] * m[6] - m[7] * m[7]));
+ // … rows likewise (focal of a).
+ let f0 = pick((-(m[2] * m[5]), m[0] * m[3] + m[1] * m[4]), (m[5] * m[5] - m[2] * m[2], m[0] * m[0] + m[1] * m[1] - m[3] * m[3] - m[4] * m[4]));
+ match (f0, f1) {
+ (Some(a), Some(b)) => Some((a * b).sqrt().sqrt()),
+ (Some(a), None) | (None, Some(a)) => Some(a.sqrt()),
+ _ => None,
+ }
+}
+
+/// Options for [`align`].
+#[derive(Clone, Debug)]
+pub struct AlignOptions {
+ pub layout: Layout,
+ /// Focal length in registration px (EXIF); estimated when `None`.
+ pub focal: Option<f64>,
+ /// Image that stays put (`None`: the best-connected one).
+ pub reference: Option<usize>,
+ /// Refine a radial distortion coefficient (Geometric Distortion Correction).
+ pub geometric: bool,
+}
+
+/// Result of [`align`].
+#[derive(Clone, Debug)]
+pub struct Alignment {
+ /// The layout actually used (Auto resolved).
+ pub layout: Layout,
+ pub reference: usize,
+ /// Per image; `None` for images that couldn't be connected.
+ pub placements: Vec<Option<Placement>>,
+ pub focal: f64,
+ pub k1: f64,
+ /// Verified pairs `(a, b, inliers)`.
+ pub pairs: Vec<(usize, usize, usize)>,
+ /// RMS reprojection error (px, registration scale) after bundle adjustment.
+ pub rms: f64,
+}
+
+struct PairData {
+ a: usize,
+ b: usize,
+ pa: Vec<[f64; 2]>,
+ pb: Vec<[f64; 2]>,
+}
+
+fn base_placement(f: &ImageFeatures, projection: Projection, focal: f64, k1: f64) -> Placement {
+ Placement { projection, focal, center: [f.w as f64 / 2.0, f.h as f64 / 2.0], k1, h: Homography::IDENTITY }
+}
+
+/// Aligns images from their features. `None` when fewer than two images connect.
+pub fn align(feats: &[ImageFeatures], matches: &[PairMatch], opts: &AlignOptions) -> Option<Alignment> {
+ let n = feats.len();
+ if n < 2 || matches.is_empty() {
+ return None;
+ }
+ let focal = opts.focal.filter(|f| *f > 1.0).unwrap_or_else(|| {
+ let mut fs: Vec<f64> = matches
+ .iter()
+ .filter_map(|m| {
+ let (fa, fb) = (&feats[m.a], &feats[m.b]);
+ focal_from_homography(&m.homography, [fa.w as f64 / 2.0, fa.h as f64 / 2.0], [fb.w as f64 / 2.0, fb.h as f64 / 2.0])
+ })
+ .filter(|f| f.is_finite())
+ .collect();
+ let side = feats.iter().map(|f| f.w.max(f.h)).max().unwrap_or(1) as f64;
+ fs.retain(|f| *f > side * 0.2 && *f < side * 20.0);
+ fs.sort_by(f64::total_cmp);
+ if fs.is_empty() { side } else { fs[fs.len() / 2] }
+ });
+ if opts.layout != Layout::Auto {
+ return align_layout(feats, matches, opts, opts.layout, focal);
+ }
+ // Auto: perspective unless it is too stretched (Photoshop's rule of thumb), then cylindrical,
+ // or spherical when the panorama is also tall.
+ if let Some(a) = align_layout(feats, matches, opts, Layout::Perspective, focal)
+ && !too_stretched(feats, &a)
+ {
+ return Some(Alignment { layout: Layout::Perspective, ..a });
+ }
+ let cyl = align_layout(feats, matches, opts, Layout::Cylindrical, focal)?;
+ let (mut y0, mut y1) = (f64::MAX, f64::MIN);
+ for (p, f) in cyl.placements.iter().zip(feats) {
+ if let Some(p) = p {
+ let b = p.bounds(f.w as f64, f.h as f64);
+ y0 = y0.min(b[1]);
+ y1 = y1.max(b[3]);
+ }
+ }
+ if (y1 - y0) / cyl.focal > 1.4 {
+ return align_layout(feats, matches, opts, Layout::Spherical, cyl.focal);
+ }
+ Some(cyl)
+}
+
+/// A perspective panorama is too stretched when an image grows or shrinks a lot, flips, or
+/// the field of view exceeds about 110°.
+fn too_stretched(feats: &[ImageFeatures], a: &Alignment) -> bool {
+ let (mut x0, mut x1) = (f64::MAX, f64::MIN);
+ for (p, f) in a.placements.iter().zip(feats) {
+ let Some(p) = p else { continue };
+ let (w, h) = (f.w as f64, f.h as f64);
+ let c: Vec<(f64, f64)> = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].iter().map(|&(x, y)| p.forward(x, y)).collect();
+ // Signed area (shoelace); orientation must be preserved.
+ let area: f64 = (0..4).map(|i| c[i].0 * c[(i + 1) % 4].1 - c[(i + 1) % 4].0 * c[i].1).sum::<f64>() / 2.0;
+ let ratio = area / (w * h);
+ if !ratio.is_finite() || !(0.3..=3.0).contains(&ratio) {
+ return true;
+ }
+ let m = &p.h.0;
+ for &(x, y) in &[(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)] {
+ let q = p.project(x, y);
+ if m[6] * q[0] + m[7] * q[1] + m[8] <= 0.0 {
+ return true;
+ }
+ }
+ for (u, _) in &c {
+ x0 = x0.min(*u);
+ x1 = x1.max(*u);
+ }
+ }
+ // Horizontal field of view through the reference's focal length.
+ let fov = 2.0 * ((x1 - x0) / 2.0 / a.focal).atan();
+ fov > 110f64.to_radians()
+}
+
+fn align_layout(feats: &[ImageFeatures], matches: &[PairMatch], opts: &AlignOptions, layout: Layout, focal: f64) -> Option<Alignment> {
+ let n = feats.len();
+ let projection = layout.projection();
+ let motion = layout.motion();
+ // Pairwise motions in projected space.
+ let mut pairs: Vec<PairData> = Vec::new();
+ let mut edges: Vec<(usize, usize, usize, Homography)> = Vec::new();
+ for m in matches {
+ let (pa, pb) = (base_placement(&feats[m.a], projection, focal, 0.0), base_placement(&feats[m.b], projection, focal, 0.0));
+ let qa: Vec<[f64; 2]> = m.pts_a.iter().map(|p| pa.project(p[0], p[1])).collect();
+ let qb: Vec<[f64; 2]> = m.pts_b.iter().map(|p| pb.project(p[0], p[1])).collect();
+ let thr = (feats[m.a].w.max(feats[m.a].h) as f64 / 250.0).clamp(2.0, 5.0);
+ let Some((hm, inl)) = ransac_motion(motion, &qb, &qa, 600, thr, (m.a * 977 + m.b) as u64) else { continue };
+ if inl.len() < 8 || (inl.len() as f64) < 0.5 * m.pts_a.len() as f64 {
+ continue;
+ }
+ edges.push((m.a, m.b, inl.len(), hm));
+ // Bundle adjustment uses at most 80 evenly spread inliers per pair.
+ let step = inl.len().div_ceil(80).max(1);
+ let sel: Vec<usize> = inl.iter().step_by(step).copied().collect();
+ pairs.push(PairData { a: m.a, b: m.b, pa: sel.iter().map(|&i| m.pts_a[i]).collect(), pb: sel.iter().map(|&i| m.pts_b[i]).collect() });
+ }
+ if edges.is_empty() {
+ return None;
+ }
+ let mut degree = vec![0usize; n];
+ for e in &edges {
+ degree[e.0] += e.2;
+ degree[e.1] += e.2;
+ }
+ let reference = opts.reference.filter(|r| *r < n).unwrap_or_else(|| {
+ // Best connected; ties go to the middle image.
+ (0..n).max_by(|&i, &j| degree[i].cmp(&degree[j]).then_with(|| (j as i64 - n as i64 / 2).abs().cmp(&(i as i64 - n as i64 / 2).abs()))).unwrap_or(0)
+ });
+ // Maximum spanning tree (Prim) from the reference; transforms map projected → panorama.
+ let mut tf: Vec<Option<Homography>> = vec![None; n];
+ let rc = [feats[reference].w as f64 / 2.0, feats[reference].h as f64 / 2.0];
+ tf[reference] = Some(Homography([1.0, 0.0, rc[0], 0.0, 1.0, rc[1], 0.0, 0.0, 1.0]));
+ loop {
+ let mut best: Option<(usize, usize, Homography)> = None;
+ for e in &edges {
+ // e.3 maps b → a.
+ let cand = match (tf[e.0], tf[e.1]) {
+ (Some(ta), None) => Some((e.1, ta.mul(&e.3))),
+ (None, Some(tb)) => e.3.inverse().map(|inv| (e.0, tb.mul(&inv))),
+ _ => None,
+ };
+ if let Some((node, t)) = cand
+ && best.as_ref().is_none_or(|b| e.2 > b.1)
+ {
+ best = Some((node, e.2, t));
+ }
+ }
+ let Some((node, _, t)) = best else { break };
+ tf[node] = Some(t);
+ }
+ let placed: Vec<usize> = (0..n).filter(|&i| tf[i].is_some()).collect();
+ if placed.len() < 2 {
+ return None;
+ }
+ // Bundle adjustment (Levenberg–Marquardt, numeric Jacobian).
+ let movable: Vec<usize> = placed.iter().copied().filter(|&i| i != reference).collect();
+ let mp = motion.n_params();
+ let refine_focal = projection != Projection::Plane;
+ let n_glob = usize::from(opts.geometric) + usize::from(refine_focal);
+ let mut params: Vec<f64> = movable.iter().flat_map(|&i| motion.to_params(&tf[i].expect("placed"))).collect();
+ if opts.geometric {
+ params.push(0.0);
+ }
+ if refine_focal {
+ params.push(focal.ln());
+ }
+ let n_par = params.len();
+ let decode = |p: &[f64]| -> Vec<Option<Placement>> {
+ let k1 = if opts.geometric { p[movable.len() * mp] } else { 0.0 };
+ let f = if refine_focal { p[n_par - 1].exp() } else { focal };
+ (0..n)
+ .map(|i| {
+ let h = if i == reference {
+ tf[reference]?
+ } else {
+ let k = movable.iter().position(|&m| m == i)?;
+ motion.to_homography(&p[k * mp..(k + 1) * mp])
+ };
+ Some(Placement { h, ..base_placement(&feats[i], projection, f, k1) })
+ })
+ .collect()
+ };
+ let residuals = |p: &[f64]| -> Vec<f64> {
+ let pl = decode(p);
+ let mut r = Vec::new();
+ for pd in &pairs {
+ let (Some(a), Some(b)) = (&pl[pd.a], &pl[pd.b]) else { continue };
+ for (qa, qb) in pd.pa.iter().zip(&pd.pb) {
+ let (ua, va) = a.forward(qa[0], qa[1]);
+ let (ub, vb) = b.forward(qb[0], qb[1]);
+ r.push(ua - ub);
+ r.push(va - vb);
+ }
+ }
+ // Soft priors keep the global terms sane when few pairs constrain them.
+ if opts.geometric {
+ r.push(p[movable.len() * mp] * 20.0);
+ }
+ if refine_focal {
+ r.push((p[n_par - 1] - focal.ln()) * 2.0);
+ }
+ r
+ };
+ let cost = |r: &[f64]| r.iter().map(|v| v * v).sum::<f64>();
+ let mut cur = residuals(&params);
+ let mut lambda = 1e-3;
+ if n_par > 0 && !movable.is_empty() {
+ for _ in 0..40 {
+ let m_res = cur.len();
+ let cols: Vec<Vec<f64>> = par_map(n_par, |j| {
+ let step = 1e-6 * (1.0 + params[j].abs());
+ let mut pp = params.clone();
+ pp[j] += step;
+ let rp = residuals(&pp);
+ pp[j] -= 2.0 * step;
+ let rm = residuals(&pp);
+ (0..m_res).map(|i| (rp[i] - rm[i]) / (2.0 * step)).collect()
+ });
+ let mut jtj = vec![0.0; n_par * n_par];
+ let mut jtr = vec![0.0; n_par];
+ for a in 0..n_par {
+ jtr[a] = -cols[a].iter().zip(&cur).map(|(j, r)| j * r).sum::<f64>();
+ for b in a..n_par {
+ let v: f64 = cols[a].iter().zip(&cols[b]).map(|(x, y)| x * y).sum();
+ jtj[a * n_par + b] = v;
+ jtj[b * n_par + a] = v;
+ }
+ }
+ let mut improved = false;
+ for _ in 0..8 {
+ let mut a = jtj.clone();
+ for d in 0..n_par {
+ a[d * n_par + d] += lambda * (jtj[d * n_par + d] + 1e-9);
+ }
+ let Some(delta) = solve_dense(n_par, a, jtr.clone()) else {
+ lambda *= 10.0;
+ continue;
+ };
+ let trial: Vec<f64> = params.iter().zip(&delta).map(|(p, d)| p + d).collect();
+ let rt = residuals(&trial);
+ if cost(&rt) < cost(&cur) {
+ let gain = cost(&cur) - cost(&rt);
+ params = trial;
+ cur = rt;
+ lambda = (lambda * 0.3).max(1e-9);
+ improved = gain > 1e-10 * cost(&cur).max(1e-12);
+ break;
+ }
+ lambda *= 10.0;
+ }
+ if !improved {
+ break;
+ }
+ }
+ }
+ let placements = decode(&params);
+ let n_res = pairs.iter().map(|p| p.pa.len()).sum::<usize>().max(1);
+ let rms = (cost(&cur[..(cur.len() - n_glob).min(cur.len())]) / n_res as f64).sqrt();
+ let k1 = if opts.geometric { params[movable.len() * mp] } else { 0.0 };
+ let focal = if refine_focal { params[n_par - 1].exp() } else { focal };
+ Some(Alignment { layout, reference, placements, focal, k1, pairs: edges.iter().map(|e| (e.0, e.1, e.2)).collect(), rms })
+}
+
+// ---------- photometric ----------
+
+/// One image warped into the panorama: an axis-aligned region with colour channels and coverage.
+#[derive(Clone, Debug)]
+pub struct RoiImage {
+ pub x0: i32,
+ pub y0: i32,
+ pub w: usize,
+ pub h: usize,
+ /// Colour channels per pixel (no alpha).
+ pub ch: usize,
+ pub px: Vec<f32>,
+ /// Coverage `0..=1`.
+ pub alpha: Vec<f32>,
+}
+
+impl RoiImage {
+ fn at(&self, x: i32, y: i32) -> Option<usize> {
+ let (lx, ly) = (x - self.x0, y - self.y0);
+ (lx >= 0 && ly >= 0 && (lx as usize) < self.w && (ly as usize) < self.h).then(|| ly as usize * self.w + lx as usize)
+ }
+}
+
+/// Placements and source sizes (for the vignetting radius).
+pub type Geometry<'a> = (&'a [Placement], &'a [(usize, usize)]);
+
+/// Gains (per image, per channel) and the vignetting model found by [`photometric`].
+#[derive(Clone, Debug, PartialEq)]
+pub struct Photometric {
+ pub gains: Vec<Vec<f32>>,
+ /// `log V(r) = a·r² + b·r⁴`, `r` = distance from the image centre over the half diagonal.
+ pub vignette: [f64; 2],
+}
+
+impl Photometric {
+ /// Multiplier that corrects a pixel of image `i` at normalised squared radius `r2`.
+ pub fn factor(&self, i: usize, c: usize, r2: f64) -> f32 {
+ let v = (self.vignette[0] * r2 + self.vignette[1] * r2 * r2).exp();
+ (1.0 / (self.gains[i][c] as f64 * v)) as f32
+ }
+}
+
+/// Estimates exposure gains (`gain`) and a shared vignetting falloff (`vignette`) from the
+/// overlaps of `imgs` (`placements`/`sizes` give each panorama pixel's source radius).
+/// Without `geometry` (placements and source sizes) the vignetting model is not estimated.
+pub fn photometric(imgs: &[RoiImage], geometry: Option<Geometry>, gain: bool, vignette: bool) -> Photometric {
+ let vignette = vignette && geometry.is_some();
+ let n = imgs.len();
+ let ch = imgs.first().map_or(1, |i| i.ch);
+ let identity = Photometric { gains: vec![vec![1.0; ch]; n], vignette: [0.0, 0.0] };
+ if n == 0 || (!gain && !vignette) {
+ return identity;
+ }
+ // Overlap samples on a grid: (a, b, colours, radii²).
+ let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
+ for im in imgs {
+ x0 = x0.min(im.x0);
+ y0 = y0.min(im.y0);
+ x1 = x1.max(im.x0 + im.w as i32);
+ y1 = y1.max(im.y0 + im.h as i32);
+ }
+ let step = (((x1 - x0) as i64 * (y1 - y0) as i64 / 40_000).max(1) as f64).sqrt().ceil() as i32;
+ let r2_of = |i: usize, u: i32, v: i32| -> Option<f64> {
+ let Some((placements, sizes)) = geometry else { return Some(0.0) };
+ let (sx, sy) = placements[i].inverse(u as f64 + 0.5, v as f64 + 0.5)?;
+ let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64);
+ let (dx, dy) = (sx - w / 2.0, sy - h / 2.0);
+ Some((dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0))
+ };
+ type Sample = (usize, usize, Vec<f32>, Vec<f32>, f64, f64);
+ let mut samples: Vec<Sample> = Vec::new();
+ let mut y = y0;
+ while y < y1 {
+ let mut x = x0;
+ while x < x1 {
+ let cover: Vec<(usize, usize)> = (0..n).filter_map(|i| imgs[i].at(x, y).filter(|&k| imgs[i].alpha[k] > 0.999).map(|k| (i, k))).collect();
+ for p in 0..cover.len() {
+ for q in p + 1..cover.len() {
+ let ((a, ka), (b, kb)) = (cover[p], cover[q]);
+ let ca = imgs[a].px[ka * ch..(ka + 1) * ch].to_vec();
+ let cb = imgs[b].px[kb * ch..(kb + 1) * ch].to_vec();
+ if ca.iter().chain(&cb).any(|v| !(0.02..=0.98).contains(v)) {
+ continue;
+ }
+ // Disagreeing content (parallax, moving objects) says nothing about exposure.
+ if ca.iter().zip(&cb).any(|(x, y)| (x / y).ln().abs() > 1.0) {
+ continue;
+ }
+ let (Some(ra), Some(rb)) = (r2_of(a, x, y), r2_of(b, x, y)) else { continue };
+ samples.push((a, b, ca, cb, ra, rb));
+ }
+ }
+ x += step;
+ }
+ y += step;
+ }
+ if samples.len() < 20 {
+ return identity;
+ }
+ // Unknowns: log gain per image (per channel), then a, b (shared, from mean log intensity).
+ let sigma_n = 0.05;
+ let sigma_g = if gain { 0.15 } else { 1e-4 };
+ let mut out = identity.clone();
+ let nv = if vignette { 2 } else { 0 };
+ // Vignetting is solved on the channel mean, then gains per channel with it fixed.
+ let mut ne = Normal::new(n + nv);
+ for (a, b, ca, cb, ra, rb) in &samples {
+ let la = ca.iter().map(|v| (*v as f64).ln()).sum::<f64>() / ch as f64;
+ let lb = cb.iter().map(|v| (*v as f64).ln()).sum::<f64>() / ch as f64;
+ let mut row = vec![(*a, 1.0), (*b, -1.0)];
+ if vignette {
+ row.push((n, ra - rb));
+ row.push((n + 1, ra * ra - rb * rb));
+ }
+ ne.add(&row, la - lb, 1.0 / sigma_n);
+ }
+ for i in 0..n {
+ ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g);
+ }
+ if vignette {
+ ne.add(&[(n, 1.0)], 0.0, 0.5);
+ ne.add(&[(n + 1, 1.0)], 0.0, 0.5);
+ }
+ let Some(sol) = ne.solve() else { return out };
+ if vignette {
+ // Vignetting only darkens; clamp a runaway brightening fit.
+ out.vignette = [sol[n].clamp(-2.0, 0.5), sol[n + 1].clamp(-2.0, 2.0)];
+ }
+ if gain {
+ for c in 0..ch {
+ let mut ne = Normal::new(n);
+ for (a, b, ca, cb, ra, rb) in &samples {
+ let va = out.vignette[0] * ra + out.vignette[1] * ra * ra;
+ let vb = out.vignette[0] * rb + out.vignette[1] * rb * rb;
+ ne.add(&[(*a, 1.0), (*b, -1.0)], ((ca[c] as f64).ln() - va) - ((cb[c] as f64).ln() - vb), 1.0 / sigma_n);
+ }
+ for i in 0..n {
+ ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g);
+ }
+ if let Some(g) = ne.solve() {
+ for i in 0..n {
+ out.gains[i][c] = g[i].exp().clamp(0.2, 5.0) as f32;
+ }
+ }
+ }
+ }
+ out
+}
+
+// ---------- seams ----------
+
+/// Seam labels on a `w × h` grid (`-1` = no image): images are added in `order`; each new image
+/// takes the part of its overlap with the composite that lies on its side of the cheapest path
+/// through the overlap (cost = colour difference).
+pub fn seam_labels(w: usize, h: usize, luma: &[Vec<f32>], cover: &[Vec<bool>], order: &[usize]) -> Vec<i32> {
+ let mut label = vec![-1i32; w * h];
+ for &img in order {
+ let cov = &cover[img];
+ let mut overlap = vec![false; w * h];
+ let (mut sx, mut sy, mut no) = (0.0f64, 0.0f64, 0usize);
+ let (mut nx, mut ny, mut nn) = (0.0f64, 0.0f64, 0usize);
+ for i in 0..w * h {
+ if !cov[i] {
+ continue;
+ }
+ nx += (i % w) as f64;
+ ny += (i / w) as f64;
+ nn += 1;
+ if label[i] >= 0 {
+ overlap[i] = true;
+ sx += (i % w) as f64;
+ sy += (i / w) as f64;
+ no += 1;
+ } else {
+ label[i] = img as i32;
+ }
+ }
+ if no == 0 || nn == no {
+ continue;
+ }
+ let (ox, oy) = (sx / no as f64, sy / no as f64);
+ let (cx, cy) = (nx / nn as f64, ny / nn as f64);
+ let vertical = (cx - ox).abs() >= (cy - oy).abs();
+ // Image on the increasing side along the seam's cross axis?
+ let positive = if vertical { cx > ox } else { cy > oy };
+ let cost = |i: usize| -> f32 { 0.002 + (luma[img][i] - luma[label[i] as usize][i]).abs() };
+ let (lines, len) = if vertical { (h, w) } else { (w, h) };
+ let idx = |line: usize, k: usize| if vertical { line * w + k } else { k * w + line };
+ // DP over lines (rows for a vertical seam), within the overlap.
+ let mut acc = vec![f32::INFINITY; w * h];
+ let mut from = vec![usize::MAX; w * h];
+ let mut prev_line: Option<usize> = None;
+ for line in 0..lines {
+ let any = (0..len).any(|k| overlap[idx(line, k)]);
+ if !any {
+ continue;
+ }
+ for k in 0..len {
+ let i = idx(line, k);
+ if !overlap[i] {
+ continue;
+ }
+ let mut best = (0.0f32, usize::MAX);
+ if let Some(pl) = prev_line.filter(|pl| *pl + 1 == line) {
+ best = (f32::INFINITY, usize::MAX);
+ for dk in [-1i64, 0, 1] {
+ let kk = k as i64 + dk;
+ if kk < 0 || kk >= len as i64 {
+ continue;
+ }
+ let j = idx(pl, kk as usize);
+ if acc[j] < best.0 {
+ best = (acc[j], kk as usize);
+ }
+ }
+ if best.1 == usize::MAX {
+ best = (0.0, usize::MAX);
+ }
+ }
+ acc[i] = best.0 + cost(i);
+ from[i] = best.1;
+ }
+ prev_line = Some(line);
+ }
+ // Backtrack from the cheapest end; lines not reached keep their own best cell.
+ let mut seam = vec![usize::MAX; lines];
+ let mut line = lines;
+ while line > 0 {
+ line -= 1;
+ if seam[line] != usize::MAX {
+ continue;
+ }
+ let Some(k) = (0..len).filter(|&k| overlap[idx(line, k)]).min_by(|&a, &b| acc[idx(line, a)].total_cmp(&acc[idx(line, b)])) else { continue };
+ let (mut l, mut k) = (line, k);
+ loop {
+ seam[l] = k;
+ let f = from[idx(l, k)];
+ if f == usize::MAX || l == 0 {
+ break;
+ }
+ l -= 1;
+ if seam[l] != usize::MAX {
+ break;
+ }
+ k = f;
+ }
+ }
+ for line in 0..lines {
+ let s = seam[line];
+ if s == usize::MAX {
+ continue;
+ }
+ for k in 0..len {
+ let i = idx(line, k);
+ if overlap[i] && ((positive && k > s) || (!positive && k < s)) {
+ label[i] = img as i32;
+ }
+ }
+ }
+ }
+ label
+}
+
+// ---------- multi-band blending ----------
+
+/// Number of pyramid levels used by [`multiband`] for a seam mask of this size.
+pub fn blend_levels(w: usize, h: usize) -> usize {
+ let mut s = w.min(h);
+ let mut n = 1;
+ while s > 16 && n < 7 {
+ s /= 2;
+ n += 1;
+ }
+ n
+}
+
+fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec<f32>) {
+ let (nw, nh) = (w.div_ceil(2), h.div_ceil(2));
+ let k = [1.0f32, 4.0, 6.0, 4.0, 1.0];
+ // Separable 5-tap binomial, then decimate.
+ let mut tmp = vec![0.0f32; nw * h * ch];
+ for y in 0..h {
+ for x in 0..nw {
+ for c in 0..ch {
+ let mut s = 0.0;
+ for (t, kv) in k.iter().enumerate() {
+ let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize;
+ s += kv * src[(y * w + xx) * ch + c];
+ }
+ tmp[(y * nw + x) * ch + c] = s / 16.0;
+ }
+ }
+ }
+ let mut out = vec![0.0f32; nw * nh * ch];
+ for y in 0..nh {
+ for x in 0..nw {
+ for c in 0..ch {
+ let mut s = 0.0;
+ for (t, kv) in k.iter().enumerate() {
+ let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize;
+ s += kv * tmp[(yy * nw + x) * ch + c];
+ }
+ out[(y * nw + x) * ch + c] = s / 16.0;
+ }
+ }
+ }
+ (nw, nh, out)
+}
+
+fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec<f32> {
+ // Bilinear upsampling at half-pixel-aligned positions.
+ let mut out = vec![0.0f32; w * h * ch];
+ for y in 0..h {
+ let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32);
+ let (y0, ty) = (fy.floor() as usize, fy - fy.floor());
+ let y1 = (y0 + 1).min(sh - 1);
+ for x in 0..w {
+ let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32);
+ let (x0, tx) = (fx.floor() as usize, fx - fx.floor());
+ let x1 = (x0 + 1).min(sw - 1);
+ for c in 0..ch {
+ let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c];
+ let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx;
+ let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx;
+ out[(y * w + x) * ch + c] = top + (bot - top) * ty;
+ }
+ }
+ }
+ out
+}
+
+/// Fills pixels with zero `wt` from their surroundings (push-pull), so pyramid levels don't
+/// pull in black from outside an image.
+fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) {
+ if w <= 1 && h <= 1 {
+ return;
+ }
+ let (nw, nh) = (w.div_ceil(2), h.div_ceil(2));
+ let mut cpx = vec![0.0f32; nw * nh * ch];
+ let mut cw = vec![0.0f32; nw * nh];
+ for y in 0..h {
+ for x in 0..w {
+ let (i, j) = (y * w + x, (y / 2) * nw + x / 2);
+ let a = wt[i];
+ cw[j] += a;
+ for c in 0..ch {
+ cpx[j * ch + c] += a * px[i * ch + c];
+ }
+ }
+ }
+ for j in 0..nw * nh {
+ if cw[j] > 0.0 {
+ for c in 0..ch {
+ cpx[j * ch + c] /= cw[j];
+ }
+ cw[j] = 1.0;
+ }
+ }
+ if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) {
+ push_pull(nw, nh, ch, &mut cpx, &cw);
+ }
+ for y in 0..h {
+ for x in 0..w {
+ let i = y * w + x;
+ if wt[i] < 1.0 {
+ let j = (y / 2) * nw + x / 2;
+ let a = wt[i];
+ for c in 0..ch {
+ px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c];
+ }
+ }
+ }
+ }
+}
+
+/// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image
+/// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour
+/// channels (`ch` per pixel) and the total coverage.
+pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec<f32>], levels: usize) -> (Vec<f32>, Vec<f32>) {
+ let ch = imgs.first().map_or(1, |i| i.ch);
+ let levels = levels.max(1);
+ let align = 1i32 << (levels - 1);
+ // Level sizes of the panorama.
+ let mut sizes = vec![(w, h)];
+ for _ in 1..levels {
+ let (pw, ph) = *sizes.last().expect("non-empty");
+ sizes.push((pw.div_ceil(2), ph.div_ceil(2)));
+ }
+ let mut acc: Vec<Vec<f32>> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect();
+ let mut wsum: Vec<Vec<f32>> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect();
+ let margin = align * 4;
+ // Each image on its ROI grown by a margin and aligned to the coarsest level's grid.
+ let bands = par_map(imgs.len(), |k| {
+ let im = &imgs[k];
+ let gx0 = ((im.x0 - margin).max(0) / align) * align;
+ let gy0 = ((im.y0 - margin).max(0) / align) * align;
+ let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32);
+ let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32);
+ let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize);
+ let mut px = vec![0.0f32; gw * gh * ch];
+ let mut cov = vec![0.0f32; gw * gh];
+ let mut wt = vec![0.0f32; gw * gh];
+ for y in 0..im.h {
+ for x in 0..im.w {
+ let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0);
+ if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh {
+ continue;
+ }
+ let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize);
+ cov[g] = im.alpha[i];
+ wt[g] = weights[k][i] * im.alpha[i].min(1.0);
+ px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]);
+ }
+ }
+ let bin: Vec<f32> = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect();
+ push_pull(gw, gh, ch, &mut px, &bin);
+ // Laplacian of the colours, Gaussian of the weights.
+ let mut lap: Vec<(usize, usize, Vec<f32>)> = Vec::new();
+ let mut gau: Vec<Vec<f32>> = Vec::new();
+ let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt);
+ for l in 0..levels {
+ if l + 1 == levels {
+ lap.push((cw, chh, cur.clone()));
+ gau.push(cwt.clone());
+ break;
+ }
+ let (nw, nh, down) = reduce(cw, chh, ch, &cur);
+ let up = expand(nw, nh, ch, &down, cw, chh);
+ lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect()));
+ gau.push(cwt.clone());
+ let (_, _, wdown) = reduce(cw, chh, 1, &cwt);
+ cw = nw;
+ chh = nh;
+ cur = down;
+ cwt = wdown;
+ }
+ (gx0, gy0, lap, gau)
+ });
+ for (gx0, gy0, lap, gau) in &bands {
+ for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() {
+ let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize);
+ let (pw, ph) = sizes[l];
+ for y in 0..*lh {
+ let py = oy + y;
+ if py >= ph {
+ break;
+ }
+ for x in 0..*lw {
+ let px = ox + x;
+ if px >= pw {
+ break;
+ }
+ let (i, p) = (y * lw + x, py * pw + px);
+ let k = g[i];
+ if k <= 0.0 {
+ continue;
+ }
+ wsum[l][p] += k;
+ for c in 0..ch {
+ acc[l][p * ch + c] += k * band[i * ch + c];
+ }
+ }
+ }
+ }
+ }
+ for l in 0..levels {
+ let (pw, ph) = sizes[l];
+ for p in 0..pw * ph {
+ let k = wsum[l][p];
+ for c in 0..ch {
+ acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 };
+ }
+ }
+ }
+ // Collapse.
+ let mut cur = acc.pop().expect("levels ≥ 1");
+ for l in (0..levels - 1).rev() {
+ let (pw, ph) = sizes[l];
+ let (sw, sh) = sizes[l + 1];
+ let up = expand(sw, sh, ch, &cur, pw, ph);
+ cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect();
+ }
+ // Coverage: union of the images.
+ let mut cov = vec![0.0f32; w * h];
+ for im in imgs {
+ for y in 0..im.h {
+ for x in 0..im.w {
+ let (px, py) = (im.x0 + x as i32, im.y0 + y as i32);
+ if px < 0 || py < 0 || px as usize >= w || py as usize >= h {
+ continue;
+ }
+ let p = py as usize * w + px as usize;
+ cov[p] = cov[p].max(im.alpha[y * im.w + x]);
+ }
+ }
+ }
+ (cur, cov)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Smooth random texture: blobs over a gradient (bounded detail so Harris finds corners).
+ pub(crate) fn scene(w: usize, h: usize, seed: u64) -> Vec<f32> {
+ let mut rng = Rng(seed);
+ let mut img: Vec<f32> = (0..w * h).map(|i| 0.25 + 0.2 * ((i % w) as f32 / w as f32)).collect();
+ for _ in 0..(w * h / 900).max(40) {
+ let cx = (rng.next() % w as u64) as f64;
+ let cy = (rng.next() % h as u64) as f64;
+ let r = 3.0 + (rng.next() % 9) as f64;
+ let v = (rng.next() % 1000) as f32 / 1000.0;
+ let sq = rng.next().is_multiple_of(2);
+ let (x0, x1) = ((cx - r).max(0.0) as usize, ((cx + r) as usize + 1).min(w));
+ let (y0, y1) = ((cy - r).max(0.0) as usize, ((cy + r) as usize + 1).min(h));
+ for y in y0..y1 {
+ for x in x0..x1 {
+ let (dx, dy) = (x as f64 - cx, y as f64 - cy);
+ if if sq { dx.abs() < r && dy.abs() < r * 0.6 } else { dx.hypot(dy) < r } {
+ img[y * w + x] = v;
+ }
+ }
+ }
+ }
+ img
+ }
+
+ fn sample(img: &[f32], w: usize, h: usize, x: f64, y: f64) -> Option<f32> {
+ if x < 0.0 || y < 0.0 || x > (w - 1) as f64 || y > (h - 1) as f64 {
+ return None;
+ }
+ Some(crate::photo_util::bilinear(img, w, h, 1, 0, x as f32, y as f32))
+ }
+
+ /// Crops `tw × th` views of a scene through `map` (view px → scene px).
+ fn view(scene: &[f32], sw: usize, sh: usize, tw: usize, th: usize, map: impl Fn(f64, f64) -> (f64, f64)) -> Vec<f32> {
+ (0..tw * th)
+ .map(|i| {
+ let (x, y) = map((i % tw) as f64, (i / tw) as f64);
+ sample(scene, sw, sh, x, y).unwrap_or(0.0)
+ })
+ .collect()
+ }
+
+ #[test]
+ fn recovers_translations_and_homographies() {
+ let (sw, sh) = (640, 300);
+ let sc = scene(sw, sh, 3);
+ let (tw, th) = (260, 220);
+ // Three overlapping crops at known offsets.
+ let offs = [(20.0, 30.0), (190.0, 40.0), (360.0, 25.0)];
+ let imgs: Vec<Vec<f32>> = offs.iter().map(|&(ox, oy)| view(&sc, sw, sh, tw, th, |x, y| (x + ox, y + oy))).collect();
+ let feats: Vec<ImageFeatures> = imgs.iter().map(|im| detect(tw, th, im, None, 700)).collect();
+ let matches = match_pairs(&feats);
+ assert!(matches.len() >= 2, "{}", matches.len());
+ for layout in [Layout::Reposition, Layout::Collage, Layout::Perspective] {
+ let a = align(&feats, &matches, &AlignOptions { layout, focal: None, reference: Some(1), geometric: false }).unwrap();
+ assert_eq!(a.reference, 1);
+ for (i, p) in a.placements.iter().enumerate() {
+ let p = p.as_ref().unwrap();
+ // A point at image px (50, 60) is scene (50+ox, 60+oy); relative to image 1.
+ let (u, v) = p.forward(50.0, 60.0);
+ let (eu, ev) = (50.0 + offs[i].0 - offs[1].0, 60.0 + offs[i].1 - offs[1].1);
+ assert!((u - eu).abs() < 1.0 && (v - ev).abs() < 1.0, "{layout:?} image {i}: ({u},{v}) vs ({eu},{ev})");
+ }
+ assert!(a.rms < 1.0, "{layout:?} rms {}", a.rms);
+ }
+ // A projective view is recovered by the perspective layout.
+ let hq = Homography([1.05, 0.03, 180.0, -0.02, 1.0, 35.0, 0.0001, -0.00005, 1.0]);
+ let im2 = view(&sc, sw, sh, tw, th, |x, y| hq.apply(x, y));
+ let feats2 = vec![feats[0].clone(), detect(tw, th, &im2, None, 700)];
+ let m2 = match_pairs(&feats2);
+ let a = align(&feats2, &m2, &AlignOptions { layout: Layout::Perspective, focal: None, reference: Some(0), geometric: false }).unwrap();
+ let p = a.placements[1].as_ref().unwrap();
+ // Points inside the overlap (extrapolation beyond it is loosely constrained).
+ for (x, y) in [(20.0, 30.0), (70.0, 180.0), (40.0, 100.0)] {
+ let (sx, sy) = hq.apply(x, y);
+ let (u, v) = p.forward(x, y);
+ assert!((u - (sx - 20.0)).abs() < 1.5 && (v - (sy - 30.0)).abs() < 1.5, "({u},{v}) vs ({},{})", sx - 20.0, sy - 30.0);
+ }
+ }
+
+ #[test]
+ fn rotating_camera_focal_and_cylindrical_layout() {
+ // Views of a cylinder-mapped scene from a camera panning by 25° with f = 300 px.
+ let f = 300.0f64;
+ let (sw, sh) = (1400, 500);
+ let sc = scene(sw, sh, 9);
+ let (tw, th) = (320, 240);
+ let pans = [-25f64, 0.0, 25.0];
+ let imgs: Vec<Vec<f32>> = pans
+ .iter()
+ .map(|&deg| {
+ view(&sc, sw, sh, tw, th, |x, y| {
+ let (dx, dy) = (x - tw as f64 / 2.0, y - th as f64 / 2.0);
+ let th_ = dx.atan2(f) + deg.to_radians();
+ let hh = dy / dx.hypot(f);
+ (sw as f64 / 2.0 + f * th_, sh as f64 / 2.0 + f * hh)
+ })
+ })
+ .collect();
+ let feats: Vec<ImageFeatures> = imgs.iter().map(|im| detect(tw, th, im, None, 700)).collect();
+ let matches = match_pairs(&feats);
+ assert_eq!(matches.iter().filter(|m| m.b == m.a + 1).count(), 2);
+ let est: Vec<f64> = matches.iter().filter_map(|m| focal_from_homography(&m.homography, [160.0, 120.0], [160.0, 120.0])).collect();
+ assert!(est.iter().any(|e| (e - f).abs() / f < 0.15), "focal estimates {est:?}");
+ let a = align(&feats, &matches, &AlignOptions { layout: Layout::Cylindrical, focal: None, reference: Some(1), geometric: false }).unwrap();
+ assert!((a.focal - f).abs() / f < 0.1, "focal {}", a.focal);
+ let p = a.placements[2].as_ref().unwrap();
+ // The centre of the right image sits 25° along the cylinder.
+ let (u, _) = p.forward(160.0, 120.0);
+ let expect = 160.0 + a.focal * 25f64.to_radians();
+ assert!((u - expect).abs() < 4.0, "{u} vs {expect}");
+ assert!(a.rms < 1.5, "rms {}", a.rms);
+ // Round trip through the placement.
+ let (u, v) = p.forward(40.0, 200.0);
+ let (x, y) = p.inverse(u, v).unwrap();
+ assert!((x - 40.0).abs() < 1e-6 && (y - 200.0).abs() < 1e-6);
+ }
+
+ #[test]
+ fn placement_round_trips_all_projections() {
+ for projection in [Projection::Plane, Projection::Cylinder, Projection::Sphere] {
+ let p = Placement { projection, focal: 400.0, center: [200.0, 150.0], k1: 0.05, h: Homography([0.98, -0.1, 30.0, 0.1, 0.98, -12.0, 0.0, 0.0, 1.0]) };
+ for (x, y) in [(0.0, 0.0), (390.0, 20.0), (123.0, 280.0)] {
+ let (u, v) = p.forward(x, y);
+ let (bx, by) = p.inverse(u, v).unwrap();
+ assert!((bx - x).abs() < 1e-6 && (by - y).abs() < 1e-6, "{projection:?}");
+ }
+ let s = p.scaled(2.0);
+ let (u, v) = p.forward(100.0, 50.0);
+ let (u2, v2) = s.forward(200.0, 100.0);
+ assert!((u2 - 2.0 * u).abs() < 1e-6 && (v2 - 2.0 * v).abs() < 1e-6);
+ }
+ }
+
+ #[test]
+ fn photometric_recovers_gain_and_vignette() {
+ // Two half-overlapping views of a flat-ish scene: the second one 30 % brighter.
+ let (w, h) = (200usize, 100usize);
+ let base = |x: i32, y: i32| 0.3 + 0.2 * ((x as f32 * 0.05).sin() * (y as f32 * 0.07).cos()).abs();
+ let mut imgs = Vec::new();
+ let mut pls = Vec::new();
+ for (k, (x0, g)) in [(0, 1.0f32), (100, 1.3f32)].into_iter().enumerate() {
+ let mut px = Vec::new();
+ for y in 0..h as i32 {
+ for x in 0..w as i32 {
+ px.push(base(x + x0, y) * g);
+ }
+ }
+ imgs.push(RoiImage { x0, y0: 0, w, h, ch: 1, px, alpha: vec![1.0; w * h] });
+ pls.push(Placement { projection: Projection::Plane, focal: 200.0, center: [100.0, 50.0], k1: 0.0, h: Homography([1.0, 0.0, 100.0 + x0 as f64, 0.0, 1.0, 50.0, 0.0, 0.0, 1.0]) });
+ let _ = k;
+ }
+ let ph = photometric(&imgs, Some((&pls, &[(w, h), (w, h)])), true, false);
+ let ratio = ph.gains[1][0] / ph.gains[0][0];
+ assert!((ratio - 1.3).abs() < 0.03, "{ph:?}");
+ // With vignetting on, the flat scene (no falloff) gives a near-zero model.
+ let pv = photometric(&imgs, Some((&pls, &[(w, h), (w, h)])), true, true);
+ assert!(pv.vignette[0].abs() < 0.1, "{pv:?}");
+ }
+
+ #[test]
+ fn seams_avoid_disagreement_and_multiband_is_seamless() {
+ // Two images over a 120×40 strip, overlapping in 40..80; the second has a bright
+ // "moving object" at x 50..58 that the first doesn't.
+ let (w, h) = (120usize, 40usize);
+ let mut luma = vec![vec![0.5f32; w * h], vec![0.5f32; w * h]];
+ let cover: Vec<Vec<bool>> = vec![(0..w * h).map(|i| i % w < 80).collect(), (0..w * h).map(|i| i % w >= 40).collect()];
+ for y in 0..h {
+ for x in 50..58 {
+ luma[1][y * w + x] = 1.0;
+ }
+ }
+ let labels = seam_labels(w, h, &luma, &cover, &[0, 1]);
+ // The object column belongs to image 0 (the seam passes to its right), or entirely to 1.
+ for y in 0..h {
+ let owner: Vec<i32> = (50..58).map(|x| labels[y * w + x]).collect();
+ assert!(owner.iter().all(|o| *o == owner[0]), "row {y} split the object: {owner:?}");
+ }
+ assert_eq!(labels[5], 0);
+ assert_eq!(labels[w - 1], 1);
+ // Multi-band blend of two flat images at different levels joins smoothly.
+ let mk = |x0: i32, v: f32| RoiImage { x0, y0: 0, w: 80, h, ch: 1, px: vec![v; 80 * h], alpha: vec![1.0; 80 * h] };
+ let imgs = [mk(0, 0.3), mk(40, 0.7)];
+ let wts: Vec<Vec<f32>> = (0..2).map(|k| (0..80 * h).map(|i| { let x = (i % 80) as i32 + imgs[k].x0; if (x < 60) == (k == 0) { 1.0 } else { 0.0 } }).collect()).collect();
+ let (out, cov) = multiband(w, h, &imgs, &wts, 4);
+ let row: Vec<f32> = (0..w).map(|x| out[20 * w + x]).collect();
+ assert!((row[2] - 0.3).abs() < 0.02 && (row[w - 3] - 0.7).abs() < 0.02, "{row:?}");
+ let max_jump = row.windows(2).map(|p| (p[1] - p[0]).abs()).fold(0.0f32, f32::max);
+ assert!(max_jump < 0.1, "max step {max_jump}");
+ assert!(cov.iter().all(|c| *c == 1.0));
+ }
+}
diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs
new file mode 100644
index 000000000..91f436b93
--- /dev/null
+++ b/crates/algo/src/photo_util.rs
@@ -0,0 +1,237 @@
+//! Small numeric helpers shared by the computational-photography modules (panorama, HDR, lens,
+//! wide angle, Camera Raw): dense and sparse least squares, parallel row loops, sampling.
+
+/// Solves the dense `n × n` system `a · x = b` (row-major) by Gaussian elimination with partial
+/// pivoting. `None` when singular.
+pub(crate) fn solve_dense(n: usize, mut a: Vec<f64>, mut b: Vec<f64>) -> Option<Vec<f64>> {
+ for col in 0..n {
+ let piv = (col..n).max_by(|&i, &j| a[i * n + col].abs().total_cmp(&a[j * n + col].abs()))?;
+ if a[piv * n + col].abs() < 1e-14 {
+ return None;
+ }
+ if piv != col {
+ for k in 0..n {
+ a.swap(col * n + k, piv * n + k);
+ }
+ b.swap(col, piv);
+ }
+ let d = a[col * n + col];
+ for r in col + 1..n {
+ let f = a[r * n + col] / d;
+ if f == 0.0 {
+ continue;
+ }
+ for k in col..n {
+ a[r * n + k] -= f * a[col * n + k];
+ }
+ b[r] -= f * b[col];
+ }
+ }
+ let mut x = vec![0.0; n];
+ for r in (0..n).rev() {
+ let s: f64 = (r + 1..n).map(|k| a[r * n + k] * x[k]).sum();
+ x[r] = (b[r] - s) / a[r * n + r];
+ }
+ x.iter().all(|v| v.is_finite()).then_some(x)
+}
+
+/// Accumulates weighted rows into normal equations `AᵀA x = Aᵀb` for a dense least-squares
+/// problem with `n` unknowns.
+pub(crate) struct Normal {
+ pub n: usize,
+ pub ata: Vec<f64>,
+ pub atb: Vec<f64>,
+}
+
+impl Normal {
+ pub fn new(n: usize) -> Self {
+ Normal { n, ata: vec![0.0; n * n], atb: vec![0.0; n] }
+ }
+ /// Adds the sparse row `Σ coef·x[idx] = rhs` with weight `w` (applied squared).
+ pub fn add(&mut self, row: &[(usize, f64)], rhs: f64, w: f64) {
+ let w2 = w * w;
+ for &(i, a) in row {
+ self.atb[i] += w2 * a * rhs;
+ for &(j, b) in row {
+ self.ata[i * self.n + j] += w2 * a * b;
+ }
+ }
+ }
+ pub fn solve(self) -> Option<Vec<f64>> {
+ solve_dense(self.n, self.ata, self.atb)
+ }
+}
+
+/// A sparse least-squares problem `min Σ w²(row·x − rhs)²`, solved by conjugate gradients on the
+/// normal equations (CGLS). Used for mesh warps with thousands of unknowns.
+#[derive(Default)]
+pub(crate) struct SparseLs {
+ pub n: usize,
+ rows: Vec<(Vec<(usize, f64)>, f64)>,
+}
+
+impl SparseLs {
+ pub fn new(n: usize) -> Self {
+ SparseLs { n, rows: Vec::new() }
+ }
+ pub fn add(&mut self, row: Vec<(usize, f64)>, rhs: f64, w: f64) {
+ self.rows.push((row.into_iter().map(|(i, c)| (i, c * w)).collect(), rhs * w));
+ }
+ /// CGLS from `x0`; at most `iters` iterations.
+ pub fn solve(&self, x0: &[f64], iters: usize) -> Vec<f64> {
+ let n = self.n;
+ let mut x = x0.to_vec();
+ let ax = |x: &[f64]| -> Vec<f64> { self.rows.iter().map(|(r, _)| r.iter().map(|&(i, c)| c * x[i]).sum()).collect() };
+ let atv = |v: &[f64]| -> Vec<f64> {
+ let mut out = vec![0.0; n];
+ for ((r, _), vi) in self.rows.iter().zip(v) {
+ for &(i, c) in r {
+ out[i] += c * vi;
+ }
+ }
+ out
+ };
+ let mut r: Vec<f64> = self.rows.iter().zip(ax(&x)).map(|((_, b), a)| b - a).collect();
+ let mut s = atv(&r);
+ let mut p = s.clone();
+ let mut gamma: f64 = s.iter().map(|v| v * v).sum();
+ let g0 = gamma.max(1e-30);
+ for _ in 0..iters {
+ if gamma <= g0 * 1e-20 {
+ break;
+ }
+ let q = ax(&p);
+ let qq: f64 = q.iter().map(|v| v * v).sum();
+ if qq <= 1e-300 {
+ break;
+ }
+ let alpha = gamma / qq;
+ for i in 0..n {
+ x[i] += alpha * p[i];
+ }
+ for (ri, qi) in r.iter_mut().zip(&q) {
+ *ri -= alpha * qi;
+ }
+ s = atv(&r);
+ let g1: f64 = s.iter().map(|v| v * v).sum();
+ let beta = g1 / gamma;
+ gamma = g1;
+ for i in 0..n {
+ p[i] = s[i] + beta * p[i];
+ }
+ }
+ x
+ }
+}
+
+/// Runs `f(y, row)` for every row of a `w × h × ch` buffer, in parallel on native targets.
+pub(crate) fn par_rows<T: Send + Sync>(buf: &mut [T], w: usize, ch: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) {
+ let stride = (w * ch).max(1);
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ buf.par_chunks_mut(stride).enumerate().for_each(|(y, row)| f(y, row));
+ }
+ #[cfg(target_arch = "wasm32")]
+ buf.chunks_mut(stride).enumerate().for_each(|(y, row)| f(y, row));
+}
+
+/// Maps `f` over `0..n` (in parallel on native targets), keeping order.
+pub(crate) fn par_map<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ (0..n).into_par_iter().map(f).collect()
+ }
+ #[cfg(target_arch = "wasm32")]
+ (0..n).map(f).collect()
+}
+
+/// Deterministic 64-bit generator (SplitMix64).
+pub(crate) struct Rng(pub u64);
+impl Rng {
+ pub fn next(&mut self) -> u64 {
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ let mut z = self.0;
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+ }
+ pub fn below(&mut self, n: usize) -> usize {
+ (self.next() % n.max(1) as u64) as usize
+ }
+}
+
+/// Integer hash → `0..1` (position-keyed noise, independent of tiling).
+pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 {
+ let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ seed.wrapping_mul(0x1656_67B1_9E37_79F9);
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^= z >> 31;
+ (z >> 40) as f32 / (1u64 << 24) as f32
+}
+
+/// sRGB transfer function, decode (extended linearly below 0 and as a power above 1).
+pub(crate) fn srgb_to_linear(v: f32) -> f32 {
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+}
+
+/// sRGB transfer function, encode.
+pub(crate) fn linear_to_srgb(v: f32) -> f32 {
+ if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
+}
+
+/// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges.
+pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 {
+ let x = x.clamp(0.0, (w - 1) as f32);
+ let y = y.clamp(0.0, (h - 1) as f32);
+ let (x0, y0) = (x.floor() as usize, y.floor() as usize);
+ let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
+ let (tx, ty) = (x - x0 as f32, y - y0 as f32);
+ let p = |xx: usize, yy: usize| buf[(yy * w + xx) * ch + c];
+ let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx;
+ let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx;
+ top + (bot - top) * ty
+}
+
+/// Catmull-Rom weights for a fractional offset `t`.
+pub(crate) fn catmull_rom(t: f32) -> [f32; 4] {
+ let t2 = t * t;
+ let t3 = t2 * t;
+ [-0.5 * t3 + t2 - 0.5 * t, 1.5 * t3 - 2.5 * t2 + 1.0, -1.5 * t3 + 2.0 * t2 + 0.5 * t, 0.5 * t3 - 0.5 * t2]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dense_and_sparse_solvers_agree() {
+ // Overdetermined line fit y = 2x + 1.
+ let mut ne = Normal::new(2);
+ let mut sp = SparseLs::new(2);
+ for x in 0..10 {
+ let y = 2.0 * x as f64 + 1.0;
+ ne.add(&[(0, x as f64), (1, 1.0)], y, 1.0);
+ sp.add(vec![(0, x as f64), (1, 1.0)], y, 1.0);
+ }
+ let a = ne.solve().unwrap();
+ let b = sp.solve(&[0.0, 0.0], 50);
+ assert!((a[0] - 2.0).abs() < 1e-9 && (a[1] - 1.0).abs() < 1e-9);
+ assert!((b[0] - 2.0).abs() < 1e-6 && (b[1] - 1.0).abs() < 1e-6, "{b:?}");
+ assert!(solve_dense(2, vec![1.0, 2.0, 2.0, 4.0], vec![1.0, 2.0]).is_none());
+ }
+
+ #[test]
+ fn srgb_round_trip_and_sampling() {
+ for v in [0.0f32, 0.01, 0.2, 0.5, 1.0] {
+ assert!((linear_to_srgb(srgb_to_linear(v)) - v).abs() < 1e-5);
+ }
+ let buf = [0.0f32, 1.0, 2.0, 3.0];
+ assert!((bilinear(&buf, 2, 2, 1, 0, 0.5, 0.5) - 1.5).abs() < 1e-6);
+ let w = catmull_rom(0.3);
+ assert!((w.iter().sum::<f32>() - 1.0).abs() < 1e-6);
+ let a = hash01(3, 4, 1);
+ assert!((0.0..1.0).contains(&a) && a == hash01(3, 4, 1) && a != hash01(4, 3, 1));
+ }
+}
diff --git a/crates/algo/src/render2.rs b/crates/algo/src/render2.rs
new file mode 100644
index 000000000..412388eea
--- /dev/null
+++ b/crates/algo/src/render2.rs
@@ -0,0 +1,1423 @@
+//! Procedural renderers of Filter › Render: Flame, Picture Frame and Tree.
+//!
+//! Each renderer turns its options into a list of anti-aliased vector
+//! primitives ([`Prim`]: tapered capsules and shaded ellipses, blended
+//! normally or additively). [`composite`] rasterizes the list over a surface
+//! tile by tile (in parallel on native targets), in straight sRGB converted to
+//! and from the surface's own colour model and depth, mixed by the selection.
+//!
+//! The shapes are our own designs (L-system-like recursive branching for
+//! trees, turbulent flame strands, ornaments walked along the frame edge),
+//! built from observation of what the options do, not from any reference
+//! implementation.
+
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+use serde::{Deserialize, Serialize};
+
+// ---------------------------------------------------------------------------
+// Primitives and compositing
+// ---------------------------------------------------------------------------
+
+/// Geometry of a primitive (document pixel coordinates).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Shape {
+ /// A segment from `a` to `b` whose radius goes from `ra` to `rb`; colour goes `c0` → `c1` along it.
+ Capsule { a: (f32, f32), b: (f32, f32), ra: f32, rb: f32 },
+ /// An ellipse rotated by `angle` radians; colour goes `c0` (centre) → `c1` (rim).
+ Ellipse { c: (f32, f32), rx: f32, ry: f32, angle: f32 },
+}
+
+/// One drawable primitive. Colours are straight sRGB RGBA (0–1).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Prim {
+ pub shape: Shape,
+ pub c0: [f32; 4],
+ pub c1: [f32; 4],
+ /// Edge softness in pixels (≥ 1 for anti-aliasing; larger for glows).
+ pub soft: f32,
+ /// Additive (glow) instead of normal blending.
+ pub add: bool,
+}
+
+impl Prim {
+ pub fn capsule(a: (f32, f32), b: (f32, f32), ra: f32, rb: f32, c0: [f32; 4], c1: [f32; 4]) -> Prim {
+ Prim { shape: Shape::Capsule { a, b, ra, rb }, c0, c1, soft: 1.0, add: false }
+ }
+ pub fn ellipse(c: (f32, f32), rx: f32, ry: f32, angle: f32, c0: [f32; 4], c1: [f32; 4]) -> Prim {
+ Prim { shape: Shape::Ellipse { c, rx, ry, angle }, c0, c1, soft: 1.0, add: false }
+ }
+ pub fn disc(c: (f32, f32), r: f32, col: [f32; 4]) -> Prim {
+ Prim::ellipse(c, r, r, 0.0, col, col)
+ }
+ fn with_soft(mut self, s: f32) -> Prim {
+ self.soft = s;
+ self
+ }
+ fn additive(mut self) -> Prim {
+ self.add = true;
+ self
+ }
+
+ /// Pixel bounds this primitive can touch.
+ pub fn bounds(&self) -> Rect {
+ let s = self.soft.max(1.0) + 1.0;
+ let (x0, y0, x1, y1) = match self.shape {
+ Shape::Capsule { a, b, ra, rb } => {
+ let r = ra.max(rb) + s;
+ (a.0.min(b.0) - r, a.1.min(b.1) - r, a.0.max(b.0) + r, a.1.max(b.1) + r)
+ }
+ Shape::Ellipse { c, rx, ry, .. } => {
+ let r = rx.max(ry) + s;
+ (c.0 - r, c.1 - r, c.0 + r, c.1 + r)
+ }
+ };
+ if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
+ return Rect::EMPTY;
+ }
+ let cl = |v: f32| v.clamp(-1.0e8, 1.0e8) as i32;
+ Rect::new(cl(x0.floor()), cl(y0.floor()), cl(x1.ceil()), cl(y1.ceil()))
+ }
+
+ /// Coverage (0–1) and colour position (0–1) at a pixel centre.
+ #[inline]
+ fn eval(&self, x: f32, y: f32) -> (f32, f32) {
+ let soft = self.soft.max(1.0);
+ match self.shape {
+ Shape::Capsule { a, b, ra, rb } => {
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let l2 = dx * dx + dy * dy;
+ let t = if l2 > 1e-9 { (((x - a.0) * dx + (y - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
+ let (px, py) = (a.0 + dx * t - x, a.1 + dy * t - y);
+ let d = (px * px + py * py).sqrt();
+ let r = ra + (rb - ra) * t;
+ // Hairlines thinner than a pixel fade instead of vanishing.
+ let thin = (2.0 * r).clamp(0.0, 1.0);
+ (((r.max(0.5) - d) / soft + 0.5).clamp(0.0, 1.0) * thin, t)
+ }
+ Shape::Ellipse { c, rx, ry, angle } => {
+ let (s, co) = angle.sin_cos();
+ let (dx, dy) = (x - c.0, y - c.1);
+ let (u, v) = (dx * co + dy * s, -dx * s + dy * co);
+ let (rx, ry) = (rx.max(0.05), ry.max(0.05));
+ let e = ((u / rx).powi(2) + (v / ry).powi(2)).sqrt();
+ let edge = (1.0 - e) * rx.min(ry);
+ let thin = (2.0 * rx.min(ry)).clamp(0.0, 1.0);
+ ((edge / soft + 0.5).clamp(0.0, 1.0) * thin, e.min(1.0))
+ }
+ }
+ }
+}
+
+#[inline]
+fn lerp4(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] {
+ [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t]
+}
+
+/// Rasterizes `prims` (in order) into a premultiplied RGBA buffer covering `t`.
+fn raster_tile(prims: &[Prim], idx: &[u32], t: Rect) -> Vec<[f32; 4]> {
+ let w = t.width() as usize;
+ let mut buf = vec![[0.0f32; 4]; w * t.height() as usize];
+ for &k in idx {
+ let p = &prims[k as usize];
+ let r = p.bounds().intersect(&t);
+ if r.is_empty() {
+ continue;
+ }
+ for y in r.y0..r.y1 {
+ let row = (y - t.y0) as usize * w;
+ for x in r.x0..r.x1 {
+ let (cov, ct) = p.eval(x as f32 + 0.5, y as f32 + 0.5);
+ if cov <= 0.0 {
+ continue;
+ }
+ let c = if p.c0 == p.c1 { p.c0 } else { lerp4(p.c0, p.c1, ct) };
+ let a = (c[3] * cov).clamp(0.0, 1.0);
+ if a <= 0.0 {
+ continue;
+ }
+ let d = &mut buf[row + (x - t.x0) as usize];
+ if p.add {
+ d[0] += c[0] * a;
+ d[1] += c[1] * a;
+ d[2] += c[2] * a;
+ d[3] += a * (1.0 - d[3]);
+ } else {
+ let k = 1.0 - a;
+ d[0] = c[0] * a + d[0] * k;
+ d[1] = c[1] * a + d[1] * k;
+ d[2] = c[2] * a + d[2] * k;
+ d[3] = a + d[3] * k;
+ }
+ }
+ }
+ }
+ buf
+}
+
+/// Size of the tiles [`composite`] works in.
+const CTILE: i32 = 128;
+
+/// Draws `prims` over `surface` inside `clip`, mixed by the selection coverage
+/// (channel 0 of `selection`). Returns the bounds of what was drawn.
+pub fn composite(surface: &mut Surface, prims: &[Prim], clip: Rect, selection: Option<&Surface>) -> Rect {
+ let mut used = Rect::EMPTY;
+ let bounds: Vec<Rect> = prims.iter().map(|p| p.bounds().intersect(&clip)).collect();
+ for b in &bounds {
+ if !b.is_empty() {
+ used = if used.is_empty() { *b } else { used.union(b) };
+ }
+ }
+ if used.is_empty() {
+ return used;
+ }
+ // Bin primitives into tiles (order preserved within a tile).
+ let tx0 = used.x0.div_euclid(CTILE);
+ let ty0 = used.y0.div_euclid(CTILE);
+ let tx1 = (used.x1 - 1).div_euclid(CTILE);
+ let ty1 = (used.y1 - 1).div_euclid(CTILE);
+ let (nx, ny) = ((tx1 - tx0 + 1) as usize, (ty1 - ty0 + 1) as usize);
+ let mut bins: Vec<Vec<u32>> = vec![Vec::new(); nx * ny];
+ for (k, b) in bounds.iter().enumerate() {
+ if b.is_empty() {
+ continue;
+ }
+ for ty in b.y0.div_euclid(CTILE)..=(b.y1 - 1).div_euclid(CTILE) {
+ for tx in b.x0.div_euclid(CTILE)..=(b.x1 - 1).div_euclid(CTILE) {
+ bins[(ty - ty0) as usize * nx + (tx - tx0) as usize].push(k as u32);
+ }
+ }
+ }
+ let fmt = surface.format();
+ let n = fmt.channels();
+ let jobs: Vec<(Rect, &Vec<u32>)> = bins
+ .iter()
+ .enumerate()
+ .filter(|(_, b)| !b.is_empty())
+ .map(|(i, b)| {
+ let (tx, ty) = (tx0 + (i % nx) as i32, ty0 + (i / nx) as i32);
+ (Rect::new(tx * CTILE, ty * CTILE, (tx + 1) * CTILE, (ty + 1) * CTILE).intersect(&clip), b)
+ })
+ .filter(|(r, _)| !r.is_empty())
+ .collect();
+ let src: &Surface = surface;
+ let run = |(t, idx): &(Rect, &Vec<u32>)| -> (Rect, Vec<f32>) {
+ let paint = raster_tile(prims, idx, *t);
+ let mut data = src.read_region(*t);
+ let sel = selection.map(|s| s.read_region(*t));
+ let sn = selection.map_or(1, Surface::channels);
+ let mut tmp = [0.0f32; 8];
+ for (i, px) in data.chunks_exact_mut(n).enumerate() {
+ let s = paint[i];
+ let k = sel.as_ref().map_or(1.0, |v| v[i * sn].clamp(0.0, 1.0));
+ let sa = s[3].clamp(0.0, 1.0) * k;
+ if sa <= 0.0 {
+ continue;
+ }
+ let inv = 1.0 / s[3].max(1e-6);
+ let sc = [(s[0] * inv).clamp(0.0, 1.0), (s[1] * inv).clamp(0.0, 1.0), (s[2] * inv).clamp(0.0, 1.0)];
+ let d = to_rgba(&fmt, px);
+ let da = if fmt.alpha { d[3] } else { 1.0 };
+ let oa = sa + da * (1.0 - sa);
+ let mix = |sv: f32, dv: f32| if oa > 1e-7 { (sv * sa + dv * da * (1.0 - sa)) / oa } else { 0.0 };
+ let o = [mix(sc[0], d[0]), mix(sc[1], d[1]), mix(sc[2], d[2]), oa];
+ let m = from_rgba_into(&fmt, o, &mut tmp);
+ px.copy_from_slice(&tmp[..m.min(n)]);
+ }
+ (*t, data)
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ let results: Vec<(Rect, Vec<f32>)> = {
+ use rayon::prelude::*;
+ jobs.par_iter().map(run).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let results: Vec<(Rect, Vec<f32>)> = jobs.iter().map(run).collect();
+ for (t, data) in results {
+ surface.write_region(t, &data);
+ }
+ used
+}
+
+// ---------------------------------------------------------------------------
+// Randomness
+// ---------------------------------------------------------------------------
+
+/// Small deterministic PRNG (SplitMix64).
+#[derive(Clone, Debug)]
+pub struct Rng(u64);
+
+impl Rng {
+ pub fn new(seed: u32, salt: u64) -> Rng {
+ Rng(((seed as u64) << 32) ^ salt.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ 0x2545_F491_4F6C_DD1D)
+ }
+ pub fn next_u64(&mut self) -> u64 {
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ let mut z = self.0;
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+ }
+ /// Uniform in [0, 1).
+ pub fn f(&mut self) -> f32 {
+ (self.next_u64() >> 40) as f32 / (1u64 << 24) as f32
+ }
+ /// Uniform in [a, b).
+ pub fn range(&mut self, a: f32, b: f32) -> f32 {
+ a + (b - a) * self.f()
+ }
+ /// Uniform in [-1, 1).
+ pub fn sym(&mut self) -> f32 {
+ self.f() * 2.0 - 1.0
+ }
+}
+
+/// Smooth 1-D value noise in [-1, 1].
+fn noise1(x: f32, seed: u64) -> f32 {
+ let h = |i: i64| -> f32 {
+ let mut r = Rng((i as u64).wrapping_mul(0xD6E8_FEB8_6659_FD93) ^ seed);
+ r.sym()
+ };
+ let i = x.floor();
+ let f = x - i;
+ let i = i as i64;
+ let t = f * f * (3.0 - 2.0 * f);
+ h(i) + (h(i + 1) - h(i)) * t
+}
+
+/// Two octaves of [`noise1`].
+fn fbm1(x: f32, seed: u64) -> f32 {
+ (noise1(x, seed) + 0.5 * noise1(x * 2.13 + 7.1, seed ^ 0xA5A5)) / 1.5
+}
+
+// ---------------------------------------------------------------------------
+// Polylines
+// ---------------------------------------------------------------------------
+
+/// A polyline parameterized by arc length.
+struct Spine {
+ pts: Vec<(f32, f32)>,
+ cum: Vec<f32>,
+}
+
+impl Spine {
+ fn new(pts: Vec<(f32, f32)>) -> Spine {
+ let mut cum = vec![0.0];
+ for w in pts.windows(2) {
+ let l = ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt();
+ cum.push(cum.last().copied().unwrap_or(0.0) + l);
+ }
+ Spine { pts, cum }
+ }
+ fn len(&self) -> f32 {
+ self.cum.last().copied().unwrap_or(0.0)
+ }
+ /// Point and unit tangent at arc length `s`.
+ fn at(&self, s: f32) -> ((f32, f32), (f32, f32)) {
+ let n = self.pts.len();
+ if n == 0 {
+ return ((0.0, 0.0), (1.0, 0.0));
+ }
+ if n == 1 {
+ return (self.pts[0], (0.0, -1.0));
+ }
+ let s = s.clamp(0.0, self.len());
+ let k = match self.cum.binary_search_by(|v| v.partial_cmp(&s).unwrap_or(std::cmp::Ordering::Less)) {
+ Ok(i) => i.min(n - 2),
+ Err(i) => i.saturating_sub(1).min(n - 2),
+ };
+ let (a, b) = (self.pts[k], self.pts[k + 1]);
+ let seg = (self.cum[k + 1] - self.cum[k]).max(1e-6);
+ let t = ((s - self.cum[k]) / seg).clamp(0.0, 1.0);
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let l = (dx * dx + dy * dy).sqrt().max(1e-6);
+ ((a.0 + dx * t, a.1 + dy * t), (dx / l, dy / l))
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Flame
+// ---------------------------------------------------------------------------
+
+/// Flame placement (Photoshop's six flame types).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum FlameType {
+ /// One flame whose spine is the path (path start = flame base).
+ #[default]
+ OneFlameAlongPath,
+ /// Flames at `interval` along the path, rising from its left side.
+ MultipleFlamesAlongPath,
+ /// Flames at `interval` along the path, pointing along the path's direction.
+ MultipleFlamesPathDirections,
+ /// Like `multipleFlamesAlongPath` with strongly varying lengths.
+ MultipleFlamesVariousLength,
+ /// A candle flame at the start of each subpath.
+ CandleLight,
+ /// Flames at `interval` along the path, all pointing at `angle`.
+ MultipleFlamesOneDirection,
+}
+
+/// Overall motion of the flame lines.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum FlameStyle {
+ #[default]
+ Normal,
+ Violent,
+ Flat,
+}
+
+/// How the flame lines converge towards the tip.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum FlameShape {
+ #[default]
+ Parallel,
+ ToCenter,
+ Spread,
+ Oval,
+ Pointed,
+}
+
+/// Flame options (Photoshop's Flame dialog, Basic + Advanced).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct FlameSpec {
+ pub flame_type: FlameType,
+ /// Flame length in px (1–1000).
+ pub length: f32,
+ pub randomize_length: bool,
+ /// Flame width in px (1–1000).
+ pub width: f32,
+ /// Direction for `multipleFlamesOneDirection` (degrees, 0 = up, clockwise).
+ pub angle: f32,
+ /// Spacing between flames along the path in px (1–1000).
+ pub interval: f32,
+ /// Spread the flames evenly so a closed path loops seamlessly.
+ pub adjust_interval_for_loops: bool,
+ /// `Some` = custom flame colour; `None` = natural flame colours.
+ pub color: Option<[f32; 4]>,
+ /// 0–100.
+ pub turbulent: f32,
+ /// 0–100.
+ pub jag: f32,
+ /// 0–100 %.
+ pub opacity: f32,
+ /// Flame lines (complexity) 1–100.
+ pub flame_lines: f32,
+ /// 0–100: how unevenly the lines start along the flame.
+ pub flame_bottom_alignment: f32,
+ pub flame_style: FlameStyle,
+ pub flame_shape: FlameShape,
+ pub randomize_shapes: bool,
+ /// 0–100: arrangement seed.
+ pub seed: u32,
+ /// 0 (draft) … 4 (fine): segments per flame line.
+ pub quality: u32,
+}
+
+impl Default for FlameSpec {
+ fn default() -> Self {
+ FlameSpec {
+ flame_type: FlameType::OneFlameAlongPath,
+ length: 150.0,
+ randomize_length: false,
+ width: 40.0,
+ angle: 0.0,
+ interval: 60.0,
+ adjust_interval_for_loops: true,
+ color: None,
+ turbulent: 25.0,
+ jag: 25.0,
+ opacity: 75.0,
+ flame_lines: 20.0,
+ flame_bottom_alignment: 20.0,
+ flame_style: FlameStyle::Normal,
+ flame_shape: FlameShape::Parallel,
+ randomize_shapes: false,
+ seed: 0,
+ quality: 2,
+ }
+ }
+}
+
+/// Natural flame colour at position `t` along the flame (0 = base, 1 = tip).
+fn flame_colour(t: f32, custom: Option<[f32; 4]>) -> [f32; 4] {
+ let a = (1.0 - t).powf(0.7) * 0.9 + 0.1 * (1.0 - t);
+ match custom {
+ Some(c) => {
+ // Hot near-white core → the colour → a darker rim.
+ let core = [c[0] * 0.4 + 0.6, c[1] * 0.4 + 0.6, c[2] * 0.4 + 0.6];
+ let rim = [c[0] * 0.6, c[1] * 0.6, c[2] * 0.6];
+ let k = t.clamp(0.0, 1.0);
+ let rgb = if k < 0.35 {
+ let u = k / 0.35;
+ [core[0] + (c[0] - core[0]) * u, core[1] + (c[1] - core[1]) * u, core[2] + (c[2] - core[2]) * u]
+ } else {
+ let u = (k - 0.35) / 0.65;
+ [c[0] + (rim[0] - c[0]) * u, c[1] + (rim[1] - c[1]) * u, c[2] + (rim[2] - c[2]) * u]
+ };
+ [rgb[0], rgb[1], rgb[2], a * c[3]]
+ }
+ None => {
+ const STOPS: [(f32, [f32; 3]); 5] = [(0.0, [1.0, 0.98, 0.85]), (0.2, [1.0, 0.86, 0.35]), (0.45, [1.0, 0.55, 0.08]), (0.75, [0.9, 0.25, 0.02]), (1.0, [0.6, 0.08, 0.0])];
+ let k = t.clamp(0.0, 1.0);
+ let mut rgb = STOPS[4].1;
+ for w in STOPS.windows(2) {
+ if k <= w[1].0 {
+ let u = (k - w[0].0) / (w[1].0 - w[0].0);
+ rgb = [w[0].1[0] + (w[1].1[0] - w[0].1[0]) * u, w[0].1[1] + (w[1].1[1] - w[0].1[1]) * u, w[0].1[2] + (w[1].1[2] - w[0].1[2]) * u];
+ break;
+ }
+ }
+ [rgb[0], rgb[1], rgb[2], a]
+ }
+ }
+}
+
+/// One flame: its spine (base → tip), how wide it is, and its random stream.
+fn draw_flame(out: &mut Vec<Prim>, spine: &Spine, width: f32, spec: &FlameSpec, rng: &mut Rng) {
+ let len = spine.len();
+ if len < 1.0 {
+ return;
+ }
+ let lines = (spec.flame_lines.clamp(1.0, 100.0) * 0.6 + 3.0).round() as usize;
+ let segs = [6usize, 10, 16, 24, 36][spec.quality.min(4) as usize].max((len / 12.0) as usize).min(160);
+ let (mut turb, mut jag) = (spec.turbulent.clamp(0.0, 100.0) / 100.0, spec.jag.clamp(0.0, 100.0) / 100.0);
+ match spec.flame_style {
+ FlameStyle::Violent => {
+ turb = (turb * 1.8 + 0.2).min(2.0);
+ jag = (jag * 1.8 + 0.15).min(2.0);
+ }
+ FlameStyle::Flat => {
+ turb *= 0.35;
+ jag *= 0.35;
+ }
+ FlameStyle::Normal => {}
+ }
+ let shape = if spec.randomize_shapes {
+ [FlameShape::Parallel, FlameShape::ToCenter, FlameShape::Spread, FlameShape::Oval, FlameShape::Pointed][(rng.next_u64() % 5) as usize]
+ } else {
+ spec.flame_shape
+ };
+ let opacity = spec.opacity.clamp(0.0, 100.0) / 100.0;
+ let half = width.max(1.0) / 2.0;
+ let seed = rng.next_u64();
+ // A soft additive glow behind the lines.
+ let ((mx, my), (tx, ty)) = spine.at(len * 0.4);
+ let glow_c = { let c = flame_colour(0.35, spec.color); [c[0], c[1], c[2], 0.35 * opacity] };
+ out.push(Prim::ellipse((mx, my), len * 0.55, half * 1.4 + 2.0, ty.atan2(tx), glow_c, [glow_c[0], glow_c[1] * 0.5, glow_c[2] * 0.3, 0.0]).with_soft((half * 0.8).max(2.0)).additive());
+ let line_r = (half / lines as f32 * 1.6).clamp(0.6, 6.0);
+ for li in 0..lines {
+ let lane = if lines == 1 { 0.0 } else { li as f32 / (lines - 1) as f32 * 2.0 - 1.0 };
+ let lseed = seed ^ (li as u64).wrapping_mul(0x51_7CC1_B727_220A);
+ let start = (spec.flame_bottom_alignment.clamp(0.0, 100.0) / 100.0) * rng.f() * 0.4;
+ // Outer lines are shorter, giving the flame its tongue shape.
+ let reach = (1.0 - 0.45 * lane.abs().powi(2)) * rng.range(0.75, 1.0);
+ let end = (start + reach * (1.0 - start)).clamp(start + 0.05, 1.0);
+ let mut prev: Option<((f32, f32), f32)> = None;
+ for k in 0..=segs {
+ let u = start + (end - start) * k as f32 / segs as f32;
+ let s = u * len;
+ let ((px, py), (dx, dy)) = spine.at(s);
+ let (nx, ny) = (-dy, dx);
+ let spread = match shape {
+ FlameShape::Parallel => 1.0,
+ FlameShape::ToCenter => 1.0 - u,
+ FlameShape::Spread => 1.0 + u,
+ FlameShape::Oval => (std::f32::consts::PI * (0.15 + 0.85 * u)).sin() * 1.3,
+ FlameShape::Pointed => (1.0 - u).powi(2),
+ };
+ let wob = turb * half * 1.2 * fbm1(s / (len * 0.25 + 8.0) + li as f32 * 0.37, lseed) * u.sqrt() + jag * half * 0.35 * noise1(s / 6.0, lseed ^ 0x77) * u;
+ let off = lane * half * spread + wob;
+ let p = (px + nx * off, py + ny * off);
+ let r = line_r * (1.0 - u * 0.8);
+ if let Some((q, rq)) = prev {
+ let c0 = flame_colour((u - (end - start) / segs as f32).max(0.0), spec.color);
+ let c1 = flame_colour(u, spec.color);
+ let fade = |c: [f32; 4]| [c[0], c[1], c[2], c[3] * opacity * 0.9];
+ out.push(Prim::capsule(q, p, rq, r, fade(c0), fade(c1)).with_soft(1.0 + line_r * 0.6).additive());
+ }
+ prev = Some((p, r));
+ }
+ }
+}
+
+/// Builds flame primitives. `paths` are flattened polylines in document pixels.
+pub fn flame(spec: &FlameSpec, paths: &[Vec<(f32, f32)>]) -> Vec<Prim> {
+ let mut out = Vec::new();
+ let mut rng = Rng::new(spec.seed, 0xF1A3);
+ let length = spec.length.clamp(1.0, 1000.0);
+ let width = spec.width.clamp(1.0, 1000.0);
+ let interval = spec.interval.clamp(1.0, 1000.0);
+ let pick_len = |rng: &mut Rng, var: f32| if spec.randomize_length || var > 0.0 { length * rng.range(1.0 - var.max(0.4), 1.0 + var.max(0.4) * 0.5) } else { length };
+ for path in paths.iter().filter(|p| !p.is_empty()) {
+ let spine = Spine::new(path.clone());
+ let total = spine.len();
+ match spec.flame_type {
+ FlameType::OneFlameAlongPath if path.len() >= 2 && total >= 1.0 => draw_flame(&mut out, &spine, width, spec, &mut rng),
+ FlameType::CandleLight | FlameType::OneFlameAlongPath => {
+ // A candle: a short teardrop rising straight up from the start.
+ let base = path[0];
+ let h = length.min(400.0);
+ let candle = Spine::new(vec![base, (base.0, base.1 - h)]);
+ let c = FlameSpec { flame_shape: FlameShape::Oval, turbulent: spec.turbulent * 0.3, jag: spec.jag * 0.2, ..spec.clone() };
+ draw_flame(&mut out, &candle, (width * 0.6).max(4.0), &c, &mut rng);
+ let core = flame_colour(0.05, spec.color);
+ out.push(Prim::ellipse((base.0, base.1 - h * 0.28), (width * 0.12).max(1.5), h * 0.22, 0.0, [core[0], core[1], core[2], 0.9 * spec.opacity.clamp(0.0, 100.0) / 100.0], [core[0], core[1], core[2], 0.0]).with_soft(2.0).additive());
+ }
+ _ => {
+ let closed = path.len() > 2 && {
+ let (a, b) = (path[0], path[path.len() - 1]);
+ (a.0 - b.0).abs() < 1.0 && (a.1 - b.1).abs() < 1.0
+ };
+ let count = if spec.adjust_interval_for_loops && closed { (total / interval).round().max(1.0) as usize } else { (total / interval).floor() as usize + 1 };
+ let step = if spec.adjust_interval_for_loops && closed { total / count as f32 } else { interval };
+ for k in 0..count {
+ let s = k as f32 * step;
+ let ((x, y), (dx, dy)) = spine.at(s);
+ let dir = match spec.flame_type {
+ FlameType::MultipleFlamesPathDirections => (dx, dy),
+ FlameType::MultipleFlamesOneDirection => {
+ let a = spec.angle.to_radians();
+ (a.sin(), -a.cos())
+ }
+ // Left of the path direction (up for a left-to-right path).
+ _ => (dy, -dx),
+ };
+ let var = if spec.flame_type == FlameType::MultipleFlamesVariousLength { 0.7 } else { 0.0 };
+ let l = pick_len(&mut rng, var);
+ let fl = Spine::new(vec![(x, y), (x + dir.0 * l, y + dir.1 * l)]);
+ draw_flame(&mut out, &fl, width, spec, &mut rng);
+ }
+ }
+ }
+ }
+ out
+}
+
+/// The path Flame uses when the document has none: a gentle arc across the lower part of the canvas.
+pub fn default_flame_path(canvas: Rect) -> Vec<(f32, f32)> {
+ let (w, h) = (canvas.width() as f32, canvas.height() as f32);
+ (0..=32)
+ .map(|k| {
+ let t = k as f32 / 32.0;
+ (canvas.x0 as f32 + w * (0.15 + 0.7 * t), canvas.y0 as f32 + h * (0.8 - 0.08 * (std::f32::consts::PI * t).sin()))
+ })
+ .collect()
+}
+
+// ---------------------------------------------------------------------------
+// Tree
+// ---------------------------------------------------------------------------
+
+/// Leaf form of a tree type.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Leaf {
+ None,
+ Round,
+ Oval,
+ Needle,
+ Heart,
+ Blossom,
+ Long,
+ Frond,
+}
+
+/// Branch architecture of a tree type.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Habit {
+ /// Recursive branching (deciduous trees).
+ Branching,
+ /// A dominant stem with whorls of side branches (conifers).
+ Conifer,
+ /// A tall trunk crowned with fronds.
+ Palm,
+ /// Several straight jointed stalks.
+ Bamboo,
+}
+
+/// One base tree type.
+struct TreeKind {
+ name: &'static str,
+ habit: Habit,
+ levels: u32,
+ children: u32,
+ /// Branch spread (degrees from the parent).
+ spread: f32,
+ /// Child / parent length ratio.
+ ratio: f32,
+ /// Trunk share of the total height.
+ trunk: f32,
+ /// Downward bend per unit length at deep levels (willow > 0, upright < 0).
+ droop: f32,
+ /// Random bend.
+ wiggle: f32,
+ /// Trunk radius as a fraction of the height.
+ thick: f32,
+ leaf: Leaf,
+ leaf_col: [f32; 3],
+ bark: [f32; 3],
+ /// Fruit or blossom accent dots.
+ accent: Option<[f32; 3]>,
+}
+
+#[allow(clippy::too_many_arguments)]
+const fn tk(name: &'static str, habit: Habit, levels: u32, children: u32, spread: f32, ratio: f32, trunk: f32, droop: f32, wiggle: f32, thick: f32, leaf: Leaf, leaf_col: [f32; 3], bark: [f32; 3], accent: Option<[f32; 3]>) -> TreeKind {
+ TreeKind { name, habit, levels, children, spread, ratio, trunk, droop, wiggle, thick, leaf, leaf_col, bark, accent }
+}
+
+const BROWN: [f32; 3] = [0.36, 0.25, 0.16];
+const GREY_BARK: [f32; 3] = [0.45, 0.42, 0.38];
+const GREEN: [f32; 3] = [0.24, 0.52, 0.16];
+const DARK_GREEN: [f32; 3] = [0.12, 0.36, 0.14];
+
+/// The base tree types (index = `baseTreeType` − 1).
+const TREES: [TreeKind; 34] = [
+ tk("Oak", Habit::Branching, 5, 3, 38.0, 0.72, 0.35, 0.05, 0.35, 0.035, Leaf::Round, GREEN, BROWN, None),
+ tk("Maple", Habit::Branching, 5, 3, 34.0, 0.74, 0.32, 0.0, 0.25, 0.03, Leaf::Heart, [0.3, 0.55, 0.15], BROWN, None),
+ tk("Pine", Habit::Conifer, 3, 2, 70.0, 0.5, 0.15, 0.25, 0.1, 0.025, Leaf::Needle, DARK_GREEN, BROWN, None),
+ tk("Palm", Habit::Palm, 1, 9, 0.0, 0.0, 0.85, 0.0, 0.15, 0.022, Leaf::Frond, [0.25, 0.5, 0.18], [0.55, 0.45, 0.32], None),
+ tk("Birch", Habit::Branching, 5, 2, 28.0, 0.75, 0.4, 0.1, 0.3, 0.02, Leaf::Oval, [0.45, 0.65, 0.2], [0.88, 0.86, 0.82], None),
+ tk("Weeping Willow", Habit::Branching, 5, 3, 40.0, 0.78, 0.3, 0.9, 0.2, 0.035, Leaf::Long, [0.45, 0.62, 0.22], GREY_BARK, None),
+ tk("Cherry Blossom", Habit::Branching, 5, 3, 42.0, 0.7, 0.3, 0.0, 0.45, 0.03, Leaf::Blossom, [0.98, 0.75, 0.82], [0.3, 0.2, 0.17], None),
+ tk("Bamboo", Habit::Bamboo, 1, 5, 6.0, 0.0, 1.0, 0.0, 0.05, 0.012, Leaf::Long, [0.35, 0.6, 0.2], [0.55, 0.65, 0.3], None),
+ tk("Cypress", Habit::Branching, 5, 3, 10.0, 0.8, 0.1, -0.1, 0.1, 0.02, Leaf::Needle, DARK_GREEN, BROWN, None),
+ tk("Baobab", Habit::Branching, 3, 4, 50.0, 0.55, 0.65, 0.0, 0.3, 0.09, Leaf::Round, [0.35, 0.55, 0.2], [0.55, 0.47, 0.4], None),
+ tk("Ginkgo", Habit::Branching, 4, 3, 30.0, 0.72, 0.35, 0.0, 0.2, 0.025, Leaf::Heart, [0.75, 0.75, 0.2], GREY_BARK, None),
+ tk("Spruce", Habit::Conifer, 3, 2, 80.0, 0.45, 0.1, 0.45, 0.08, 0.025, Leaf::Needle, [0.1, 0.3, 0.2], BROWN, None),
+ tk("Bare Winter Tree", Habit::Branching, 6, 2, 34.0, 0.74, 0.3, 0.05, 0.35, 0.03, Leaf::None, GREEN, [0.3, 0.25, 0.22], None),
+ tk("Apple", Habit::Branching, 5, 3, 46.0, 0.68, 0.3, 0.1, 0.4, 0.03, Leaf::Round, GREEN, BROWN, Some([0.85, 0.1, 0.1])),
+ tk("Acacia", Habit::Branching, 4, 3, 55.0, 0.75, 0.45, -0.25, 0.25, 0.03, Leaf::Round, [0.35, 0.5, 0.18], BROWN, None),
+ tk("Poplar", Habit::Branching, 5, 3, 12.0, 0.8, 0.15, -0.15, 0.1, 0.025, Leaf::Oval, [0.3, 0.55, 0.15], GREY_BARK, None),
+ tk("Elm", Habit::Branching, 5, 2, 24.0, 0.8, 0.3, 0.15, 0.25, 0.032, Leaf::Oval, GREEN, BROWN, None),
+ tk("Magnolia", Habit::Branching, 4, 3, 40.0, 0.7, 0.3, 0.0, 0.3, 0.03, Leaf::Blossom, [0.98, 0.9, 0.92], [0.35, 0.28, 0.25], Some([0.85, 0.5, 0.65])),
+ tk("Banana", Habit::Palm, 1, 7, 0.0, 0.0, 0.6, 0.0, 0.05, 0.04, Leaf::Frond, [0.45, 0.7, 0.2], [0.5, 0.6, 0.3], None),
+ tk("Bonsai", Habit::Branching, 4, 3, 60.0, 0.6, 0.45, 0.2, 0.7, 0.05, Leaf::Round, DARK_GREEN, [0.4, 0.3, 0.22], None),
+ tk("Jacaranda", Habit::Branching, 5, 3, 44.0, 0.72, 0.3, 0.0, 0.35, 0.03, Leaf::Blossom, [0.6, 0.45, 0.85], BROWN, None),
+ tk("Autumn Maple", Habit::Branching, 5, 3, 34.0, 0.74, 0.32, 0.0, 0.25, 0.03, Leaf::Heart, [0.85, 0.3, 0.1], BROWN, None),
+ tk("Golden Autumn", Habit::Branching, 5, 3, 36.0, 0.72, 0.33, 0.05, 0.3, 0.03, Leaf::Round, [0.9, 0.7, 0.15], BROWN, None),
+ tk("Olive", Habit::Branching, 4, 3, 48.0, 0.68, 0.35, 0.1, 0.6, 0.04, Leaf::Long, [0.5, 0.58, 0.42], GREY_BARK, Some([0.25, 0.28, 0.12])),
+ tk("Fir", Habit::Conifer, 3, 2, 75.0, 0.5, 0.12, 0.15, 0.05, 0.025, Leaf::Needle, [0.12, 0.38, 0.22], BROWN, None),
+ tk("Cedar", Habit::Conifer, 3, 3, 88.0, 0.6, 0.2, 0.0, 0.15, 0.03, Leaf::Needle, [0.2, 0.4, 0.25], BROWN, None),
+ tk("Lemon", Habit::Branching, 4, 3, 45.0, 0.68, 0.3, 0.05, 0.35, 0.03, Leaf::Oval, DARK_GREEN, BROWN, Some([0.98, 0.88, 0.15])),
+ tk("Wisteria", Habit::Branching, 5, 3, 45.0, 0.72, 0.3, 0.7, 0.3, 0.03, Leaf::Blossom, [0.7, 0.55, 0.9], [0.35, 0.3, 0.27], None),
+ tk("Young Sapling", Habit::Branching, 3, 2, 30.0, 0.7, 0.45, 0.0, 0.2, 0.015, Leaf::Oval, [0.4, 0.7, 0.2], [0.45, 0.35, 0.22], None),
+ tk("Dead Tree", Habit::Branching, 5, 2, 45.0, 0.68, 0.4, 0.1, 0.8, 0.035, Leaf::None, GREEN, [0.32, 0.29, 0.26], None),
+ tk("Coconut Palm", Habit::Palm, 1, 11, 0.0, 0.0, 0.88, 0.0, 0.35, 0.018, Leaf::Frond, [0.3, 0.55, 0.15], [0.6, 0.5, 0.36], Some([0.4, 0.3, 0.15])),
+ tk("Shrub", Habit::Branching, 4, 4, 55.0, 0.7, 0.05, 0.0, 0.35, 0.02, Leaf::Round, GREEN, BROWN, None),
+ tk("Plum Blossom", Habit::Branching, 5, 2, 48.0, 0.7, 0.3, 0.1, 0.6, 0.03, Leaf::Blossom, [0.95, 0.6, 0.7], [0.25, 0.18, 0.15], None),
+ tk("Cloud Pine", Habit::Branching, 4, 3, 70.0, 0.65, 0.35, 0.2, 0.5, 0.035, Leaf::Needle, [0.15, 0.4, 0.2], [0.35, 0.27, 0.2], None),
+];
+
+/// Names of the base tree types (1-based `baseTreeType` = index + 1).
+pub fn tree_type_names() -> Vec<&'static str> {
+ TREES.iter().map(|t| t.name).collect()
+}
+
+/// Tree options (Photoshop's Tree dialog).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct TreeSpec {
+ /// 1–34.
+ pub base_tree_type: u32,
+ /// 1 (light from the left) … 3 (above) … 5 (right).
+ pub light_direction: u32,
+ /// 0–100.
+ pub leaves_amount: f32,
+ /// 0–200 %.
+ pub leaves_size: f32,
+ /// 50–300 %: how high the branching starts.
+ pub branches_height: f32,
+ /// 50–200 %.
+ pub branches_thickness: f32,
+ /// Use the type's leaf colour; otherwise `leaves_color`.
+ pub default_leaves: bool,
+ pub leaves_color: [f32; 4],
+ /// Use `branches_color` instead of the type's bark.
+ pub custom_branch_color: bool,
+ pub branches_color: [f32; 4],
+ /// Flat shading (no light variation).
+ pub flat_shading: bool,
+ pub seed: u32,
+ /// Base position as a fraction of the canvas.
+ pub x: f32,
+ pub y: f32,
+ /// Height as a fraction of the canvas height.
+ pub size: f32,
+}
+
+impl Default for TreeSpec {
+ fn default() -> Self {
+ TreeSpec {
+ base_tree_type: 1,
+ light_direction: 3,
+ leaves_amount: 50.0,
+ leaves_size: 100.0,
+ branches_height: 100.0,
+ branches_thickness: 100.0,
+ default_leaves: true,
+ leaves_color: [0.24, 0.52, 0.16, 1.0],
+ custom_branch_color: false,
+ branches_color: [0.36, 0.25, 0.16, 1.0],
+ flat_shading: false,
+ seed: 0,
+ x: 0.5,
+ y: 0.95,
+ size: 0.8,
+ }
+ }
+}
+
+struct TreeCtx<'a> {
+ kind: &'a TreeKind,
+ spec: &'a TreeSpec,
+ rng: Rng,
+ branches: Vec<Prim>,
+ leaves: Vec<(f32, Prim)>,
+ bark: [f32; 3],
+ leaf: [f32; 3],
+ light: (f32, f32),
+ centre: (f32, f32),
+ leaf_px: f32,
+}
+
+fn shade(c: [f32; 3], k: f32) -> [f32; 4] {
+ [(c[0] * k).clamp(0.0, 1.0), (c[1] * k).clamp(0.0, 1.0), (c[2] * k).clamp(0.0, 1.0), 1.0]
+}
+
+impl TreeCtx<'_> {
+ /// Brightness of a leaf at `p` (lit side of the crown brighter).
+ fn light_at(&mut self, p: (f32, f32)) -> f32 {
+ if self.spec.flat_shading {
+ return 1.0;
+ }
+ let (dx, dy) = (p.0 - self.centre.0, p.1 - self.centre.1);
+ let l = (dx * dx + dy * dy).sqrt().max(1.0);
+ 0.78 + 0.32 * ((dx * self.light.0 + dy * self.light.1) / l) + 0.12 * self.rng.sym()
+ }
+
+ fn add_leaf(&mut self, p: (f32, f32), dir: f32) {
+ let r = &mut self.rng;
+ let s = self.leaf_px * r.range(0.7, 1.2);
+ let ang = dir + r.sym() * 1.2;
+ let k = self.light_at(p);
+ let col = self.leaf;
+ let prim = match self.kind.leaf {
+ Leaf::None => return,
+ Leaf::Round => Prim::ellipse(p, s, s * 0.85, ang, shade(col, k * 1.1), shade(col, k * 0.8)),
+ Leaf::Oval => Prim::ellipse(p, s * 1.2, s * 0.55, ang, shade(col, k * 1.1), shade(col, k * 0.8)),
+ Leaf::Long => Prim::ellipse(p, s * 1.6, s * 0.28, ang, shade(col, k * 1.1), shade(col, k * 0.8)),
+ Leaf::Heart => Prim::ellipse(p, s * 0.9, s * 1.1, ang, shade(col, k * 1.1), shade(col, k * 0.75)),
+ Leaf::Needle => {
+ let (sa, ca) = ang.sin_cos();
+ let q = (p.0 + ca * s * 1.4, p.1 + sa * s * 1.4);
+ Prim::capsule(p, q, (s * 0.12).max(0.5), (s * 0.06).max(0.3), shade(col, k * 0.9), shade(col, k * 1.1))
+ }
+ Leaf::Blossom => Prim::ellipse(p, s * 0.75, s * 0.75, 0.0, shade(col, k * 1.08), shade(col, k * 0.85)),
+ Leaf::Frond => Prim::ellipse(p, s * 1.6, s * 0.3, ang, shade(col, k), shade(col, k * 0.8)),
+ };
+ let order = k + self.rng.f() * 0.05;
+ self.leaves.push((order, prim));
+ if let Some(acc) = self.kind.accent
+ && self.rng.f() < 0.12
+ {
+ let q = (p.0 + self.rng.sym() * s, p.1 + self.rng.sym() * s);
+ let r = (s * 0.45).max(1.0);
+ self.leaves.push((k + 1.0, Prim::ellipse(q, r, r, 0.0, shade(acc, k * 1.15), shade(acc, k * 0.75))));
+ }
+ }
+
+ /// A curved branch from `p` heading `ang` (radians, 0 = right, y down).
+ /// Returns its end point and end heading.
+ fn limb(&mut self, p: (f32, f32), ang: f32, len: f32, r0: f32, r1: f32, depth01: f32) -> ((f32, f32), f32) {
+ let segs = ((len / 6.0) as usize).clamp(2, 10);
+ let (mut q, mut a) = (p, ang);
+ let droop = self.kind.droop * depth01;
+ let col0 = shade(self.bark, 0.9 + 0.2 * depth01);
+ for k in 0..segs {
+ let t0 = k as f32 / segs as f32;
+ let t1 = (k + 1) as f32 / segs as f32;
+ a += self.kind.wiggle * self.rng.sym() * 0.25;
+ // Gravity pulls the heading towards straight down (π/2).
+ let down = std::f32::consts::FRAC_PI_2;
+ let diff = (down - a).sin().atan2((down - a).cos());
+ a += diff * droop * 0.12;
+ let step = len / segs as f32;
+ let nq = (q.0 + a.cos() * step, q.1 + a.sin() * step);
+ let (ra, rb) = (r0 + (r1 - r0) * t0, r0 + (r1 - r0) * t1);
+ self.branches.push(Prim::capsule(q, nq, ra, rb, col0, col0));
+ if depth01 > 0.99 && self.kind.leaf != Leaf::None && k > 0 && self.rng.f() < self.spec.leaves_amount.clamp(0.0, 100.0) / 100.0 * 0.9 {
+ self.add_leaf(nq, a);
+ }
+ q = nq;
+ }
+ (q, a)
+ }
+
+ fn branch(&mut self, p: (f32, f32), ang: f32, len: f32, r: f32, level: u32) {
+ let levels = self.kind.levels;
+ let depth01 = level as f32 / levels.max(1) as f32;
+ let r_end = r * 0.62;
+ let (end, a) = self.limb(p, ang, len, r, r_end, depth01);
+ if level >= levels {
+ let amount = self.spec.leaves_amount.clamp(0.0, 100.0) / 100.0;
+ if self.kind.leaf != Leaf::None {
+ let n = (amount * 9.0).round() as usize;
+ for _ in 0..n {
+ let d = len * 0.5 * self.rng.f();
+ let th = self.rng.f() * std::f32::consts::TAU;
+ self.add_leaf((end.0 + th.cos() * d, end.1 + th.sin() * d), a);
+ }
+ }
+ return;
+ }
+ let spread = self.kind.spread.to_radians();
+ let n = self.kind.children;
+ for c in 0..n {
+ let side = if n == 1 { 0.0 } else { c as f32 / (n - 1) as f32 * 2.0 - 1.0 };
+ let ca = a + side * spread + self.rng.sym() * spread * 0.35;
+ let cl = len * self.kind.ratio * self.rng.range(0.8, 1.1);
+ let cr = r_end * self.rng.range(0.75, 0.95);
+ self.branch(end, ca, cl, cr, level + 1);
+ }
+ }
+}
+
+/// Builds tree primitives inside `canvas`.
+pub fn tree(spec: &TreeSpec, canvas: Rect) -> Vec<Prim> {
+ let kind = &TREES[(spec.base_tree_type.clamp(1, TREES.len() as u32) - 1) as usize];
+ let h = canvas.height() as f32 * spec.size.clamp(0.05, 2.0);
+ let base = (canvas.x0 as f32 + canvas.width() as f32 * spec.x, canvas.y0 as f32 + canvas.height() as f32 * spec.y);
+ let la = match spec.light_direction.clamp(1, 5) {
+ 1 => 180.0f32,
+ 2 => 225.0,
+ 3 => 270.0,
+ 4 => 315.0,
+ _ => 0.0,
+ }
+ .to_radians();
+ let leaf = if spec.default_leaves { kind.leaf_col } else { [spec.leaves_color[0], spec.leaves_color[1], spec.leaves_color[2]] };
+ let bark = if spec.custom_branch_color { [spec.branches_color[0], spec.branches_color[1], spec.branches_color[2]] } else { kind.bark };
+ let thick = spec.branches_thickness.clamp(50.0, 200.0) / 100.0;
+ let bh = spec.branches_height.clamp(50.0, 300.0) / 100.0;
+ let mut t = TreeCtx {
+ kind,
+ spec,
+ rng: Rng::new(spec.seed, 0x7EE + spec.base_tree_type as u64),
+ branches: Vec::new(),
+ leaves: Vec::new(),
+ bark,
+ leaf,
+ light: (la.cos(), la.sin()),
+ centre: (base.0, base.1 - h * 0.65),
+ leaf_px: (h * 0.012 * spec.leaves_size.clamp(0.0, 200.0) / 100.0).max(0.6),
+ };
+ let up = -std::f32::consts::FRAC_PI_2;
+ let r0 = (h * kind.thick * thick).max(0.8);
+ match kind.habit {
+ Habit::Branching => {
+ let trunk = (h * kind.trunk * bh).min(h * 0.92);
+ let (top, a) = t.limb(base, up, trunk.max(1.0), r0, r0 * 0.75, 0.0);
+ // Crown length so the tree reaches about `h`.
+ let geo: f32 = (0..kind.levels).map(|k| kind.ratio.powi(k as i32)).sum();
+ let first = ((h - trunk).max(h * 0.08) / geo.max(0.5)) * 1.05;
+ let n = kind.children.max(2);
+ for c in 0..n {
+ let side = c as f32 / (n - 1) as f32 * 2.0 - 1.0;
+ let sp = kind.spread.to_radians() * 0.8;
+ let ca = a + side * sp + t.rng.sym() * 0.15;
+ let fl = first * t.rng.range(0.85, 1.05);
+ t.branch(top, ca, fl, r0 * 0.7, 1);
+ }
+ }
+ Habit::Conifer => {
+ let (top, _) = t.limb(base, up, h, r0, r0 * 0.1, 0.0);
+ let start = (h * kind.trunk * bh).min(h * 0.8);
+ let whorls = (14.0 * (h / 300.0).sqrt().clamp(0.6, 2.5)) as usize;
+ let spread = kind.spread.to_radians();
+ for k in 0..whorls {
+ let f = k as f32 / whorls as f32;
+ let y = base.1 - start - (h - start) * f;
+ let x = base.0 + (top.0 - base.0) * ((base.1 - y) / h);
+ let span = (h - start) * 0.42 * (1.0 - f).powf(0.9) + h * 0.03;
+ for side in [-1.0f32, 1.0] {
+ let ang = up + side * spread + t.rng.sym() * 0.1;
+ t.branch((x, y), ang, span, (r0 * 0.35 * (1.0 - f)).max(0.6), kind.levels);
+ if kind.levels >= 2 {
+ let (s2, c2) = (ang + side * 0.5).sin_cos();
+ let mid = (x + c2 * span * 0.5, y + s2 * span * 0.5);
+ t.branch(mid, ang + side * 0.6, span * 0.4, (r0 * 0.15).max(0.5), kind.levels);
+ }
+ }
+ }
+ }
+ Habit::Palm => {
+ let trunk = (h * kind.trunk * bh.min(1.15)).max(1.0);
+ let lean = t.rng.sym() * kind.wiggle;
+ let segs = 12;
+ let mut p = base;
+ for k in 0..segs {
+ let f = k as f32 / segs as f32;
+ let a = up + lean * f;
+ let q = (p.0 + a.cos() * trunk / segs as f32, p.1 + a.sin() * trunk / segs as f32);
+ let r = r0 * (1.0 - 0.35 * f);
+ let ring = shade(bark, if k % 2 == 0 { 1.0 } else { 0.85 });
+ t.branches.push(Prim::capsule(p, q, r, r * 0.97, ring, ring));
+ p = q;
+ }
+ let fronds = kind.children;
+ let flen = h * 0.38 * (spec.leaves_size.clamp(10.0, 200.0) / 100.0).sqrt();
+ for k in 0..fronds {
+ let a = up + (k as f32 / fronds as f32 - 0.5) * std::f32::consts::PI * 1.7 + t.rng.sym() * 0.2;
+ let mut q = p;
+ let mut ang = a;
+ let segs = 10;
+ let leaflets = (spec.leaves_amount.clamp(0.0, 100.0) / 100.0 * 3.0).round() as usize;
+ for s in 0..segs {
+ // Fronds arch over and droop towards the ground.
+ let d = std::f32::consts::FRAC_PI_2 - ang;
+ ang += 0.06 * d.sin().atan2(d.cos());
+ let nq = (q.0 + ang.cos() * flen / segs as f32, q.1 + ang.sin() * flen / segs as f32);
+ let k2 = t.light_at(nq);
+ t.leaves.push((k2 - 0.1, Prim::capsule(q, nq, (r0 * 0.15).max(0.6), (r0 * 0.1).max(0.4), shade(t.leaf, k2 * 0.8), shade(t.leaf, k2 * 0.8))));
+ for j in 0..leaflets {
+ let along = j as f32 / leaflets as f32;
+ let at = (q.0 + (nq.0 - q.0) * along, q.1 + (nq.1 - q.1) * along);
+ for side in [-1.0f32, 1.0] {
+ let la = ang + side * 1.1;
+ let ll = flen * 0.22 * (1.0 - s as f32 / segs as f32 * 0.7);
+ let tip = (at.0 + la.cos() * ll, at.1 + la.sin() * ll + ll * 0.25);
+ t.leaves.push((k2, Prim::capsule(at, tip, (ll * 0.08).max(0.5), 0.3, shade(t.leaf, k2), shade(t.leaf, k2 * 0.9))));
+ }
+ }
+ q = nq;
+ }
+ }
+ if let Some(acc) = kind.accent {
+ for _ in 0..4 {
+ let c = (p.0 + t.rng.sym() * r0 * 2.0, p.1 + t.rng.f() * r0 * 2.0);
+ t.leaves.push((2.0, Prim::disc(c, r0 * 1.1, shade(acc, 1.0))));
+ }
+ }
+ }
+ Habit::Bamboo => {
+ let stalks = kind.children;
+ for k in 0..stalks {
+ let x = base.0 + (k as f32 - (stalks - 1) as f32 / 2.0) * r0 * 5.0 + t.rng.sym() * r0;
+ let hh = h * t.rng.range(0.7, 1.0);
+ let a = up + t.rng.sym() * kind.spread.to_radians() * 0.5;
+ let joints = 8;
+ let mut p = (x, base.1);
+ for j in 0..joints {
+ let q = (p.0 + a.cos() * hh / joints as f32, p.1 + a.sin() * hh / joints as f32);
+ t.branches.push(Prim::capsule(p, q, r0, r0, shade(bark, 1.0), shade(bark, 0.85)));
+ t.branches.push(Prim::capsule((q.0 - r0 * 1.1, q.1), (q.0 + r0 * 1.1, q.1), r0 * 0.25, r0 * 0.25, shade(bark, 0.7), shade(bark, 0.7)));
+ if j >= joints / 3 {
+ let leaves = (spec.leaves_amount.clamp(0.0, 100.0) / 100.0 * 4.0).round() as usize;
+ for _ in 0..leaves {
+ let side = if t.rng.f() < 0.5 { -1.0 } else { 1.0 };
+ let la = a + side * t.rng.range(0.6, 1.4);
+ let ll = t.leaf_px * 2.2;
+ t.add_leaf((q.0 + la.cos() * ll, q.1 + la.sin() * ll), la);
+ }
+ }
+ p = q;
+ }
+ }
+ }
+ }
+ // Back leaves first: darker ones underneath, lit ones on top.
+ t.leaves.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
+ let mut out = t.branches;
+ out.extend(t.leaves.into_iter().map(|(_, p)| p));
+ out
+}
+
+// ---------------------------------------------------------------------------
+// Picture Frame
+// ---------------------------------------------------------------------------
+
+/// Picture frame designs (index = `frame` − 1).
+pub const FRAME_STYLES: [&str; 16] = [
+ "vineWithFlowers",
+ "vineWithLeaves",
+ "ivy",
+ "roses",
+ "daisies",
+ "berries",
+ "bamboo",
+ "waves",
+ "zigzag",
+ "dots",
+ "rope",
+ "scallops",
+ "doubleLine",
+ "snowflakes",
+ "stars",
+ "hearts",
+];
+
+/// Picture Frame options.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct FrameSpec {
+ /// 1-based design (see [`FRAME_STYLES`]).
+ pub frame: u32,
+ /// Distance of the frame from the canvas edge, % of the shorter side (0–30).
+ pub margin: f32,
+ /// Ornament size 1–100.
+ pub size: f32,
+ /// Ornament spacing / density 1–100 (higher = denser).
+ pub arrangement: f32,
+ /// Number of parallel lines for line designs (1–5).
+ pub lines: u32,
+ /// Line / vine thickness 1–100.
+ pub thickness: f32,
+ /// 0–100 %: fade the ornaments towards the inside.
+ pub fade: f32,
+ pub vine_color: [f32; 4],
+ pub flower_color: [f32; 4],
+ pub leaf_color: [f32; 4],
+ pub seed: u32,
+}
+
+impl Default for FrameSpec {
+ fn default() -> Self {
+ FrameSpec {
+ frame: 1,
+ margin: 4.0,
+ size: 50.0,
+ arrangement: 50.0,
+ lines: 1,
+ thickness: 30.0,
+ fade: 0.0,
+ vine_color: [0.25, 0.4, 0.15, 1.0],
+ flower_color: [0.9, 0.3, 0.45, 1.0],
+ leaf_color: [0.3, 0.6, 0.2, 1.0],
+ seed: 0,
+ }
+ }
+}
+
+/// The frame rectangle walked by arc length (clockwise from the top-left).
+struct Border {
+ x0: f32,
+ y0: f32,
+ w: f32,
+ h: f32,
+}
+
+impl Border {
+ fn len(&self) -> f32 {
+ 2.0 * (self.w + self.h)
+ }
+ /// Point, unit tangent and inward normal at arc length `s`.
+ fn at(&self, s: f32) -> ((f32, f32), (f32, f32), (f32, f32)) {
+ let s = s.rem_euclid(self.len());
+ let (w, h) = (self.w, self.h);
+ if s < w {
+ ((self.x0 + s, self.y0), (1.0, 0.0), (0.0, 1.0))
+ } else if s < w + h {
+ ((self.x0 + w, self.y0 + s - w), (0.0, 1.0), (-1.0, 0.0))
+ } else if s < 2.0 * w + h {
+ ((self.x0 + w - (s - w - h), self.y0 + h), (-1.0, 0.0), (0.0, -1.0))
+ } else {
+ ((self.x0, self.y0 + h - (s - 2.0 * w - h)), (0.0, -1.0), (1.0, 0.0))
+ }
+ }
+}
+
+fn flower(out: &mut Vec<Prim>, c: (f32, f32), r: f32, petals: usize, petal: [f32; 4], centre: [f32; 4], rot: f32) {
+ for k in 0..petals {
+ let a = rot + k as f32 / petals as f32 * std::f32::consts::TAU;
+ let p = (c.0 + a.cos() * r * 0.55, c.1 + a.sin() * r * 0.55);
+ out.push(Prim::ellipse(p, r * 0.5, r * 0.26, a, petal, shade([petal[0], petal[1], petal[2]], 0.8)));
+ }
+ out.push(Prim::ellipse(c, r * 0.28, r * 0.28, 0.0, centre, shade([centre[0], centre[1], centre[2]], 0.75)));
+}
+
+fn leaf(out: &mut Vec<Prim>, p: (f32, f32), ang: f32, len: f32, col: [f32; 4]) {
+ let c = (p.0 + ang.cos() * len * 0.5, p.1 + ang.sin() * len * 0.5);
+ out.push(Prim::ellipse(c, len * 0.5, len * 0.22, ang, shade([col[0], col[1], col[2]], 1.12), shade([col[0], col[1], col[2]], 0.8)));
+}
+
+fn star(out: &mut Vec<Prim>, c: (f32, f32), r: f32, points: usize, col: [f32; 4], rot: f32) {
+ for k in 0..points {
+ let a = rot + k as f32 / points as f32 * std::f32::consts::TAU;
+ out.push(Prim::capsule(c, (c.0 + a.cos() * r, c.1 + a.sin() * r), r * 0.28, 0.4, col, col));
+ }
+}
+
+/// Builds picture-frame primitives inside `canvas`.
+pub fn picture_frame(spec: &FrameSpec, canvas: Rect) -> Vec<Prim> {
+ let mut out = Vec::new();
+ let short = (canvas.width().min(canvas.height()) as f32).max(8.0);
+ let margin = short * spec.margin.clamp(0.0, 30.0) / 100.0;
+ let unit = short * (0.008 + spec.size.clamp(1.0, 100.0) / 100.0 * 0.05);
+ let thick = (unit * 0.08 + short * 0.0006 * spec.thickness.clamp(1.0, 100.0)).max(0.6);
+ let spacing = unit * (4.0 - 3.2 * spec.arrangement.clamp(1.0, 100.0) / 100.0);
+ let inset = margin + unit;
+ let b = Border { x0: canvas.x0 as f32 + inset, y0: canvas.y0 as f32 + inset, w: (canvas.width() as f32 - 2.0 * inset).max(1.0), h: (canvas.height() as f32 - 2.0 * inset).max(1.0) };
+ let total = b.len();
+ let count = (total / spacing).round().max(4.0) as usize;
+ let step = total / count as f32;
+ let mut rng = Rng::new(spec.seed, 0xF8A3E + spec.frame as u64);
+ let (vine, fl, lf) = (spec.vine_color, spec.flower_color, spec.leaf_color);
+ let style = FRAME_STYLES[(spec.frame.clamp(1, FRAME_STYLES.len() as u32) - 1) as usize];
+ let lines = spec.lines.clamp(1, 5) as usize;
+ let white = [1.0, 1.0, 1.0, 1.0];
+ let yellow = [0.98, 0.82, 0.2, 1.0];
+ // A wavy vine along the border.
+ let vine_path = |out: &mut Vec<Prim>, amp: f32, wl: f32, col: [f32; 4], r: f32| {
+ let n = (total / 3.0).ceil().max(8.0) as usize;
+ let mut prev: Option<(f32, f32)> = None;
+ for k in 0..=n {
+ let s = k as f32 / n as f32 * total;
+ let (p, _, nn) = b.at(s);
+ let o = amp * (s / wl * std::f32::consts::TAU).sin();
+ let q = (p.0 + nn.0 * o, p.1 + nn.1 * o);
+ if let Some(pp) = prev {
+ out.push(Prim::capsule(pp, q, r, r, col, col));
+ }
+ prev = Some(q);
+ }
+ };
+ let wave_off = |s: f32, amp: f32, wl: f32| amp * (s / wl * std::f32::consts::TAU).sin();
+ match style {
+ "vineWithFlowers" | "vineWithLeaves" | "ivy" | "roses" | "daisies" | "berries" => {
+ let amp = unit * 0.5;
+ let wl = step * 2.0;
+ vine_path(&mut out, amp, wl, vine, thick);
+ for k in 0..count {
+ let s = k as f32 * step + step * 0.5;
+ let (p, t, nn) = b.at(s);
+ let o = wave_off(s, amp, wl);
+ let q = (p.0 + nn.0 * o, p.1 + nn.1 * o);
+ let side = if k % 2 == 0 { 1.0 } else { -1.0 };
+ let ta = t.1.atan2(t.0);
+ let la = ta + side * 0.9 + rng.sym() * 0.3;
+ let ll = unit * rng.range(0.9, 1.2);
+ match style {
+ "vineWithFlowers" => {
+ leaf(&mut out, q, la, ll, lf);
+ if k % 2 == 0 {
+ let c = (q.0 + nn.0 * unit * 0.7 * side, q.1 + nn.1 * unit * 0.7 * side);
+ flower(&mut out, c, unit * 0.65, 5, fl, yellow, rng.f() * 6.3);
+ }
+ }
+ "vineWithLeaves" => {
+ leaf(&mut out, q, la, ll, lf);
+ leaf(&mut out, q, ta - side * 0.9, ll * 0.8, lf);
+ }
+ "ivy" => {
+ for j in 0..3 {
+ let a = la + (j as f32 - 1.0) * 0.7;
+ leaf(&mut out, q, a, ll * 0.75, shade([lf[0], lf[1], lf[2]], 0.75 + 0.15 * j as f32));
+ }
+ }
+ "roses" => {
+ leaf(&mut out, q, la, ll, lf);
+ if k % 3 == 0 {
+ let r = unit * 0.7;
+ for (j, f) in [1.0f32, 0.75, 0.5, 0.28].iter().enumerate() {
+ let c = shade([fl[0], fl[1], fl[2]], 0.75 + 0.1 * j as f32);
+ out.push(Prim::ellipse(q, r * f, r * f * 0.9, rng.f() * 3.0, c, shade([fl[0], fl[1], fl[2]], 0.55)));
+ }
+ }
+ }
+ "daisies" => {
+ leaf(&mut out, q, la, ll * 0.8, lf);
+ if k % 2 == 1 {
+ flower(&mut out, q, unit * 0.6, 12, white, yellow, rng.f());
+ }
+ }
+ _ => {
+ leaf(&mut out, q, la, ll, lf);
+ for _ in 0..3 {
+ let c = (q.0 + rng.sym() * unit * 0.4, q.1 + rng.sym() * unit * 0.4);
+ out.push(Prim::ellipse(c, unit * 0.2, unit * 0.2, 0.0, shade([fl[0], fl[1], fl[2]], 1.2), shade([fl[0], fl[1], fl[2]], 0.6)));
+ }
+ }
+ }
+ }
+ }
+ "bamboo" => {
+ for edge in 0..4 {
+ let (s0, l) = match edge {
+ 0 => (0.0, b.w),
+ 1 => (b.w, b.h),
+ 2 => (b.w + b.h, b.w),
+ _ => (2.0 * b.w + b.h, b.h),
+ };
+ let (a, _, _) = b.at(s0 + 0.01);
+ let (z, _, _) = b.at(s0 + l - 0.01);
+ let joints = (l / (spacing * 2.0)).round().max(1.0) as usize;
+ for j in 0..joints {
+ let f0 = j as f32 / joints as f32;
+ let f1 = (j + 1) as f32 / joints as f32;
+ let p0 = (a.0 + (z.0 - a.0) * f0, a.1 + (z.1 - a.1) * f0);
+ let p1 = (a.0 + (z.0 - a.0) * f1, a.1 + (z.1 - a.1) * f1);
+ out.push(Prim::capsule(p0, p1, unit * 0.35, unit * 0.35, vine, shade([vine[0], vine[1], vine[2]], 0.8)));
+ out.push(Prim::disc(p1, unit * 0.4, shade([vine[0], vine[1], vine[2]], 0.7)));
+ }
+ // A few leaves per edge.
+ for _ in 0..(joints / 2).max(1) {
+ let f = rng.f();
+ let p = (a.0 + (z.0 - a.0) * f, a.1 + (z.1 - a.1) * f);
+ leaf(&mut out, p, rng.f() * 6.3, unit * 1.4, lf);
+ }
+ }
+ }
+ "waves" | "zigzag" | "doubleLine" | "rope" => {
+ for li in 0..lines {
+ let off = (li as f32 - (lines - 1) as f32 / 2.0) * thick * 4.0;
+ let n = (total / 2.0).ceil().max(8.0) as usize;
+ let mut prev: Option<(f32, f32)> = None;
+ for k in 0..=n {
+ let s = k as f32 / n as f32 * total;
+ let (p, _, nn) = b.at(s);
+ let o = off
+ + match style {
+ "waves" => wave_off(s + li as f32 * step * 0.25, unit * 0.4, step),
+ "zigzag" => {
+ let ph = (s / step).fract();
+ unit * 0.4 * (4.0 * (ph - 0.5).abs() - 1.0)
+ }
+ _ => 0.0,
+ };
+ let q = (p.0 + nn.0 * o, p.1 + nn.1 * o);
+ if style == "rope" {
+ if k % 2 == 0 {
+ let (_, t, _) = b.at(s);
+ out.push(Prim::ellipse(q, unit * 0.45, unit * 0.2, t.1.atan2(t.0) + 0.7, shade([vine[0], vine[1], vine[2]], 1.1), shade([vine[0], vine[1], vine[2]], 0.65)));
+ }
+ } else if let Some(pp) = prev {
+ out.push(Prim::capsule(pp, q, thick, thick, vine, vine));
+ }
+ prev = Some(q);
+ }
+ if style == "doubleLine" {
+ // A second rule inside each line and corner squares.
+ let inner = Border { x0: b.x0 + unit * 0.6 + off, y0: b.y0 + unit * 0.6 + off, w: b.w - 2.0 * (unit * 0.6 + off), h: b.h - 2.0 * (unit * 0.6 + off) };
+ for e in 0..4 {
+ let (p, _, _) = inner.at([0.0, inner.w, inner.w + inner.h, 2.0 * inner.w + inner.h][e]);
+ let (q, _, _) = inner.at([inner.w, inner.w + inner.h, 2.0 * inner.w + inner.h, inner.len() - 0.001][e]);
+ out.push(Prim::capsule(p, q, thick * 0.6, thick * 0.6, vine, vine));
+ }
+ }
+ }
+ if style == "doubleLine" {
+ for e in 0..4 {
+ let (p, _, _) = b.at([0.0, b.w, b.w + b.h, 2.0 * b.w + b.h][e]);
+ out.push(Prim::ellipse(p, unit * 0.45, unit * 0.45, std::f32::consts::FRAC_PI_4, fl, fl));
+ }
+ }
+ }
+ "dots" | "scallops" | "snowflakes" | "stars" | "hearts" => {
+ for k in 0..count {
+ let s = k as f32 * step;
+ let (p, t, nn) = b.at(s);
+ let ta = t.1.atan2(t.0);
+ match style {
+ "dots" => {
+ let r = unit * if k % 2 == 0 { 0.4 } else { 0.22 };
+ out.push(Prim::ellipse(p, r, r, 0.0, shade([fl[0], fl[1], fl[2]], 1.15), shade([fl[0], fl[1], fl[2]], 0.75)));
+ }
+ "scallops" => {
+ let (c0, _, _) = b.at(s - step * 0.5);
+ let mid = ((c0.0 + p.0) / 2.0, (c0.1 + p.1) / 2.0);
+ let n = 8;
+ for j in 0..n {
+ let a0 = std::f32::consts::PI * j as f32 / n as f32;
+ let a1 = std::f32::consts::PI * (j + 1) as f32 / n as f32;
+ let r = step * 0.5;
+ let pt = |a: f32| (mid.0 - t.0 * r * a.cos() - nn.0 * r * a.sin(), mid.1 - t.1 * r * a.cos() - nn.1 * r * a.sin());
+ out.push(Prim::capsule(pt(a0), pt(a1), thick, thick, vine, vine));
+ }
+ }
+ "snowflakes" => {
+ let r = unit * 0.6;
+ let c = [0.85, 0.92, 1.0, 1.0];
+ for j in 0..6 {
+ let a = ta + j as f32 * std::f32::consts::FRAC_PI_3;
+ let e = (p.0 + a.cos() * r, p.1 + a.sin() * r);
+ out.push(Prim::capsule(p, e, (thick * 0.6).max(0.6), (thick * 0.4).max(0.5), c, c));
+ let m = (p.0 + a.cos() * r * 0.6, p.1 + a.sin() * r * 0.6);
+ for sd in [-0.7f32, 0.7] {
+ let b2 = (m.0 + (a + sd).cos() * r * 0.3, m.1 + (a + sd).sin() * r * 0.3);
+ out.push(Prim::capsule(m, b2, (thick * 0.4).max(0.5), 0.4, c, c));
+ }
+ }
+ }
+ "stars" => star(&mut out, p, unit * 0.55, 5, if k % 2 == 0 { yellow } else { fl }, ta - std::f32::consts::FRAC_PI_2),
+ _ => {
+ // Heart: two lobes and a point towards the inside.
+ let r = unit * 0.3;
+ let (tx, ty) = t;
+ let l = (p.0 - tx * r * 0.8 - nn.0 * r * 0.3, p.1 - ty * r * 0.8 - nn.1 * r * 0.3);
+ let rr = (p.0 + tx * r * 0.8 - nn.0 * r * 0.3, p.1 + ty * r * 0.8 - nn.1 * r * 0.3);
+ let tip = (p.0 + nn.0 * r * 1.6, p.1 + nn.1 * r * 1.6);
+ out.push(Prim::capsule(l, tip, r, 0.6, fl, fl));
+ out.push(Prim::capsule(rr, tip, r, 0.6, fl, fl));
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ // Fade: lower the opacity of ornaments that reach further inside.
+ let fade = spec.fade.clamp(0.0, 100.0) / 100.0;
+ if fade > 0.0 {
+ let cx = canvas.x0 as f32 + canvas.width() as f32 / 2.0;
+ let cy = canvas.y0 as f32 + canvas.height() as f32 / 2.0;
+ for p in &mut out {
+ let c = match p.shape {
+ Shape::Capsule { a, .. } => a,
+ Shape::Ellipse { c, .. } => c,
+ };
+ let edge = ((c.0 - cx).abs() / (b.w / 2.0)).max((c.1 - cy).abs() / (b.h / 2.0)).clamp(0.0, 1.0);
+ let k = 1.0 - fade * (1.0 - edge) * 8.0;
+ p.c0[3] *= k.clamp(0.0, 1.0);
+ p.c1[3] *= k.clamp(0.0, 1.0);
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::{ColorMode, PixelFormat, SampleType};
+
+ #[test]
+ fn composite_draws_a_disc_and_respects_the_clip() {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
+ let p = [Prim::disc((20.0, 20.0), 8.0, [1.0, 0.0, 0.0, 1.0])];
+ let used = composite(&mut s, &p, Rect::new(0, 0, 20, 40), None);
+ assert_eq!(used.x1, 20);
+ let c = s.pixel(18, 20);
+ assert!(c[0] > 0.99 && c[3] > 0.99);
+ assert_eq!(s.pixel(22, 20)[3], 0.0, "clipped");
+ assert_eq!(s.pixel(2, 2)[3], 0.0);
+ }
+
+ #[test]
+ fn renderers_are_deterministic_and_seeded() {
+ let canvas = Rect::new(0, 0, 400, 300);
+ let a = tree(&TreeSpec::default(), canvas);
+ assert_eq!(a, tree(&TreeSpec::default(), canvas));
+ assert_ne!(a, tree(&TreeSpec { seed: 7, ..Default::default() }, canvas));
+ for k in 1..=34 {
+ assert!(!tree(&TreeSpec { base_tree_type: k, ..Default::default() }, canvas).is_empty(), "tree {k}");
+ }
+ for k in 1..=FRAME_STYLES.len() as u32 {
+ assert!(!picture_frame(&FrameSpec { frame: k, ..Default::default() }, canvas).is_empty(), "frame {k}");
+ }
+ let path = default_flame_path(canvas);
+ for t in [FlameType::OneFlameAlongPath, FlameType::MultipleFlamesAlongPath, FlameType::MultipleFlamesPathDirections, FlameType::MultipleFlamesVariousLength, FlameType::CandleLight, FlameType::MultipleFlamesOneDirection] {
+ assert!(!flame(&FlameSpec { flame_type: t, ..Default::default() }, std::slice::from_ref(&path)).is_empty(), "{t:?}");
+ }
+ }
+}
diff --git a/crates/algo/src/scancrop.rs b/crates/algo/src/scancrop.rs
new file mode 100644
index 000000000..68037121a
--- /dev/null
+++ b/crates/algo/src/scancrop.rs
@@ -0,0 +1,299 @@
+//! File › Automate › Crop and Straighten Photos: find the photos on a flatbed scan, measure each
+//! one's rotation, and cut them out upright.
+//!
+//! 1. **Background**: the median colour of the image border (a scanner lid is uniform).
+//! 2. **Foreground**: pixels whose colour distance to the background exceeds a threshold chosen
+//! by Otsu's method (N. Otsu, *A Threshold Selection Method from Gray-Level Histograms*, IEEE
+//! SMC 1979) on a downsampled copy, then closed and opened morphologically (fills specks
+//! inside photos, drops dust) and split into 8-connected components; tiny ones are dropped.
+//! 3. **Rotation**: the minimum-area enclosing rectangle of each component's convex hull
+//! (H. Freeman, R. Shapira, *Determining the Minimum-Area Encasing Rectangle for an
+//! Arbitrary Closed Curve*, CACM 1975: one side is collinear with a hull edge).
+//! 4. The rectangle is shrunk by a pixel (to drop the anti-aliased border) and returned in full
+//! resolution; callers resample it upright.
+
+/// A found photo: centre, size (long and short sides as measured along its own axes) and the
+/// rotation (degrees, clockwise) that makes it upright.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FoundPhoto {
+ pub center: [f64; 2],
+ pub width: f64,
+ pub height: f64,
+ /// Angle of the photo's x axis in the scan (degrees, `-45..=45`).
+ pub angle: f64,
+ /// Area as a fraction of the scan.
+ pub area: f64,
+}
+
+impl FoundPhoto {
+ /// The four corners in the scan, clockwise from the photo's top-left.
+ pub fn corners(&self) -> [[f64; 2]; 4] {
+ let (s, c) = self.angle.to_radians().sin_cos();
+ let (hw, hh) = (self.width / 2.0, self.height / 2.0);
+ [(-hw, -hh), (hw, -hh), (hw, hh), (-hw, hh)].map(|(x, y)| [self.center[0] + c * x - s * y, self.center[1] + s * x + c * y])
+ }
+}
+
+fn otsu(v: &[f32]) -> f32 {
+ const B: usize = 256;
+ let mut hist = [0f64; B];
+ for x in v {
+ hist[((x.clamp(0.0, 1.0)) * (B - 1) as f32) as usize] += 1.0;
+ }
+ let total: f64 = hist.iter().sum();
+ let sum: f64 = hist.iter().enumerate().map(|(i, h)| i as f64 * h).sum();
+ let (mut wb, mut sb, mut best, mut thr) = (0.0, 0.0, 0.0, 0usize);
+ for (i, h) in hist.iter().enumerate() {
+ wb += h;
+ if wb == 0.0 {
+ continue;
+ }
+ let wf = total - wb;
+ if wf == 0.0 {
+ break;
+ }
+ sb += i as f64 * h;
+ let (mb, mf) = (sb / wb, (sum - sb) / wf);
+ let between = wb * wf * (mb - mf) * (mb - mf);
+ if between > best {
+ best = between;
+ thr = i;
+ }
+ }
+ (thr as f32 + 0.5) / (B - 1) as f32
+}
+
+fn morph(w: usize, h: usize, m: &[bool], r: i64, dilate: bool) -> Vec<bool> {
+ // Separable square structuring element.
+ let pass = |src: &[bool], horizontal: bool| -> Vec<bool> {
+ let mut out = vec![false; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let mut acc = !dilate;
+ for d in -r..=r {
+ let (xx, yy) = if horizontal { (x as i64 + d, y as i64) } else { (x as i64, y as i64 + d) };
+ let v = if xx < 0 || yy < 0 || xx >= w as i64 || yy >= h as i64 { false } else { src[yy as usize * w + xx as usize] };
+ if dilate { acc |= v } else { acc &= v }
+ }
+ out[y * w + x] = acc;
+ }
+ }
+ out
+ };
+ pass(&pass(m, true), false)
+}
+
+fn convex_hull(mut pts: Vec<[f64; 2]>) -> Vec<[f64; 2]> {
+ pts.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
+ pts.dedup();
+ if pts.len() < 3 {
+ return pts;
+ }
+ let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
+ let mut lower: Vec<[f64; 2]> = Vec::new();
+ for p in &pts {
+ while lower.len() >= 2 && cross(lower[lower.len() - 2], lower[lower.len() - 1], *p) <= 0.0 {
+ lower.pop();
+ }
+ lower.push(*p);
+ }
+ let mut upper: Vec<[f64; 2]> = Vec::new();
+ for p in pts.iter().rev() {
+ while upper.len() >= 2 && cross(upper[upper.len() - 2], upper[upper.len() - 1], *p) <= 0.0 {
+ upper.pop();
+ }
+ upper.push(*p);
+ }
+ lower.pop();
+ upper.pop();
+ lower.extend(upper);
+ lower
+}
+
+/// Minimum-area rectangle around a convex hull: (centre, width, height, angle in degrees).
+fn min_rect(hull: &[[f64; 2]]) -> ([f64; 2], f64, f64, f64) {
+ let mut best = (f64::MAX, [0.0, 0.0], 0.0, 0.0, 0.0);
+ let n = hull.len();
+ for i in 0..n {
+ let (a, b) = (hull[i], hull[(i + 1) % n]);
+ let th = (b[1] - a[1]).atan2(b[0] - a[0]);
+ let (s, c) = th.sin_cos();
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for p in hull {
+ let (u, v) = (c * p[0] + s * p[1], -s * p[0] + c * p[1]);
+ x0 = x0.min(u);
+ x1 = x1.max(u);
+ y0 = y0.min(v);
+ y1 = y1.max(v);
+ }
+ let area = (x1 - x0) * (y1 - y0);
+ if area < best.0 {
+ let (cu, cv) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
+ best = (area, [c * cu - s * cv, s * cu + c * cv], x1 - x0, y1 - y0, th.to_degrees());
+ }
+ }
+ let (_, center, mut w, mut h, mut ang) = best;
+ // Normalise to −45..45, swapping the sides when turning by 90°.
+ while ang > 45.0 {
+ ang -= 90.0;
+ std::mem::swap(&mut w, &mut h);
+ }
+ while ang < -45.0 {
+ ang += 90.0;
+ std::mem::swap(&mut w, &mut h);
+ }
+ (center, w, h, ang)
+}
+
+/// Finds the photos on a scan given as straight RGBA rows (`w × h`). Photos are returned in
+/// reading order (top to bottom, then left to right).
+pub fn find_photos(w: usize, h: usize, rgba: &[[f32; 4]]) -> Vec<FoundPhoto> {
+ if w < 8 || h < 8 {
+ return Vec::new();
+ }
+ // Work on ≤ 800 px.
+ let k = (w.max(h)).div_ceil(800).max(1);
+ let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
+ let mut small = vec![[0.0f32; 3]; sw * sh];
+ let mut cnt = vec![0u32; sw * sh];
+ for y in 0..h {
+ for x in 0..w {
+ let i = (y / k) * sw + x / k;
+ let p = rgba[y * w + x];
+ for c in 0..3 {
+ small[i][c] += p[c];
+ }
+ cnt[i] += 1;
+ }
+ }
+ for (p, c) in small.iter_mut().zip(&cnt) {
+ for v in p.iter_mut() {
+ *v /= (*c).max(1) as f32;
+ }
+ }
+ // Background = per-channel median of the border.
+ let mut border: Vec<[f32; 3]> = Vec::new();
+ for x in 0..sw {
+ border.push(small[x]);
+ border.push(small[(sh - 1) * sw + x]);
+ }
+ for y in 0..sh {
+ border.push(small[y * sw]);
+ border.push(small[y * sw + sw - 1]);
+ }
+ let bg: [f32; 3] = std::array::from_fn(|c| {
+ let mut v: Vec<f32> = border.iter().map(|p| p[c]).collect();
+ v.sort_by(f32::total_cmp);
+ v[v.len() / 2]
+ });
+ let dist: Vec<f32> = small.iter().map(|p| ((p[0] - bg[0]).powi(2) + (p[1] - bg[1]).powi(2) + (p[2] - bg[2]).powi(2)).sqrt() / 3f32.sqrt()).collect();
+ let thr = otsu(&dist).max(0.04);
+ let mask: Vec<bool> = dist.iter().map(|d| *d > thr).collect();
+ let r = ((sw.max(sh) / 200) as i64).max(1);
+ let mask = morph(sw, sh, &morph(sw, sh, &mask, r, true), r, false);
+ let mask = morph(sw, sh, &morph(sw, sh, &mask, 1, false), 1, true);
+ // Connected components (8-connected).
+ let mut label = vec![u32::MAX; sw * sh];
+ let mut comps: Vec<Vec<usize>> = Vec::new();
+ for s in 0..sw * sh {
+ if !mask[s] || label[s] != u32::MAX {
+ continue;
+ }
+ let id = comps.len() as u32;
+ let mut stack = vec![s];
+ label[s] = id;
+ let mut px = Vec::new();
+ while let Some(i) = stack.pop() {
+ px.push(i);
+ let (x, y) = ((i % sw) as i64, (i / sw) as i64);
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let (xx, yy) = (x + dx, y + dy);
+ if xx < 0 || yy < 0 || xx >= sw as i64 || yy >= sh as i64 {
+ continue;
+ }
+ let j = yy as usize * sw + xx as usize;
+ if mask[j] && label[j] == u32::MAX {
+ label[j] = id;
+ stack.push(j);
+ }
+ }
+ }
+ }
+ comps.push(px);
+ }
+ let total = (sw * sh) as f64;
+ let mut out: Vec<FoundPhoto> = comps
+ .iter()
+ .filter(|c| c.len() as f64 > total * 0.01)
+ .map(|c| {
+ // Hull of the boundary pixels' corners (in full-resolution px).
+ let pts: Vec<[f64; 2]> = c
+ .iter()
+ .filter(|&&i| {
+ let (x, y) = (i % sw, i / sw);
+ x == 0 || y == 0 || x + 1 == sw || y + 1 == sh || !mask[i - 1] || !mask[i + 1] || !mask[i - sw] || !mask[i + sw]
+ })
+ .flat_map(|&i| {
+ let (x, y) = ((i % sw) as f64, (i / sw) as f64);
+ [[x, y], [x + 1.0, y], [x, y + 1.0], [x + 1.0, y + 1.0]]
+ })
+ .map(|p| [p[0] * k as f64, p[1] * k as f64])
+ .collect();
+ let hull = convex_hull(pts);
+ let (center, wd, ht, ang) = min_rect(&hull);
+ let inset = k as f64;
+ FoundPhoto { center, width: (wd - 2.0 * inset).max(1.0), height: (ht - 2.0 * inset).max(1.0), angle: ang, area: c.len() as f64 / total }
+ })
+ .collect();
+ // Reading order: rows by centre y (bands of a third of the smallest photo), then x.
+ let band = out.iter().map(|p| p.height.min(p.width)).fold(f64::MAX, f64::min).max(1.0) / 3.0;
+ out.sort_by(|a, b| ((a.center[1] / band).floor()).total_cmp(&(b.center[1] / band).floor()).then(a.center[0].total_cmp(&b.center[0])));
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A scan: white background with rotated textured rectangles.
+ fn scan(w: usize, h: usize, photos: &[FoundPhoto]) -> Vec<[f32; 4]> {
+ let mut px = vec![[0.97f32, 0.97, 0.96, 1.0]; w * h];
+ for (k, p) in photos.iter().enumerate() {
+ let (s, c) = p.angle.to_radians().sin_cos();
+ for y in 0..h {
+ for x in 0..w {
+ let (dx, dy) = (x as f64 + 0.5 - p.center[0], y as f64 + 0.5 - p.center[1]);
+ let (u, v) = (c * dx + s * dy, -s * dx + c * dy);
+ if u.abs() < p.width / 2.0 && v.abs() < p.height / 2.0 {
+ let t = ((u * 0.05).sin() * (v * 0.07).cos()) as f32;
+ px[y * w + x] = [0.3 + 0.2 * t, 0.2 + 0.1 * k as f32, 0.5 - 0.2 * t, 1.0];
+ }
+ }
+ }
+ }
+ px
+ }
+
+ #[test]
+ fn finds_rotated_photos_in_reading_order() {
+ let truth = [
+ FoundPhoto { center: [150.0, 120.0], width: 180.0, height: 120.0, angle: 7.0, area: 0.0 },
+ FoundPhoto { center: [450.0, 130.0], width: 160.0, height: 130.0, angle: -12.0, area: 0.0 },
+ FoundPhoto { center: [300.0, 330.0], width: 220.0, height: 110.0, angle: 3.0, area: 0.0 },
+ ];
+ let (w, h) = (600, 440);
+ let found = find_photos(w, h, &scan(w, h, &truth));
+ assert_eq!(found.len(), 3, "{found:?}");
+ for (f, t) in found.iter().zip(&truth) {
+ assert!((f.angle - t.angle).abs() < 1.0, "{f:?} vs {t:?}");
+ assert!((f.center[0] - t.center[0]).abs() < 3.0 && (f.center[1] - t.center[1]).abs() < 3.0, "{f:?}");
+ assert!((f.width - t.width).abs() < 6.0 && (f.height - t.height).abs() < 6.0, "{f:?}");
+ }
+ // Corners are consistent with the centre.
+ let c = found[0].corners();
+ let mid = [(c[0][0] + c[2][0]) / 2.0, (c[0][1] + c[2][1]) / 2.0];
+ assert!((mid[0] - found[0].center[0]).abs() < 1e-9);
+ assert!(find_photos(w, h, &vec![[1.0, 1.0, 1.0, 1.0]; w * h]).is_empty());
+ }
+}
diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment/mod.rs
index e73bc4bd5..dd50bc7a9 100644
--- a/crates/algo/src/segment/mod.rs
+++ b/crates/algo/src/segment/mod.rs
@@ -31,6 +31,7 @@ pub mod grabcut;
pub mod maxflow;
pub mod quick;
pub mod slic;
+pub mod sky;
pub mod subject;
use photocraft_geom::Rect;
diff --git a/crates/algo/src/segment/sky.rs b/crates/algo/src/segment/sky.rs
new file mode 100644
index 000000000..74fc62790
--- /dev/null
+++ b/crates/algo/src/segment/sky.rs
@@ -0,0 +1,278 @@
+//! Select › Sky: classical sky segmentation (no learned model).
+//!
+//! 1. At a reduced working resolution every pixel gets a *sky likelihood*: a colour prior
+//! (blue and bright, or bright and unsaturated for overcast / cloud, or a bright warm glow
+//! for sunsets) times a smoothness term (sky has little gradient energy).
+//! 2. Seeds are likely-sky pixels in the top rows; the sky region grows from them through
+//! 4-connected neighbours that stay likely-sky and change colour gradually.
+//! 3. Sky seen through gaps (between branches) is not connected to the top: likely-sky pixels
+//! that fit a colour model (GMM) of the grown sky are added too. Small holes are filled.
+//! 4. The binary working-resolution mask is upsampled and refined at full resolution with a
+//! guided filter (He, Sun & Tang, "Guided Image Filtering", ECCV 2010) on the luminance, tile
+//! by tile and only where the mask is mixed, which gives soft edges around foliage.
+
+use photocraft_geom::Rect;
+
+use super::gmm::Gmm;
+use super::{Region, RgbImage, Sampler, clean_mask, scale_for, subsample, trim_region};
+use crate::matting::{box_mean, guided_filter_gray};
+
+/// Working-resolution budget (pixels).
+pub const WORK_PX: usize = 160_000;
+
+/// Sky selection options.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct SkyParams {
+ /// 0–100: higher is stricter (fewer, more certain sky pixels).
+ pub threshold: f32,
+ /// 0–100: edge softness of the refined mask.
+ pub softness: f32,
+}
+
+impl Default for SkyParams {
+ fn default() -> Self {
+ Self { threshold: 50.0, softness: 50.0 }
+ }
+}
+
+#[inline]
+fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+}
+
+#[inline]
+fn luma(p: [f32; 3]) -> f32 {
+ 0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]
+}
+
+/// Colour prior: how sky-like a colour is on its own (0–1).
+pub fn colour_prior(p: [f32; 3]) -> f32 {
+ let [r, g, b] = p;
+ let y = luma(p);
+ let mx = r.max(g).max(b);
+ let mn = r.min(g).min(b);
+ let sat = if mx > 1e-4 { (mx - mn) / mx } else { 0.0 };
+ // Blue sky: blue dominates red clearly and isn't far below green (excludes foliage).
+ let blue = smooth(0.02, 0.12, b - r) * smooth(-0.12, 0.0, b - g) * smooth(0.18, 0.4, y);
+ // Overcast / clouds / haze: bright and nearly neutral.
+ let white = smooth(0.5, 0.75, y) * (1.0 - smooth(0.12, 0.3, sat));
+ // Sunset glow: bright and warm, kept weaker (warm walls are common too).
+ let warm = 0.6 * smooth(0.55, 0.8, y) * smooth(0.0, 0.1, r - b) * (1.0 - smooth(0.05, 0.25, g - b - 0.2));
+ blue.max(white).max(warm)
+}
+
+/// Per-pixel sky likelihood of a working-resolution image (colour prior × smoothness).
+pub fn likelihood(img: &RgbImage) -> Vec<f32> {
+ let (w, h) = (img.w, img.h);
+ let y: Vec<f32> = img.px.iter().map(|p| luma(*p)).collect();
+ let at = |x: isize, yy: isize| y[(yy.clamp(0, h as isize - 1) as usize) * w + x.clamp(0, w as isize - 1) as usize];
+ let mut grad = vec![0.0f32; w * h];
+ for yy in 0..h as isize {
+ for x in 0..w as isize {
+ let gx = (at(x + 1, yy - 1) + 2.0 * at(x + 1, yy) + at(x + 1, yy + 1)) - (at(x - 1, yy - 1) + 2.0 * at(x - 1, yy) + at(x - 1, yy + 1));
+ let gy = (at(x - 1, yy + 1) + 2.0 * at(x, yy + 1) + at(x + 1, yy + 1)) - (at(x - 1, yy - 1) + 2.0 * at(x, yy - 1) + at(x + 1, yy - 1));
+ grad[yy as usize * w + x as usize] = (gx * gx + gy * gy).sqrt() / 8.0;
+ }
+ }
+ let tex = box_mean(&grad, w, h, 2);
+ img.px.iter().zip(&tex).map(|(p, t)| colour_prior(*p) * (1.0 - smooth(0.015, 0.07, *t))).collect()
+}
+
+/// Binary sky mask at working resolution (`None` when no sky touches the top of the image).
+pub fn sky_mask_low(img: &RgbImage, threshold: f32) -> Option<Vec<bool>> {
+ let (w, h) = (img.w, img.h);
+ if w < 2 || h < 2 {
+ return None;
+ }
+ let like = likelihood(img);
+ let t = 0.12 + 0.6 * (threshold.clamp(0.0, 100.0) / 100.0);
+ // Seeds: likely sky in the top rows.
+ let top = (h / 40).max(1);
+ let mut mask = vec![false; w * h];
+ let mut stack = Vec::new();
+ for i in 0..top * w {
+ if like[i] > t {
+ mask[i] = true;
+ stack.push(i);
+ }
+ }
+ if stack.len() * 20 < top * w {
+ return None; // less than 5 % of the top edge looks like sky
+ }
+ // Region growing with a gradual-change constraint.
+ let max_step = 0.12f32;
+ while let Some(i) = stack.pop() {
+ let (x, y) = (i % w, i / w);
+ let n = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)];
+ for j in n.into_iter().flatten() {
+ if mask[j] || like[j] <= t {
+ continue;
+ }
+ let (a, b) = (img.px[i], img.px[j]);
+ let d = ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt();
+ if d < max_step {
+ mask[j] = true;
+ stack.push(j);
+ }
+ }
+ }
+ // Sky seen through gaps: likely-sky pixels that fit the grown sky's colours.
+ let samples: Vec<[f32; 3]> = img.px.iter().zip(&mask).filter(|(_, m)| **m).map(|(p, _)| *p).collect();
+ if samples.len() >= 16
+ && let Some(g) = Gmm::fit(&subsample(&samples, 4000), 3, 1e-4)
+ {
+ let mut nl: Vec<f32> = subsample(&samples, 2000).iter().map(|p| g.neg_log(*p)).collect();
+ nl.sort_by(f32::total_cmp);
+ let cut = nl[(nl.len() * 95 / 100).min(nl.len() - 1)];
+ for (i, m) in mask.iter_mut().enumerate() {
+ if !*m && like[i] > t + 0.1 && g.neg_log(img.px[i]) <= cut {
+ *m = true;
+ }
+ }
+ }
+ let mask = clean_mask(&mask, w, h, 0.002, 0.01);
+ mask.iter().any(|v| *v).then_some(mask)
+}
+
+/// Selects the sky over `canvas`. `None` if no sky was found.
+pub fn select_sky(sampler: &dyn Sampler, canvas: Rect, p: SkyParams) -> Option<Region> {
+ if canvas.width() < 4 || canvas.height() < 4 {
+ return None;
+ }
+ let step = scale_for(canvas, WORK_PX);
+ let img = sampler.rgb_scaled(canvas, step);
+ let (lw, lh) = (img.w, img.h);
+ let low = sky_mask_low(&img, p.threshold)?;
+ let lowf: Vec<f32> = low.iter().map(|v| if *v { 1.0 } else { 0.0 }).collect();
+ let soft = p.softness.clamp(0.0, 100.0) / 100.0;
+ let r = ((step as f32 * (1.0 + 2.0 * soft)).ceil() as usize).max(3);
+ let eps = 1e-4 + 4e-3 * soft;
+ // Contrast after filtering: soft 0 → narrow ramp, 1 → the filter output as is.
+ let k = 0.08 + 0.42 * soft;
+ let (w, h) = (canvas.width() as usize, canvas.height() as usize);
+ let coarse = |x: i32, y: i32| -> f32 {
+ // Bilinear upsample of the working mask (pixel centres).
+ let fx = ((x - canvas.x0) as f32 + 0.5) / step as f32 - 0.5;
+ let fy = ((y - canvas.y0) as f32 + 0.5) / step as f32 - 0.5;
+ let (x0, y0) = (fx.floor(), fy.floor());
+ let (ax, ay) = (fx - x0, fy - y0);
+ let g = |xx: f32, yy: f32| lowf[(yy.clamp(0.0, lh as f32 - 1.0) as usize) * lw + xx.clamp(0.0, lw as f32 - 1.0) as usize];
+ let top = g(x0, y0) * (1.0 - ax) + g(x0 + 1.0, y0) * ax;
+ let bot = g(x0, y0 + 1.0) * (1.0 - ax) + g(x0 + 1.0, y0 + 1.0) * ax;
+ top * (1.0 - ay) + bot * ay
+ };
+ const T: i32 = 256;
+ let mut tiles = Vec::new();
+ let mut ty = canvas.y0;
+ while ty < canvas.y1 {
+ let mut tx = canvas.x0;
+ while tx < canvas.x1 {
+ tiles.push(Rect::new(tx, ty, (tx + T).min(canvas.x1), (ty + T).min(canvas.y1)));
+ tx += T;
+ }
+ ty += T;
+ }
+ let ri = r as i32;
+ let run = |t: &Rect| -> (Rect, Vec<u8>) {
+ let win = t.inflate(ri).intersect(&canvas);
+ let (ww, wh) = (win.width() as usize, win.height() as usize);
+ let pm: Vec<f32> = (0..ww * wh).map(|i| coarse(win.x0 + (i % ww) as i32, win.y0 + (i / ww) as i32)).collect();
+ let lo = pm.iter().copied().fold(f32::MAX, f32::min);
+ let hi = pm.iter().copied().fold(f32::MIN, f32::max);
+ let crop = |v: &[f32]| -> Vec<u8> {
+ let mut o = Vec::with_capacity(t.width() as usize * t.height() as usize);
+ for y in t.y0..t.y1 {
+ for x in t.x0..t.x1 {
+ let q = v[(y - win.y0) as usize * ww + (x - win.x0) as usize];
+ o.push((smooth(0.5 - k, 0.5 + k, q) * 255.0).round() as u8);
+ }
+ }
+ o
+ };
+ if hi <= 0.0 || lo >= 1.0 {
+ return (*t, vec![if lo >= 1.0 { 255 } else { 0 }; t.width() as usize * t.height() as usize]);
+ }
+ let guide: Vec<f32> = sampler.rgb(win).px.iter().map(|q| luma(*q)).collect();
+ let q = guided_filter_gray(&guide, &pm, ww, wh, r, eps);
+ (*t, crop(&q))
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ let parts: Vec<(Rect, Vec<u8>)> = {
+ use rayon::prelude::*;
+ tiles.par_iter().map(run).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let parts: Vec<(Rect, Vec<u8>)> = tiles.iter().map(run).collect();
+ let mut mask = vec![0u8; w * h];
+ for (t, v) in parts {
+ let tw = t.width() as usize;
+ for (row, y) in (t.y0..t.y1).enumerate() {
+ let o = (y - canvas.y0) as usize * w + (t.x0 - canvas.x0) as usize;
+ mask[o..o + tw].copy_from_slice(&v[row * tw..(row + 1) * tw]);
+ }
+ }
+ trim_region(Region { bbox: canvas, mask })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::ImageSampler;
+ use super::*;
+
+ /// Blue gradient sky over textured ground, with a dark round "tree" crown on a trunk
+ /// reaching into the sky.
+ pub(crate) fn landscape(w: usize, h: usize) -> RgbImage {
+ let horizon = h * 3 / 5;
+ RgbImage::from_fn(w, h, |x, y| {
+ let (cx, cy, rr) = (w as f32 * 0.7, h as f32 * 0.35, h as f32 * 0.18);
+ let in_crown = ((x as f32 - cx).powi(2) + (y as f32 - cy).powi(2)).sqrt() < rr;
+ let in_trunk = (x as f32 - cx).abs() < 3.0 && y as f32 > cy && y < horizon;
+ let n = (((x * 7919 + y * 104_729) % 97) as f32 / 97.0 - 0.5) * 0.25;
+ if in_crown {
+ [0.1 + n * 0.5, 0.35 + n, 0.1 + n * 0.5]
+ } else if in_trunk {
+ [0.3 + n * 0.3, 0.2, 0.1]
+ } else if y < horizon {
+ let t = y as f32 / horizon as f32;
+ [0.25 + 0.4 * t, 0.5 + 0.3 * t, 0.9 + 0.05 * t]
+ } else {
+ [0.35 + n, 0.3 + n, 0.15 + n * 0.5]
+ }
+ })
+ }
+
+ #[test]
+ fn finds_sky_and_not_ground_or_tree() {
+ let img = landscape(160, 100);
+ let r = select_sky(&ImageSampler { img: &img, origin: (0, 0) }, Rect::new(0, 0, 160, 100), SkyParams::default()).expect("sky");
+ assert!(r.at(10, 5) > 0.9, "top-left sky");
+ assert!(r.at(80, 50) > 0.9, "sky near the horizon");
+ assert!(r.at(10, 80) < 0.1, "ground");
+ assert!(r.at(112, 35) < 0.1, "tree crown");
+ assert!(r.bbox.y1 <= 64, "{:?}", r.bbox);
+ }
+
+ #[test]
+ fn no_sky_in_a_ground_only_image() {
+ let img = RgbImage::from_fn(64, 64, |x, y| {
+ let n = (((x * 7919 + y * 104_729) % 97) as f32 / 97.0 - 0.5) * 0.3;
+ [0.35 + n, 0.3 + n, 0.12]
+ });
+ assert!(select_sky(&ImageSampler { img: &img, origin: (0, 0) }, Rect::new(0, 0, 64, 64), SkyParams::default()).is_none());
+ }
+
+ #[test]
+ fn overcast_sky_is_found() {
+ let img = RgbImage::from_fn(64, 64, |_, y| if y < 30 { [0.85, 0.86, 0.88] } else { [0.2, 0.3, 0.1] });
+ let r = select_sky(&ImageSampler { img: &img, origin: (0, 0) }, Rect::new(0, 0, 64, 64), SkyParams::default()).expect("sky");
+ assert!(r.at(30, 10) > 0.9 && r.at(30, 50) < 0.1);
+ }
+
+ #[test]
+ fn colour_prior_ranks_sky_over_foliage() {
+ assert!(colour_prior([0.4, 0.6, 0.95]) > 0.8);
+ assert!(colour_prior([0.15, 0.4, 0.15]) < 0.1);
+ assert!(colour_prior([0.9, 0.9, 0.92]) > 0.8);
+ }
+}
diff --git a/crates/algo/src/vanishing.rs b/crates/algo/src/vanishing.rs
new file mode 100644
index 000000000..02bc79dd8
--- /dev/null
+++ b/crates/algo/src/vanishing.rs
@@ -0,0 +1,408 @@
+//! Filter › Vanishing Point: perspective planes, pasting onto a plane and cloning in perspective.
+//!
+//! A plane is a quad the user aligns with a flat surface in the photo. Its two vanishing points
+//! (where opposite edges meet) give the camera's focal length for a centred principal point,
+//! `f² = −(v₁ − c)·(v₂ − c)` (R. Hartley, A. Zisserman, *Multiple View Geometry*, 2nd ed., §8.8:
+//! orthogonal vanishing directions), which lifts the quad to 3-D: each corner is back-projected
+//! onto the plane through the vanishing directions' normal. That gives the plane's metric aspect
+//! (so pasted images keep their proportions) and lets perpendicular planes be torn off an edge
+//! by rotating about it in 3-D and projecting back.
+//!
+//! Pasting maps the image's rectangle into the plane's metric coordinates and warps it with the
+//! composed homography, clipped to the plane. Clone stamping copies, for each destination dab,
+//! the pixels at the same metric offset from the source point, so texture shrinks with distance
+//! as it does in the photo.
+
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde::{Deserialize, Serialize};
+
+use crate::transform::{Homography, Interp, warp_surface};
+
+type V3 = [f64; 3];
+
+fn sub(a: V3, b: V3) -> V3 {
+ [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
+}
+fn add(a: V3, b: V3) -> V3 {
+ [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
+}
+fn mul(a: V3, k: f64) -> V3 {
+ [a[0] * k, a[1] * k, a[2] * k]
+}
+fn dot(a: V3, b: V3) -> f64 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+fn cross(a: V3, b: V3) -> V3 {
+ [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
+}
+fn norm(a: V3) -> V3 {
+ mul(a, 1.0 / dot(a, a).sqrt().max(1e-300))
+}
+
+/// Intersection of lines (a, b) and (c, d) in homogeneous coordinates.
+fn meet(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> V3 {
+ let l1 = cross([a[0], a[1], 1.0], [b[0], b[1], 1.0]);
+ let l2 = cross([c[0], c[1], 1.0], [d[0], d[1], 1.0]);
+ cross(l1, l2)
+}
+
+/// A perspective plane: corners in image px, clockwise from the plane's top-left.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct VpPlane {
+ pub corners: [[f64; 2]; 4],
+}
+
+/// Plane edges for tearing off a perpendicular plane.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Edge {
+ Top,
+ Right,
+ Bottom,
+ Left,
+}
+
+/// The camera and a plane lifted to 3-D.
+#[derive(Clone, Debug)]
+pub struct Lifted {
+ pub focal: f64,
+ pub center: [f64; 2],
+ /// 3-D corners (camera coordinates, plane at unit distance along its normal).
+ pub pts: [V3; 4],
+}
+
+impl VpPlane {
+ /// Unit square (u, v) → image.
+ pub fn homography(&self) -> Option<Homography> {
+ Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], self.corners)
+ }
+
+ /// Focal length (px) implied by the plane's two vanishing points, if both are finite and
+ /// consistent with a camera centred at `c`.
+ pub fn focal(&self, c: [f64; 2]) -> Option<f64> {
+ let q = &self.corners;
+ let v1 = meet(q[0], q[1], q[3], q[2]);
+ let v2 = meet(q[0], q[3], q[1], q[2]);
+ if v1[2].abs() < 1e-9 || v2[2].abs() < 1e-9 {
+ return None;
+ }
+ let (a, b) = ([v1[0] / v1[2] - c[0], v1[1] / v1[2] - c[1]], [v2[0] / v2[2] - c[0], v2[1] / v2[2] - c[1]]);
+ let f2 = -(a[0] * b[0] + a[1] * b[1]);
+ (f2 > 1.0).then(|| f2.sqrt())
+ }
+
+ /// Lifts the plane to 3-D with focal `f` (camera at the origin looking along +z).
+ pub fn lift(&self, f: f64, c: [f64; 2]) -> Lifted {
+ let ray = |p: [f64; 2]| [(p[0] - c[0]) / f, (p[1] - c[1]) / f, 1.0];
+ let q = &self.corners;
+ // Vanishing directions (or the edge directions when they're parallel in the image).
+ let dir = |a: [f64; 2], b: [f64; 2], cc: [f64; 2], d: [f64; 2]| -> V3 {
+ let v = meet(a, b, cc, d);
+ if v[2].abs() < 1e-9 * (v[0].abs() + v[1].abs()).max(1.0) {
+ norm([v[0], v[1], 0.0])
+ } else {
+ norm(ray([v[0] / v[2], v[1] / v[2]]))
+ }
+ };
+ let d1 = dir(q[0], q[1], q[3], q[2]);
+ let d2 = dir(q[0], q[3], q[1], q[2]);
+ let mut n = norm(cross(d1, d2));
+ if n[2] < 0.0 {
+ n = mul(n, -1.0);
+ }
+ let pts = q.map(|p| {
+ let r = ray(p);
+ let lam = 1.0 / dot(n, r).abs().max(1e-9);
+ mul(r, lam)
+ });
+ Lifted { focal: f, center: c, pts }
+ }
+}
+
+impl Lifted {
+ pub fn project(&self, x: V3) -> Option<[f64; 2]> {
+ (x[2] > 1e-9).then(|| [self.center[0] + self.focal * x[0] / x[2], self.center[1] + self.focal * x[1] / x[2]])
+ }
+ /// Metric side lengths (u along top edge, v along left edge).
+ pub fn lengths(&self) -> (f64, f64) {
+ let l = |a: V3, b: V3| dot(sub(a, b), sub(a, b)).sqrt();
+ ((l(self.pts[0], self.pts[1]) + l(self.pts[3], self.pts[2])) / 2.0, (l(self.pts[0], self.pts[3]) + l(self.pts[1], self.pts[2])) / 2.0)
+ }
+}
+
+/// A scene: planes plus the shared focal length.
+#[derive(Clone, Debug)]
+pub struct Scene {
+ pub planes: Vec<VpPlane>,
+ pub focal: f64,
+ pub center: [f64; 2],
+}
+
+impl Scene {
+ /// Focal length from the first plane (or `fallback` px when it is fronto-parallel).
+ pub fn new(first: VpPlane, center: [f64; 2], focal: Option<f64>, fallback: f64) -> Scene {
+ let f = focal.filter(|f| *f > 1.0).or_else(|| first.focal(center)).unwrap_or(fallback);
+ Scene { planes: vec![first], focal: f, center }
+ }
+
+ pub fn lifted(&self, i: usize) -> Lifted {
+ self.planes[i].lift(self.focal, self.center)
+ }
+
+ /// Tears a plane off edge `edge` of plane `from`, turned by `angle` degrees about that edge
+ /// (90 = perpendicular), extending `depth` times the parent's adjacent side. Returns its index.
+ pub fn tear_off(&mut self, from: usize, edge: Edge, angle: f64, depth: f64) -> Option<usize> {
+ let lf = self.lifted(from);
+ let p = lf.pts;
+ // Edge endpoints (a → b, clockwise) and the parent's inward direction.
+ let (ia, ib, ic) = match edge {
+ Edge::Top => (0, 1, 3),
+ Edge::Right => (1, 2, 0),
+ Edge::Bottom => (2, 3, 1),
+ Edge::Left => (3, 0, 2),
+ };
+ let (a, b) = (p[ia], p[ib]);
+ let axis = norm(sub(b, a));
+ let inward = sub(p[ic], p[ia]);
+ let len = dot(inward, inward).sqrt() * depth.max(0.05);
+ // The new plane continues outward (−inward), turned about the edge by 180° − angle; of
+ // the two turning directions pick the one that faces the camera with the parent in front
+ // of it (a room corner, as Photoshop tears planes off).
+ let out = mul(norm(inward), -1.0);
+ let th = (180.0 - angle).to_radians();
+ let mut best: Option<(f64, [[f64; 2]; 4])> = None;
+ for sgn in [1.0, -1.0] {
+ let (s, c) = (sgn * th).sin_cos();
+ let rot = add(add(mul(out, c), mul(cross(axis, out), s)), mul(axis, dot(axis, out) * (1.0 - c)));
+ let (a2, b2) = (add(a, mul(rot, len)), add(b, mul(rot, len)));
+ let (Some(pa), Some(pb), Some(pa2), Some(pb2)) = (lf.project(a), lf.project(b), lf.project(a2), lf.project(b2)) else { continue };
+ let mut n2 = norm(cross(sub(b, a), sub(a2, a)));
+ if dot(n2, a) > 0.0 {
+ n2 = mul(n2, -1.0);
+ }
+ let score = dot(n2, inward);
+ if best.as_ref().is_none_or(|(sc, _)| score > *sc) {
+ best = Some((score, [pa, pb, pa2, pb2]));
+ }
+ }
+ let (_, [pa, pb, pa2, pb2]) = best?;
+ // Keep corners clockwise from the new plane's top-left (shared edge first or last).
+ let corners = match edge {
+ Edge::Top => [pa2, pb2, pb, pa],
+ Edge::Right => [pa, pa2, pb2, pb],
+ Edge::Bottom => [pb, pa, pa2, pb2],
+ Edge::Left => [pb2, pb, pa, pa2],
+ };
+ self.planes.push(VpPlane { corners });
+ Some(self.planes.len() - 1)
+ }
+
+ /// Plane-metric frame of plane `i`: (homography unit square → image, metric width, height).
+ pub fn frame(&self, i: usize) -> Option<(Homography, f64, f64)> {
+ let h = self.planes[i].homography()?;
+ let (lu, lv) = self.lifted(i).lengths();
+ Some((h, lu, lv))
+ }
+
+ /// The plane whose quad contains image point `p`.
+ pub fn plane_at(&self, p: [f64; 2]) -> Option<usize> {
+ (0..self.planes.len()).rev().find(|&i| {
+ self.planes[i].homography().and_then(|h| h.inverse()).is_some_and(|inv| {
+ let (u, v) = inv.apply(p[0], p[1]);
+ (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)
+ })
+ })
+ }
+}
+
+/// Coverage mask (0/1 surface values) of a plane quad over `area`.
+fn quad_mask(h: &Homography, area: Rect) -> Vec<f32> {
+ let Some(inv) = h.inverse() else { return vec![0.0; (area.width() * area.height()) as usize] };
+ let w = area.width() as usize;
+ (0..(area.width() * area.height()) as usize)
+ .map(|i| {
+ let (x, y) = (area.x0 as f64 + (i % w) as f64 + 0.5, area.y0 as f64 + (i / w) as f64 + 0.5);
+ let (u, v) = inv.apply(x, y);
+ if (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v) { 1.0 } else { 0.0 }
+ })
+ .collect()
+}
+
+/// Pastes `src` (content in `src_rect`) onto plane `i` with its top-left at plane coordinates
+/// `at` (0..1) and its width `width` (fraction of the plane's width), aspect preserved in the
+/// plane's metric. Returns the warped image clipped to the plane (transparent elsewhere).
+pub fn paste(scene: &Scene, i: usize, src: &Surface, src_rect: Rect, at: [f64; 2], width: f64) -> Option<Surface> {
+ let (h, lu, lv) = scene.frame(i)?;
+ let (sw, sh) = (src_rect.width() as f64, src_rect.height() as f64);
+ if sw <= 0.0 || sh <= 0.0 {
+ return None;
+ }
+ // Source px → plane (u, v): u spans `width`, v keeps the metric aspect.
+ let su = width / sw;
+ let sv = width * lu / lv / sw;
+ let to_plane = Homography([su, 0.0, at[0] - src_rect.x0 as f64 * su, 0.0, sv, at[1] - src_rect.y0 as f64 * sv, 0.0, 0.0, 1.0]);
+ let full = h.mul(&to_plane);
+ let mut out = warp_surface(src, src_rect, &full, Interp::Bicubic);
+ // Clip to the plane.
+ let b = out.content_bounds();
+ if b.is_empty() {
+ return Some(out);
+ }
+ let mask = quad_mask(&h, b);
+ let fmt = out.format();
+ let n = fmt.channels();
+ let mut data = out.read_region(b);
+ for (px, m) in data.chunks_exact_mut(n).zip(&mask) {
+ px[n - 1] *= m;
+ }
+ out.write_region(b, &data);
+ out.prune();
+ Some(out)
+}
+
+/// Perspective clone stamp: one stroke of dabs at image points `points` on the destination
+/// plane, copying from `source` (image px) with the offset fixed in plane-metric units at the
+/// first dab. `size` is the brush diameter in px at the first dab; `hardness` 0..=1.
+pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: &[[f64; 2]], size: f64, hardness: f64, opacity: f32) -> usize {
+ let Some(first) = points.first() else { return 0 };
+ let (Some(ps), Some(pd)) = (scene.plane_at(source), scene.plane_at(*first)) else { return 0 };
+ let (Some((hs, lus, lvs)), Some((hd, lud, lvd))) = (scene.frame(ps), scene.frame(pd)) else { return 0 };
+ let (Some(hs_inv), Some(hd_inv)) = (hs.inverse(), hd.inverse()) else { return 0 };
+ let metric = |inv: &Homography, lu: f64, lv: f64, p: [f64; 2]| {
+ let (u, v) = inv.apply(p[0], p[1]);
+ [u * lu, v * lv]
+ };
+ let ms = metric(&hs_inv, lus, lvs, source);
+ let md0 = metric(&hd_inv, lud, lvd, *first);
+ let offset = [ms[0] - md0[0], ms[1] - md0[1]];
+ // Brush radius in metric units (from the image size at the first dab).
+ let probe = metric(&hd_inv, lud, lvd, [first[0] + size / 2.0, first[1]]);
+ let r_m = ((probe[0] - md0[0]).hypot(probe[1] - md0[1])).max(1e-9);
+ let src_copy = surf.clone();
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let mut dabs = 0;
+ for p in points {
+ let mc = metric(&hd_inv, lud, lvd, *p);
+ // Image-space footprint: map a metric circle's bounding points.
+ let mut bb = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
+ for k in 0..16 {
+ let a = k as f64 / 16.0 * std::f64::consts::TAU;
+ let (u, v) = ((mc[0] + r_m * a.cos()) / lud, (mc[1] + r_m * a.sin()) / lvd);
+ let (x, y) = hd.apply(u, v);
+ bb = [bb[0].min(x), bb[1].min(y), bb[2].max(x), bb[3].max(y)];
+ }
+ let area = Rect::new(bb[0].floor() as i32, bb[1].floor() as i32, bb[2].ceil() as i32 + 1, bb[3].ceil() as i32 + 1);
+ if area.is_empty() || area.width() > 4096 || area.height() > 4096 {
+ continue;
+ }
+ let mut data = surf.read_region(area);
+ let w = area.width() as usize;
+ let mut changed = false;
+ for (i, px) in data.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (area.x0 as f64 + (i % w) as f64 + 0.5, area.y0 as f64 + (i / w) as f64 + 0.5);
+ let m = metric(&hd_inv, lud, lvd, [x, y]);
+ let d = (m[0] - mc[0]).hypot(m[1] - mc[1]) / r_m;
+ if d >= 1.0 {
+ continue;
+ }
+ let hard = hardness.clamp(0.0, 0.99);
+ let fall = if d <= hard { 1.0 } else { 1.0 - (d - hard) / (1.0 - hard) };
+ let k = (fall * fall * (3.0 - 2.0 * fall)) as f32 * opacity;
+ // Source pixel at the same metric offset.
+ let sm = [m[0] + offset[0], m[1] + offset[1]];
+ let (sx, sy) = hs.apply(sm[0] / lus, sm[1] / lvs);
+ let s = sample(&src_copy, sx - 0.5, sy - 0.5, n);
+ for c in 0..n {
+ px[c] += (s[c] - px[c]) * k;
+ }
+ changed = true;
+ }
+ if changed {
+ surf.write_region(area, &data);
+ dabs += 1;
+ }
+ }
+ dabs
+}
+
+fn sample(s: &Surface, x: f64, y: f64, n: usize) -> Vec<f32> {
+ let (x0, y0) = (x.floor() as i32, y.floor() as i32);
+ let (tx, ty) = ((x - x0 as f64) as f32, (y - y0 as f64) as f32);
+ let r = s.read_region(Rect::new(x0, y0, x0 + 2, y0 + 2));
+ (0..n).map(|c| (r[c] * (1.0 - tx) + r[n + c] * tx) * (1.0 - ty) + (r[2 * n + c] * (1.0 - tx) + r[3 * n + c] * tx) * ty).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_color::PixelFormat;
+
+ /// A ground plane seen by a camera with f = 500 px: projects 3-D points.
+ fn project(f: f64, c: [f64; 2], p: V3) -> [f64; 2] {
+ [c[0] + f * p[0] / p[2], c[1] + f * p[1] / p[2]]
+ }
+
+ fn floor_quad(f: f64, c: [f64; 2]) -> VpPlane {
+ // A 2 × 1 rectangle on a tilted plane, rotated about the vertical axis too.
+ let (rx, ry) = (0.6f64, 0.4f64);
+ let rot = |p: V3| {
+ let (s, co) = rx.sin_cos();
+ let q = [p[0], co * p[1] - s * p[2], s * p[1] + co * p[2]];
+ let (s2, c2) = ry.sin_cos();
+ [c2 * q[0] + s2 * q[2], q[1], -s2 * q[0] + c2 * q[2]]
+ };
+ let corners = [[-1.0, -0.5, 0.0], [1.0, -0.5, 0.0], [1.0, 0.5, 0.0], [-1.0, 0.5, 0.0]].map(|p: V3| project(f, c, add(rot(p), [0.0, 0.0, 4.0])));
+ VpPlane { corners }
+ }
+
+ #[test]
+ fn focal_and_metric_aspect_from_one_plane() {
+ let c = [400.0, 300.0];
+ let pl = floor_quad(500.0, c);
+ let f = pl.focal(c).unwrap();
+ assert!((f - 500.0).abs() < 1.0, "{f}");
+ let (lu, lv) = pl.lift(f, c).lengths();
+ assert!((lu / lv - 2.0).abs() < 0.01, "aspect {}", lu / lv);
+ }
+
+ #[test]
+ fn tear_off_is_perpendicular_and_shares_the_edge() {
+ let c = [400.0, 300.0];
+ let mut sc = Scene::new(floor_quad(500.0, c), c, None, 800.0);
+ let k = sc.tear_off(0, Edge::Top, 90.0, 1.0).unwrap();
+ let p = &sc.planes[k];
+ // Shared edge.
+ assert!((p.corners[3][0] - sc.planes[0].corners[0][0]).abs() < 1e-6 && (p.corners[2][0] - sc.planes[0].corners[1][0]).abs() < 1e-6);
+ // In 3-D the new plane is perpendicular.
+ let (a, b) = (sc.lifted(0), sc.lifted(k));
+ let n1 = norm(cross(sub(a.pts[1], a.pts[0]), sub(a.pts[3], a.pts[0])));
+ let n2 = norm(cross(sub(b.pts[1], b.pts[0]), sub(b.pts[3], b.pts[0])));
+ assert!(dot(n1, n2).abs() < 0.02, "{}", dot(n1, n2));
+ }
+
+ #[test]
+ fn paste_and_clone_in_perspective() {
+ let c = [400.0, 300.0];
+ let sc = Scene::new(floor_quad(500.0, c), c, None, 800.0);
+ let mut img = Surface::new(PixelFormat::RGBA8);
+ img.fill_rect(Rect::new(0, 0, 100, 50), &[1.0, 0.0, 0.0, 1.0]);
+ let out = paste(&sc, 0, &img, Rect::new(0, 0, 100, 50), [0.25, 0.25], 0.5).unwrap();
+ // The pasted rectangle lands inside the plane, around plane (0.5, 0.5).
+ let h = sc.planes[0].homography().unwrap();
+ let (x, y) = h.apply(0.5, 0.5);
+ assert!(out.rgba(x as i32, y as i32)[3] > 0.9);
+ let (x, y) = h.apply(0.1, 0.1);
+ assert!(out.rgba(x as i32, y as i32)[3] < 0.1);
+ // Clone: paint a red dot near the far edge from a red source near the near edge.
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(Rect::new(0, 0, 800, 600), &[0.2, 0.2, 0.2, 1.0]);
+ let (sx, sy) = h.apply(0.5, 0.8);
+ s.fill_rect(Rect::new(sx as i32 - 6, sy as i32 - 6, sx as i32 + 6, sy as i32 + 6), &[1.0, 0.0, 0.0, 1.0]);
+ let (dx, dy) = h.apply(0.5, 0.3);
+ let n = clone_stroke(&sc, &mut s, [sx, sy], &[[dx, dy]], 10.0, 0.8, 1.0);
+ assert_eq!(n, 1);
+ assert!(s.rgba(dx as i32, dy as i32)[0] > 0.8, "{:?}", s.rgba(dx as i32, dy as i32));
+ }
+}
diff --git a/crates/algo/src/wideangle.rs b/crates/algo/src/wideangle.rs
new file mode 100644
index 000000000..a15b9341b
--- /dev/null
+++ b/crates/algo/src/wideangle.rs
@@ -0,0 +1,444 @@
+//! Filter › Adaptive Wide Angle: straighten lines that a wide-angle or fisheye lens bends.
+//!
+//! The user marks constraints by their two end points; the lens model (equidistant fisheye
+//! `r = f·θ`, rectilinear perspective `r = f·tan θ`, or a full 2:1 equirectangular sphere) turns
+//! them into rays, and the scene line between them is the great circle through both rays,
+//! which is sampled back into the image as the curve the user sees. A content-preserving mesh
+//! warp then makes every constrained curve straight (and horizontal or vertical when asked)
+//! while keeping each mesh triangle as similar as possible to its original shape:
+//!
+//! * shape term: T. Igarashi, T. Moscovich, J. Hughes, *As-Rigid-As-Possible Shape
+//! Manipulation*, SIGGRAPH 2005 (the similarity / "as-similar-as-possible" step), as used for
+//! wide-angle correction by R. Carroll, M. Agrawala, A. Agarwala, *Optimizing
+//! Content-Preserving Projections for Wide-Angle Images*, SIGGRAPH 2009;
+//! * line term: every sample of a constrained curve lies on one output line (normal fixed for
+//! horizontal / vertical constraints, re-estimated a few times for free ones), as in
+//! Carroll et al.
+//!
+//! The linear least-squares problems are solved with conjugate gradients. The result is
+//! rendered by textured triangles ([`crate::warp::warp_triangles`]).
+
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde::{Deserialize, Serialize};
+
+use crate::photo_util::SparseLs;
+use crate::transform::Interp;
+
+/// Lens projection of the source image.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum WideModel {
+ #[default]
+ Auto,
+ Fisheye,
+ Perspective,
+ FullSpherical,
+}
+
+impl WideModel {
+ pub fn parse(s: &str) -> Option<WideModel> {
+ Some(match s {
+ "auto" => WideModel::Auto,
+ "fisheye" => WideModel::Fisheye,
+ "perspective" => WideModel::Perspective,
+ "fullSpherical" | "spherical" => WideModel::FullSpherical,
+ _ => return None,
+ })
+ }
+}
+
+/// Constraint orientation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum Orientation {
+ #[default]
+ Free,
+ Horizontal,
+ Vertical,
+}
+
+/// A constraint: the end points of a scene line (image px).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Constraint {
+ pub a: [f64; 2],
+ pub b: [f64; 2],
+ #[serde(default)]
+ pub orientation: Orientation,
+}
+
+/// Adaptive Wide Angle settings.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct WideAngle {
+ pub model: WideModel,
+ /// Focal length in mm (35 mm frame after the crop factor).
+ pub focal_length: f64,
+ pub crop_factor: f64,
+ /// Output scale in percent.
+ pub scale: f64,
+ pub constraints: Vec<Constraint>,
+}
+
+impl Default for WideAngle {
+ fn default() -> Self {
+ WideAngle { model: WideModel::Auto, focal_length: 0.0, crop_factor: 1.0, scale: 100.0, constraints: Vec::new() }
+ }
+}
+
+/// Camera model over an image frame.
+#[derive(Clone, Copy, Debug)]
+pub struct Camera {
+ pub model: WideModel,
+ /// Focal length in px.
+ pub f: f64,
+ pub c: [f64; 2],
+ pub size: [f64; 2],
+}
+
+impl Camera {
+ /// Resolves `Auto` and the focal length: 35 mm-equivalent `focal_mm × crop` over a 36 mm
+ /// long side; `0` picks a default (fisheye 8 mm-ish, perspective 24 mm).
+ pub fn new(p: &WideAngle, frame: Rect) -> Camera {
+ let (w, h) = (frame.width().max(1) as f64, frame.height().max(1) as f64);
+ let f35 = p.focal_length * p.crop_factor.max(0.1);
+ let model = match p.model {
+ WideModel::Auto => {
+ if (w / h - 2.0).abs() < 0.01 {
+ WideModel::FullSpherical
+ } else if f35 > 0.0 && f35 < 17.0 {
+ WideModel::Fisheye
+ } else {
+ WideModel::Perspective
+ }
+ }
+ m => m,
+ };
+ let f35 = if f35 > 0.0 {
+ f35
+ } else if model == WideModel::Fisheye {
+ 12.0
+ } else {
+ 24.0
+ };
+ Camera { model, f: f35 / 36.0 * w.max(h), c: [(frame.x0 + frame.x1) as f64 / 2.0, (frame.y0 + frame.y1) as f64 / 2.0], size: [w, h] }
+ }
+
+ /// Image px → unit ray (x right, y down, z forward).
+ pub fn ray(&self, x: f64, y: f64) -> [f64; 3] {
+ let (dx, dy) = (x - self.c[0], y - self.c[1]);
+ let v = match self.model {
+ WideModel::FullSpherical => {
+ let lon = dx / self.size[0] * std::f64::consts::TAU;
+ let lat = dy / self.size[1] * std::f64::consts::PI;
+ [lon.sin() * lat.cos(), lat.sin(), lon.cos() * lat.cos()]
+ }
+ WideModel::Fisheye => {
+ let r = dx.hypot(dy);
+ let th = r / self.f;
+ if r < 1e-12 { [0.0, 0.0, 1.0] } else { [th.sin() * dx / r, th.sin() * dy / r, th.cos()] }
+ }
+ _ => [dx, dy, self.f],
+ };
+ norm(v)
+ }
+
+ /// Unit ray → image px.
+ pub fn pixel(&self, d: [f64; 3]) -> Option<[f64; 2]> {
+ match self.model {
+ WideModel::FullSpherical => {
+ let lon = d[0].atan2(d[2]);
+ let lat = d[1].clamp(-1.0, 1.0).asin();
+ Some([self.c[0] + lon / std::f64::consts::TAU * self.size[0], self.c[1] + lat / std::f64::consts::PI * self.size[1]])
+ }
+ WideModel::Fisheye => {
+ let th = d[2].clamp(-1.0, 1.0).acos();
+ let s = d[0].hypot(d[1]);
+ if s < 1e-12 {
+ return Some(self.c);
+ }
+ Some([self.c[0] + self.f * th * d[0] / s, self.c[1] + self.f * th * d[1] / s])
+ }
+ _ => (d[2] > 1e-6).then(|| [self.c[0] + self.f * d[0] / d[2], self.c[1] + self.f * d[1] / d[2]]),
+ }
+ }
+
+ /// `n + 1` image points along the scene line (great circle) from `a` to `b`.
+ pub fn arc(&self, a: [f64; 2], b: [f64; 2], n: usize) -> Vec<[f64; 2]> {
+ let (da, db) = (self.ray(a[0], a[1]), self.ray(b[0], b[1]));
+ let omega = dot(da, db).clamp(-1.0, 1.0).acos();
+ (0..=n)
+ .filter_map(|k| {
+ let t = k as f64 / n as f64;
+ let d = if omega < 1e-9 {
+ da
+ } else {
+ let (sa, sb) = (((1.0 - t) * omega).sin() / omega.sin(), (t * omega).sin() / omega.sin());
+ norm([sa * da[0] + sb * db[0], sa * da[1] + sb * db[1], sa * da[2] + sb * db[2]])
+ };
+ self.pixel(d)
+ })
+ .collect()
+ }
+}
+
+fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+fn norm(v: [f64; 3]) -> [f64; 3] {
+ let l = dot(v, v).sqrt().max(1e-300);
+ [v[0] / l, v[1] / l, v[2] / l]
+}
+
+/// The solved warp: a grid over the frame with each vertex's output position.
+#[derive(Clone, Debug)]
+pub struct WideMesh {
+ pub nx: usize,
+ pub ny: usize,
+ /// `(output, source)` per vertex, row-major `(nx + 1) × (ny + 1)`.
+ pub verts: Vec<([f64; 2], [f64; 2])>,
+ /// Each constraint's curve in the source (for overlays).
+ pub curves: Vec<Vec<[f64; 2]>>,
+ /// Max deviation from straight of the constrained curves after the warp (px).
+ pub residual: f64,
+}
+
+impl WideMesh {
+ pub fn triangles(&self) -> Vec<[usize; 3]> {
+ let w1 = self.nx + 1;
+ let mut t = Vec::with_capacity(self.nx * self.ny * 2);
+ for j in 0..self.ny {
+ for i in 0..self.nx {
+ let a = j * w1 + i;
+ t.push([a, a + 1, a + w1 + 1]);
+ t.push([a, a + w1 + 1, a + w1]);
+ }
+ }
+ t
+ }
+
+ /// Output position of source point `p` (bilinear in its grid cell).
+ pub fn map(&self, frame: Rect, p: [f64; 2]) -> [f64; 2] {
+ let (cw, ch) = (frame.width() as f64 / self.nx as f64, frame.height() as f64 / self.ny as f64);
+ let gx = ((p[0] - frame.x0 as f64) / cw).clamp(0.0, self.nx as f64 - 1e-9);
+ let gy = ((p[1] - frame.y0 as f64) / ch).clamp(0.0, self.ny as f64 - 1e-9);
+ let (i, j) = (gx.floor() as usize, gy.floor() as usize);
+ let (tx, ty) = (gx - i as f64, gy - j as f64);
+ let w1 = self.nx + 1;
+ let v = |ii: usize, jj: usize| self.verts[jj * w1 + ii].0;
+ let (a, b, c, d) = (v(i, j), v(i + 1, j), v(i, j + 1), v(i + 1, j + 1));
+ [
+ (a[0] * (1.0 - tx) + b[0] * tx) * (1.0 - ty) + (c[0] * (1.0 - tx) + d[0] * tx) * ty,
+ (a[1] * (1.0 - tx) + b[1] * tx) * (1.0 - ty) + (c[1] * (1.0 - tx) + d[1] * tx) * ty,
+ ]
+ }
+}
+
+/// Solves the content-preserving warp for `p` over `frame`.
+pub fn solve(p: &WideAngle, frame: Rect) -> WideMesh {
+ let cam = Camera::new(p, frame);
+ let (fw, fh) = (frame.width().max(1) as f64, frame.height().max(1) as f64);
+ let cells = 48.0;
+ let cell = fw.max(fh) / cells;
+ let nx = ((fw / cell).round() as usize).clamp(2, 96);
+ let ny = ((fh / cell).round() as usize).clamp(2, 96);
+ let (cw, ch) = (fw / nx as f64, fh / ny as f64);
+ let w1 = nx + 1;
+ let nv = w1 * (ny + 1);
+ let src: Vec<[f64; 2]> = (0..nv).map(|k| [frame.x0 as f64 + (k % w1) as f64 * cw, frame.y0 as f64 + (k / w1) as f64 * ch]).collect();
+ let curves: Vec<Vec<[f64; 2]>> = p.constraints.iter().map(|c| cam.arc(c.a, c.b, 24)).collect();
+ let mut x: Vec<f64> = src.iter().flat_map(|s| [s[0], s[1]]).collect();
+ // Bilinear weights of a source point in the grid.
+ let weights = |q: [f64; 2]| -> [(usize, f64); 4] {
+ let gx = ((q[0] - frame.x0 as f64) / cw).clamp(0.0, nx as f64 - 1e-9);
+ let gy = ((q[1] - frame.y0 as f64) / ch).clamp(0.0, ny as f64 - 1e-9);
+ let (i, j) = (gx.floor() as usize, gy.floor() as usize);
+ let (tx, ty) = (gx - i as f64, gy - j as f64);
+ let a = j * w1 + i;
+ [(a, (1.0 - tx) * (1.0 - ty)), (a + 1, tx * (1.0 - ty)), (a + w1, (1.0 - tx) * ty), (a + w1 + 1, tx * ty)]
+ };
+ let tris = {
+ let mut t = Vec::new();
+ for j in 0..ny {
+ for i in 0..nx {
+ let a = j * w1 + i;
+ t.push([a, a + 1, a + w1 + 1]);
+ t.push([a, a + w1 + 1, a + w1]);
+ // Both diagonals so the shape term is symmetric.
+ t.push([a, a + 1, a + w1]);
+ t.push([a + 1, a + w1 + 1, a + w1]);
+ }
+ }
+ t
+ };
+ let active: Vec<usize> = (0..curves.len()).filter(|&k| curves[k].len() >= 3).collect();
+ if !active.is_empty() {
+ let mut normals: Vec<[f64; 2]> = active.iter().map(|_| [0.0, 1.0]).collect();
+ for round in 0..4 {
+ let mut ls = SparseLs::new(2 * nv);
+ // Shape: v0 = v1 + u (v2 − v1) + v R90 (v2 − v1), with (u, v) from the source.
+ for t in &tris {
+ for rot in 0..3 {
+ let (i0, i1, i2) = (t[rot], t[(rot + 1) % 3], t[(rot + 2) % 3]);
+ let (p0, p1, p2) = (src[i0], src[i1], src[i2]);
+ let e = [p2[0] - p1[0], p2[1] - p1[1]];
+ let l2 = e[0] * e[0] + e[1] * e[1];
+ let d = [p0[0] - p1[0], p0[1] - p1[1]];
+ let u = (d[0] * e[0] + d[1] * e[1]) / l2;
+ let v = (d[0] * -e[1] + d[1] * e[0]) / l2;
+ // x: v0x − v1x − u (v2x − v1x) + v (v2y − v1y) = 0
+ ls.add(vec![(2 * i0, 1.0), (2 * i1, -1.0 + u), (2 * i2, -u), (2 * i2 + 1, v), (2 * i1 + 1, -v)], 0.0, 1.0);
+ // y: v0y − v1y − u (v2y − v1y) − v (v2x − v1x) = 0
+ ls.add(vec![(2 * i0 + 1, 1.0), (2 * i1 + 1, -1.0 + u), (2 * i2 + 1, -u), (2 * i2, -v), (2 * i1, v)], 0.0, 1.0);
+ }
+ }
+ // Weak anchoring to the source (fixes the global similarity).
+ for (k, s) in src.iter().enumerate() {
+ ls.add(vec![(2 * k, 1.0)], s[0], 0.02);
+ ls.add(vec![(2 * k + 1, 1.0)], s[1], 0.02);
+ }
+ // Lines.
+ for (ci, &k) in active.iter().enumerate() {
+ let c = &curves[k];
+ let n = match p.constraints[k].orientation {
+ Orientation::Horizontal => [0.0, 1.0],
+ Orientation::Vertical => [1.0, 0.0],
+ Orientation::Free => normals[ci],
+ };
+ let w0 = weights(c[0]);
+ for q in &c[1..] {
+ let wq = weights(*q);
+ let mut row: Vec<(usize, f64)> = Vec::with_capacity(16);
+ for &(i, w) in &wq {
+ row.push((2 * i, n[0] * w));
+ row.push((2 * i + 1, n[1] * w));
+ }
+ for &(i, w) in &w0 {
+ row.push((2 * i, -n[0] * w));
+ row.push((2 * i + 1, -n[1] * w));
+ }
+ ls.add(row, 0.0, 10.0);
+ }
+ }
+ x = ls.solve(&x, 400 + 200 * round);
+ // Re-estimate free normals from the current end points.
+ let pos = |q: [f64; 2]| -> [f64; 2] { weights(q).iter().fold([0.0, 0.0], |acc, &(i, w)| [acc[0] + w * x[2 * i], acc[1] + w * x[2 * i + 1]]) };
+ let mut changed = false;
+ for (ci, &k) in active.iter().enumerate() {
+ let c = &curves[k];
+ let (a, b) = (pos(c[0]), pos(c[c.len() - 1]));
+ let d = [b[0] - a[0], b[1] - a[1]];
+ let l = d[0].hypot(d[1]).max(1e-9);
+ let nn = [-d[1] / l, d[0] / l];
+ if (nn[0] - normals[ci][0]).abs() + (nn[1] - normals[ci][1]).abs() > 1e-3 {
+ changed = true;
+ }
+ normals[ci] = nn;
+ }
+ if round == 0 && active.iter().all(|&k| p.constraints[k].orientation != Orientation::Free) {
+ break;
+ }
+ if round > 0 && !changed {
+ break;
+ }
+ }
+ }
+ // Scale about the centre.
+ let s = (p.scale / 100.0).clamp(0.1, 10.0);
+ let c = cam.c;
+ let verts: Vec<([f64; 2], [f64; 2])> = (0..nv).map(|k| ([c[0] + (x[2 * k] - c[0]) * s, c[1] + (x[2 * k + 1] - c[1]) * s], src[k])).collect();
+ let mut mesh = WideMesh { nx, ny, verts, curves, residual: 0.0 };
+ // Straightness residual: distance of curve samples from the chord of their mapped ends.
+ let mut worst = 0.0f64;
+ for (k, cv) in mesh.curves.iter().enumerate() {
+ if cv.len() < 3 {
+ continue;
+ }
+ let pts: Vec<[f64; 2]> = cv.iter().map(|q| mesh.map(frame, *q)).collect();
+ let (a, b) = (pts[0], pts[pts.len() - 1]);
+ let d = [b[0] - a[0], b[1] - a[1]];
+ let l = d[0].hypot(d[1]).max(1e-9);
+ for q in &pts {
+ worst = worst.max(((q[0] - a[0]) * d[1] - (q[1] - a[1]) * d[0]).abs() / l);
+ }
+ let _ = k;
+ }
+ mesh.residual = worst;
+ mesh
+}
+
+/// Applies Adaptive Wide Angle to `src` over `frame` (pixels outside the warped image become
+/// transparent).
+pub fn apply(src: &Surface, frame: Rect, p: &WideAngle, interp: Interp) -> Surface {
+ let mesh = solve(p, frame);
+ let tris = mesh.triangles();
+ crate::warp::warp_triangles(src, frame, &mesh.verts, &tris, interp)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn camera_models_round_trip() {
+ let frame = Rect::new(0, 0, 600, 400);
+ for model in [WideModel::Fisheye, WideModel::Perspective] {
+ let cam = Camera::new(&WideAngle { model, focal_length: 15.0, ..Default::default() }, frame);
+ for (x, y) in [(10.0, 20.0), (300.0, 200.0), (590.0, 350.0)] {
+ let p = cam.pixel(cam.ray(x, y)).unwrap();
+ assert!((p[0] - x).abs() < 1e-6 && (p[1] - y).abs() < 1e-6, "{model:?}");
+ }
+ }
+ let eq = Camera::new(&WideAngle::default(), Rect::new(0, 0, 800, 400));
+ assert_eq!(eq.model, WideModel::FullSpherical);
+ let p = eq.pixel(eq.ray(123.0, 77.0)).unwrap();
+ assert!((p[0] - 123.0).abs() < 1e-6 && (p[1] - 77.0).abs() < 1e-6);
+ // Perspective arcs are straight; fisheye arcs bend.
+ let cam = Camera::new(&WideAngle { model: WideModel::Perspective, ..Default::default() }, frame);
+ let arc = cam.arc([50.0, 50.0], [550.0, 80.0], 10);
+ let mid = arc[5];
+ assert!((mid[1] - 65.0).abs() < 2.0, "{mid:?}");
+ let fish = Camera::new(&WideAngle { model: WideModel::Fisheye, focal_length: 8.0, ..Default::default() }, frame);
+ let arc = fish.arc([50.0, 60.0], [550.0, 60.0], 10);
+ assert!(arc[5][1] < 50.0, "a line near the top bows away from the centre: {:?}", arc[5]);
+ }
+
+ #[test]
+ fn constraints_become_straight_and_level() {
+ let frame = Rect::new(0, 0, 480, 320);
+ let p = WideAngle {
+ model: WideModel::Fisheye,
+ focal_length: 8.0,
+ constraints: vec![Constraint { a: [60.0, 70.0], b: [420.0, 70.0], orientation: Orientation::Horizontal }, Constraint { a: [80.0, 60.0], b: [80.0, 260.0], orientation: Orientation::Free }],
+ ..Default::default()
+ };
+ let cam = Camera::new(&p, frame);
+ let before = {
+ let c = cam.arc([60.0, 70.0], [420.0, 70.0], 24);
+ c.iter().map(|q| (q[1] - 70.0).abs()).fold(0.0, f64::max)
+ };
+ assert!(before > 10.0, "the fisheye curve bows: {before}");
+ let mesh = solve(&p, frame);
+ assert!(mesh.residual < 2.0, "residual {}", mesh.residual);
+ // The horizontal constraint is level.
+ let pts: Vec<[f64; 2]> = mesh.curves[0].iter().map(|q| mesh.map(frame, *q)).collect();
+ let ys: Vec<f64> = pts.iter().map(|q| q[1]).collect();
+ let spread = ys.iter().cloned().fold(f64::MIN, f64::max) - ys.iter().cloned().fold(f64::MAX, f64::min);
+ assert!(spread < 2.0, "{spread}");
+ // Far from the constraints the image barely moves.
+ let c = mesh.map(frame, [300.0, 250.0]);
+ assert!((c[0] - 300.0).abs() < 80.0 && (c[1] - 250.0).abs() < 40.0, "{c:?}");
+ }
+
+ #[test]
+ fn no_constraints_is_identity_and_renders() {
+ use photocraft_color::PixelFormat;
+ let frame = Rect::new(0, 0, 64, 48);
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(frame, &[0.2, 0.4, 0.6, 1.0]);
+ let mesh = solve(&WideAngle::default(), frame);
+ assert!(mesh.verts.iter().all(|(o, s)| (o[0] - s[0]).abs() < 1e-9 && (o[1] - s[1]).abs() < 1e-9));
+ let out = apply(&s, frame, &WideAngle { scale: 80.0, ..Default::default() }, Interp::Bilinear);
+ assert!(out.pixel(32, 24)[3] > 0.99 && out.pixel(1, 1)[3] < 0.01);
+ }
+}
diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs
index 34a4dc758..ed55ea0f6 100644
--- a/crates/automation/tests/agent_tasks.rs
+++ b/crates/automation/tests/agent_tasks.rs
@@ -32,7 +32,12 @@ async fn connect() -> Conn {
}
fn text(r: &CallToolResult) -> String {
- r.content.iter().filter_map(|c| c.as_text()).map(|t| t.text.clone()).collect::<Vec<_>>().join("\n")
+ r.content
+ .iter()
+ .filter_map(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .collect::<Vec<_>>()
+ .join("\n")
}
/// Call a tool and parse its JSON result, failing the test on a tool error.
@@ -57,8 +62,16 @@ async fn inspect(c: &Conn) -> Value {
/// Composite RGBA at (x, y), whatever envelope `command_run` wraps the result in.
async fn pixel(c: &Conn, x: i32, y: i32) -> Vec<f64> {
let v = run(c, "document.pixel", json!({"x": x, "y": y})).await;
- let arr = if v.is_array() { v } else { v.get("result").cloned().unwrap_or(v) };
- arr.as_array().unwrap_or_else(|| panic!("pixel: {arr}")).iter().map(|x| x.as_f64().unwrap()).collect()
+ let arr = if v.is_array() {
+ v
+ } else {
+ v.get("result").cloned().unwrap_or(v)
+ };
+ arr.as_array()
+ .unwrap_or_else(|| panic!("pixel: {arr}"))
+ .iter()
+ .map(|x| x.as_f64().unwrap())
+ .collect()
}
fn top_layer(doc: &Value) -> &Value {
@@ -81,11 +94,15 @@ fn gradient_png(dir: &std::path::Path) -> String {
px.extend_from_slice(&[(x * 4) as u8, (y * 5) as u8, 128]);
}
}
- let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
+ let img =
+ photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
let path = dir.join("gradient.png");
std::fs::File::create(&path)
.unwrap()
- .write_all(&photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap())
+ .write_all(
+ &photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default())
+ .unwrap(),
+ )
.unwrap();
path.to_string_lossy().into_owned()
}
@@ -101,14 +118,32 @@ async fn agent_completes_ten_scripted_tasks() {
let c = connect().await;
// 1. Make a title card: type layer with a drop shadow, exported as PNG.
- tool(&c, "doc_new", json!({"width": 200, "height": 120, "background": "white"})).await;
- run(&c, "type.create", json!({"x": 20, "y": 70, "text": "Hello", "size": 36})).await;
- run(&c, "layer.layerStyle.dropShadow", json!({"distance": 4, "size": 3})).await;
+ tool(
+ &c,
+ "doc_new",
+ json!({"width": 200, "height": 120, "background": "white"}),
+ )
+ .await;
+ run(
+ &c,
+ "type.create",
+ json!({"x": 20, "y": 70, "text": "Hello", "size": 36}),
+ )
+ .await;
+ run(
+ &c,
+ "layer.layerStyle.dropShadow",
+ json!({"distance": 4, "size": 3}),
+ )
+ .await;
let doc = inspect(&c).await;
let t = top_layer(&doc);
assert_eq!(t["kind"], "Type", "task 1: {t}");
assert_eq!(t["text"]["text"], "Hello", "task 1: {t}");
- assert_eq!(t["effects"]["items"][0]["kind"], "Drop Shadow", "task 1: {t}");
+ assert_eq!(
+ t["effects"]["items"][0]["kind"], "Drop Shadow",
+ "task 1: {t}"
+ );
let out = dir.join("card.png");
tool(&c, "doc_export", json!({"path": out.to_string_lossy()})).await;
let card = photocraft_codecs::decode(&std::fs::read(&out).unwrap()).unwrap();
@@ -118,84 +153,179 @@ async fn agent_completes_ten_scripted_tasks() {
// 2. Colour grade a photo non-destructively: Curves brightens the midtones, Vibrance on top.
tool(&c, "doc_open", json!({"path": png})).await;
let before = pixel(&c, 16, 24).await;
- run(&c, "layer.newAdjustmentLayer.curves", json!({"points": [[0, 0], [128, 200], [255, 255]]})).await;
- run(&c, "layer.newAdjustmentLayer.vibrance", json!({"vibrance": 40, "saturation": 0})).await;
+ run(
+ &c,
+ "layer.newAdjustmentLayer.curves",
+ json!({"points": [[0, 0], [128, 200], [255, 255]]}),
+ )
+ .await;
+ run(
+ &c,
+ "layer.newAdjustmentLayer.vibrance",
+ json!({"vibrance": 40, "saturation": 0}),
+ )
+ .await;
let after = pixel(&c, 16, 24).await;
- assert!(after[1] > before[1] + 0.05, "task 2: curves should brighten green {before:?} -> {after:?}");
+ assert!(
+ after[1] > before[1] + 0.05,
+ "task 2: curves should brighten green {before:?} -> {after:?}"
+ );
let doc = inspect(&c).await;
- let kinds: Vec<&str> = doc["layers"].as_array().unwrap().iter().filter_map(|l| l["kind"].as_str()).collect();
+ let kinds: Vec<&str> = doc["layers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|l| l["kind"].as_str())
+ .collect();
assert_eq!(kinds, ["Adjustment", "Adjustment", "Pixel"], "task 2");
// 3. Undo/redo: remove both adjustments, restore one.
run(&c, "edit.undo", json!({})).await;
run(&c, "edit.undo", json!({})).await;
- assert!(close(&pixel(&c, 16, 24).await, &before, 1e-6), "task 3: undo should restore the original");
+ assert!(
+ close(&pixel(&c, 16, 24).await, &before, 1e-6),
+ "task 3: undo should restore the original"
+ );
run(&c, "edit.redo", json!({})).await;
- assert_eq!(inspect(&c).await["layers"].as_array().unwrap().len(), 2, "task 3: redo restores Curves");
+ assert_eq!(
+ inspect(&c).await["layers"].as_array().unwrap().len(),
+ 2,
+ "task 3: redo restores Curves"
+ );
run(&c, "edit.undo", json!({})).await;
// 4. Editable blur: smart object + Gaussian Blur, retune the radius, then hide the filter.
run(&c, "layer.smartObjects.convertToSmartObject", json!({})).await;
run(&c, "filter.blur.gaussianBlur", json!({"radius": 2})).await;
- run(&c, "layer.smartFilter.setParams", json!({"index": 0, "params": {"radius": 6}})).await;
+ run(
+ &c,
+ "layer.smartFilter.setParams",
+ json!({"index": 0, "params": {"radius": 6}}),
+ )
+ .await;
let t = inspect(&c).await;
let sf = &top_layer(&t)["smartFilters"][0];
assert_eq!(sf["command"], "filter.blur.gaussianBlur", "task 4: {t}");
assert_eq!(sf["params"]["radius"].as_f64(), Some(6.0), "task 4: {sf}");
- run(&c, "layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).await;
- assert!(close(&pixel(&c, 16, 24).await, &before, 1.0 / 255.0), "task 4: hiding the filter restores the pixels");
+ run(
+ &c,
+ "layer.smartFilter.setVisible",
+ json!({"index": 0, "visible": false}),
+ )
+ .await;
+ assert!(
+ close(&pixel(&c, 16, 24).await, &before, 1.0 / 255.0),
+ "task 4: hiding the filter restores the pixels"
+ );
// 5. Selection → layer mask: an elliptical reveal on a red layer.
run(&c, "layer.new.layer", json!({"name": "Red"})).await;
run(&c, "select.all", json!({})).await;
run(&c, "edit.fill", json!({"color": "#ff0000"})).await;
- run(&c, "select.rect", json!({"x": 16, "y": 12, "width": 32, "height": 24, "ellipse": true})).await;
+ run(
+ &c,
+ "select.rect",
+ json!({"x": 16, "y": 12, "width": 32, "height": 24, "ellipse": true}),
+ )
+ .await;
run(&c, "layer.layerMask.revealSelection", json!({})).await;
assert_eq!(top_layer(&inspect(&c).await)["hasMask"], true, "task 5");
let inside = pixel(&c, 32, 24).await;
let outside = pixel(&c, 1, 1).await;
- assert!(inside[0] > 0.99 && inside[1] < 0.01, "task 5: centre is red {inside:?}");
- assert!(outside[0] < 0.1, "task 5: corner shows the photo {outside:?}");
+ assert!(
+ inside[0] > 0.99 && inside[1] < 0.01,
+ "task 5: centre is red {inside:?}"
+ );
+ assert!(
+ outside[0] < 0.1,
+ "task 5: corner shows the photo {outside:?}"
+ );
run(&c, "select.deselect", json!({})).await;
// 6. Save a selection to a channel and load it back.
- run(&c, "select.rect", json!({"x": 4, "y": 6, "width": 20, "height": 10})).await;
+ run(
+ &c,
+ "select.rect",
+ json!({"x": 4, "y": 6, "width": 20, "height": 10}),
+ )
+ .await;
run(&c, "select.saveSelection", json!({"name": "Keep"})).await;
run(&c, "select.deselect", json!({})).await;
assert_eq!(inspect(&c).await["hasSelection"], false, "task 6");
run(&c, "select.loadSelection", json!({"channel": "Keep"})).await;
let doc = inspect(&c).await;
- assert_eq!(doc["selectionBounds"], json!([4, 6, 20, 10]), "task 6: {}", doc["selectionBounds"]);
+ assert_eq!(
+ doc["selectionBounds"],
+ json!([4, 6, 20, 10]),
+ "task 6: {}",
+ doc["selectionBounds"]
+ );
assert_eq!(doc["channels"]["alpha"][0]["name"], "Keep", "task 6");
run(&c, "select.deselect", json!({})).await;
tool(&c, "doc_close", json!({})).await;
// 7. Lay out three swatches and align their left edges.
- tool(&c, "doc_new", json!({"width": 120, "height": 90, "background": "white"})).await;
+ tool(
+ &c,
+ "doc_new",
+ json!({"width": 120, "height": 90, "background": "white"}),
+ )
+ .await;
for (i, x) in [10, 40, 70].into_iter().enumerate() {
run(&c, "layer.new.layer", json!({"name": format!("S{i}")})).await;
- run(&c, "select.rect", json!({"x": x, "y": 10 + 25 * i as i32, "width": 20, "height": 15})).await;
+ run(
+ &c,
+ "select.rect",
+ json!({"x": x, "y": 10 + 25 * i as i32, "width": 20, "height": 15}),
+ )
+ .await;
run(&c, "edit.fill", json!({"color": "#3366cc"})).await;
}
run(&c, "select.deselect", json!({})).await;
run(&c, "select.allLayers", json!({})).await;
run(&c, "layer.align.leftEdges", json!({})).await;
let doc = inspect(&c).await;
- let xs: Vec<i64> = doc["layers"].as_array().unwrap().iter().filter(|l| l["name"].as_str().is_some_and(|n| n.starts_with('S'))).map(|l| l["bounds"][0].as_i64().unwrap()).collect();
+ let xs: Vec<i64> = doc["layers"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|l| l["name"].as_str().is_some_and(|n| n.starts_with('S')))
+ .map(|l| l["bounds"][0].as_i64().unwrap())
+ .collect();
assert_eq!(xs, [10, 10, 10], "task 7: {}", doc["layers"]);
// 8. Export every layer to its own file.
let layers_dir = dir.join("layers");
std::fs::create_dir_all(&layers_dir).unwrap();
- run(&c, "file.export.layersToFiles", json!({"dir": layers_dir.to_string_lossy(), "format": "png", "prefix": "swatch"})).await;
- let n = std::fs::read_dir(&layers_dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some_and(|x| x == "png"))).count();
+ run(
+ &c,
+ "file.export.layersToFiles",
+ json!({"dir": layers_dir.to_string_lossy(), "format": "png", "prefix": "swatch"}),
+ )
+ .await;
+ let n = std::fs::read_dir(&layers_dir)
+ .unwrap()
+ .filter(|e| {
+ e.as_ref()
+ .is_ok_and(|e| e.path().extension().is_some_and(|x| x == "png"))
+ })
+ .count();
assert_eq!(n, 4, "task 8: three swatches plus the background");
// 9. Resize, then crop to a square.
run(&c, "image.imageSize", json!({"width": 60, "height": 45})).await;
- run(&c, "image.crop", json!({"x": 5, "y": 0, "width": 45, "height": 45})).await;
+ run(
+ &c,
+ "image.crop",
+ json!({"x": 5, "y": 0, "width": 45, "height": 45}),
+ )
+ .await;
let doc = inspect(&c).await;
- assert_eq!((doc["width"].as_u64(), doc["height"].as_u64()), (Some(45), Some(45)), "task 9");
+ assert_eq!(
+ (doc["width"].as_u64(), doc["height"].as_u64()),
+ (Some(45), Some(45)),
+ "task 9"
+ );
// 10. Prepare for print: convert to CMYK and save natively, then reopen.
run(&c, "image.mode.cmyk", json!({"intent": "perceptual"})).await;
@@ -205,7 +335,11 @@ async fn agent_completes_ten_scripted_tasks() {
tool(&c, "doc_close", json!({})).await;
tool(&c, "doc_open", json!({"path": saved.to_string_lossy()})).await;
let doc = inspect(&c).await;
- assert_eq!((doc["mode"].as_str(), doc["width"].as_u64()), (Some("Cmyk"), Some(45)), "task 10");
+ assert_eq!(
+ (doc["mode"].as_str(), doc["width"].as_u64()),
+ (Some("Cmyk"), Some(45)),
+ "task 10"
+ );
assert_eq!(doc["layers"].as_array().unwrap().len(), 4, "task 10");
c.cancel().await.unwrap();
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index 337a6d1c0..d1c08e051 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -18,6 +18,7 @@ mod fidelity;
mod format;
mod image;
mod options;
+pub mod web;
pub use crate::error::CodecError;
pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with};
diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rs
new file mode 100644
index 000000000..25a9ae00f
--- /dev/null
+++ b/crates/codecs/src/web.rs
@@ -0,0 +1,333 @@
+//! Web-optimised writers for Save for Web: indexed GIF (our own LZW encoder, GIF89a spec),
+//! WBMP (WAP Wireless Bitmap, type 0) and baseline/progressive JPEG from 8-bit RGB.
+//!
+//! Indexed PNG is [`crate::encode_png_indexed`]. Every writer here has a matching reader (GIF
+//! through the regular decoder, WBMP through [`decode_wbmp`]), keeping the crate symmetric.
+
+use std::collections::HashMap;
+
+use crate::error::CodecError;
+use crate::format::Format;
+
+fn gif_err(msg: impl Into<String>) -> CodecError {
+ CodecError::InvalidImage(msg.into())
+}
+
+/// Packs variable-length LZW codes LSB-first into GIF data sub-blocks.
+struct BitSink {
+ bytes: Vec<u8>,
+ acc: u32,
+ nbits: u32,
+}
+
+impl BitSink {
+ fn put(&mut self, code: u16, size: u32) {
+ self.acc |= u32::from(code) << self.nbits;
+ self.nbits += size;
+ while self.nbits >= 8 {
+ self.bytes.push(self.acc as u8);
+ self.acc >>= 8;
+ self.nbits -= 8;
+ }
+ }
+ fn finish(mut self) -> Vec<u8> {
+ if self.nbits > 0 {
+ self.bytes.push(self.acc as u8);
+ }
+ self.bytes
+ }
+}
+
+/// GIF variable-code-length LZW compression of `indices` (each < 2^`min_code_size`).
+pub fn lzw_encode(indices: &[u8], min_code_size: u8) -> Vec<u8> {
+ let min = u32::from(min_code_size.clamp(2, 8));
+ let clear = 1u16 << min;
+ let eoi = clear + 1;
+ let mut size = min + 1;
+ let mut next = eoi + 1;
+ let mut dict: HashMap<u32, u16> = HashMap::with_capacity(4096);
+ let mut out = BitSink { bytes: Vec::with_capacity(indices.len() / 2 + 16), acc: 0, nbits: 0 };
+ out.put(clear, size);
+ let Some((&first, rest)) = indices.split_first() else {
+ out.put(eoi, size);
+ return out.finish();
+ };
+ let mut prefix = u16::from(first);
+ for &k in rest {
+ let key = u32::from(prefix) << 8 | u32::from(k);
+ if let Some(&c) = dict.get(&key) {
+ prefix = c;
+ continue;
+ }
+ out.put(prefix, size);
+ // The decoder adds its entries one code late, so widen once the next free code no
+ // longer fits (before assigning it), exactly like the classic compress-based encoders.
+ if u32::from(next) >= 1 << size && size < 12 {
+ size += 1;
+ }
+ if next < 4096 {
+ dict.insert(key, next);
+ next += 1;
+ } else {
+ out.put(clear, size);
+ dict.clear();
+ size = min + 1;
+ next = eoi + 1;
+ }
+ prefix = u16::from(k);
+ }
+ out.put(prefix, size);
+ if u32::from(next) >= 1 << size && size < 12 {
+ size += 1;
+ }
+ out.put(eoi, size);
+ out.finish()
+}
+
+/// Rows in GIF interlaced order (passes every 8th from 0, every 8th from 4, every 4th from 2,
+/// every 2nd from 1).
+fn interlaced_rows(h: usize) -> Vec<usize> {
+ let mut v = Vec::with_capacity(h);
+ for (start, step) in [(0, 8), (4, 8), (2, 4), (1, 2)] {
+ v.extend((start..h).step_by(step));
+ }
+ v
+}
+
+/// An indexed GIF89a: `palette` (1..=256 entries), one index per pixel, optional transparent
+/// index (Graphic Control Extension) and interlacing.
+pub fn encode_gif_indexed(width: u32, height: u32, indices: &[u8], palette: &[[u8; 3]], transparent: Option<u8>, interlaced: bool) -> Result<Vec<u8>, CodecError> {
+ let (w, h) = (width as usize, height as usize);
+ if width == 0 || height == 0 || width > 65535 || height > 65535 || indices.len() != w * h {
+ return Err(gif_err("GIF size must be 1..=65535 and match the index data"));
+ }
+ if palette.is_empty() || palette.len() > 256 || indices.iter().any(|&i| usize::from(i) >= palette.len()) {
+ return Err(gif_err("palette must have 1..=256 entries covering every index"));
+ }
+ // Colour table size: 2^(bits) entries, bits ≥ 1.
+ let bits = (1..=8u8).find(|b| (1usize << b) >= palette.len()).unwrap_or(8);
+ let mut out = b"GIF89a".to_vec();
+ out.extend((width as u16).to_le_bytes());
+ out.extend((height as u16).to_le_bytes());
+ out.push(0x80 | ((bits - 1) << 4) | (bits - 1));
+ out.push(transparent.unwrap_or(0));
+ out.push(0);
+ for i in 0..(1usize << bits) {
+ out.extend(palette.get(i).copied().unwrap_or([0, 0, 0]));
+ }
+ if let Some(t) = transparent {
+ out.extend([0x21, 0xF9, 0x04, 0x01, 0, 0, t, 0]);
+ }
+ out.push(0x2C);
+ out.extend([0, 0, 0, 0]);
+ out.extend((width as u16).to_le_bytes());
+ out.extend((height as u16).to_le_bytes());
+ out.push(if interlaced { 0x40 } else { 0 });
+ let min = bits.max(2);
+ out.push(min);
+ let data = if interlaced {
+ let mut v = Vec::with_capacity(indices.len());
+ for y in interlaced_rows(h) {
+ v.extend_from_slice(&indices[y * w..(y + 1) * w]);
+ }
+ lzw_encode(&v, min)
+ } else {
+ lzw_encode(indices, min)
+ };
+ for chunk in data.chunks(255) {
+ out.push(chunk.len() as u8);
+ out.extend_from_slice(chunk);
+ }
+ out.push(0);
+ out.push(0x3B);
+ Ok(out)
+}
+
+fn put_multibyte(out: &mut Vec<u8>, v: u32) {
+ let mut groups = vec![(v & 0x7f) as u8];
+ let mut v = v >> 7;
+ while v > 0 {
+ groups.push((v & 0x7f) as u8 | 0x80);
+ v >>= 7;
+ }
+ out.extend(groups.iter().rev());
+}
+
+/// WBMP type 0 (1 bit per pixel, rows padded to bytes, 1 = white). `white[i]` per pixel.
+pub fn encode_wbmp(width: u32, height: u32, white: &[bool]) -> Result<Vec<u8>, CodecError> {
+ let (w, h) = (width as usize, height as usize);
+ if width == 0 || height == 0 || white.len() != w * h {
+ return Err(CodecError::InvalidImage("WBMP size must match the pixel data".into()));
+ }
+ let mut out = vec![0u8, 0u8];
+ put_multibyte(&mut out, width);
+ put_multibyte(&mut out, height);
+ let stride = w.div_ceil(8);
+ for y in 0..h {
+ let mut row = vec![0u8; stride];
+ for x in 0..w {
+ if white[y * w + x] {
+ row[x / 8] |= 0x80 >> (x % 8);
+ }
+ }
+ out.extend(row);
+ }
+ Ok(out)
+}
+
+/// Reads a WBMP type 0 image: (width, height, white per pixel).
+pub fn decode_wbmp(bytes: &[u8]) -> Result<(u32, u32, Vec<bool>), CodecError> {
+ let bad = || CodecError::InvalidImage("not a type 0 WBMP".into());
+ let mut i = 0usize;
+ let mut next = || -> Result<u8, CodecError> {
+ let b = *bytes.get(i).ok_or_else(bad)?;
+ i += 1;
+ Ok(b)
+ };
+ if next()? != 0 || next()? & 0x9f != 0 {
+ return Err(bad());
+ }
+ let mut mb = || -> Result<u32, CodecError> {
+ let mut v: u32 = 0;
+ for _ in 0..5 {
+ let b = next()?;
+ v = v.checked_mul(128).ok_or_else(bad)? | u32::from(b & 0x7f);
+ if b & 0x80 == 0 {
+ return Ok(v);
+ }
+ }
+ Err(bad())
+ };
+ let (w, h) = (mb()?, mb()?);
+ if w == 0 || h == 0 || u64::from(w) * u64::from(h) > 1 << 28 {
+ return Err(bad());
+ }
+ let stride = (w as usize).div_ceil(8);
+ let data = bytes.get(i..i + stride * h as usize).ok_or_else(bad)?;
+ let mut px = Vec::with_capacity(w as usize * h as usize);
+ for y in 0..h as usize {
+ for x in 0..w as usize {
+ px.push(data[y * stride + x / 8] & (0x80 >> (x % 8)) != 0);
+ }
+ }
+ Ok((w, h, px))
+}
+
+/// JPEG from 8-bit RGB (`rgb.len() == 3·w·h`): quality 1..=100, optional progressive scans and
+/// optimised Huffman tables (Save for Web's "Optimized"), optional ICC profile, density and XMP.
+#[allow(clippy::too_many_arguments)]
+pub fn encode_jpeg_rgb8(width: u32, height: u32, rgb: &[u8], quality: u8, progressive: bool, optimized: bool, icc: Option<&[u8]>, dpi: Option<f32>, xmp: Option<&str>) -> Result<Vec<u8>, CodecError> {
+ let e = |e: jpeg_encoder::EncodingError| CodecError::encode(Format::Jpeg, e);
+ let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else {
+ return Err(CodecError::encode(Format::Jpeg, "JPEG dimensions are limited to 65535"));
+ };
+ if rgb.len() != width as usize * height as usize * 3 {
+ return Err(CodecError::InvalidImage("RGB data does not match the size".into()));
+ }
+ let mut out = Vec::new();
+ let mut enc = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
+ enc.set_progressive(progressive);
+ enc.set_optimized_huffman_tables(optimized || progressive);
+ enc.set_sampling_factor(if quality >= 90 { jpeg_encoder::SamplingFactor::R_4_4_4 } else { jpeg_encoder::SamplingFactor::R_4_2_0 });
+ if let Some(d) = dpi.filter(|d| *d >= 1.0) {
+ let v = d.round().min(65535.0) as u16;
+ enc.set_density(jpeg_encoder::Density::Inch { x: v, y: v });
+ }
+ if let Some(x) = xmp {
+ let mut seg = b"http://ns.adobe.com/xap/1.0/\0".to_vec();
+ seg.extend_from_slice(x.as_bytes());
+ enc.add_app_segment(1, &seg).map_err(e)?;
+ }
+ if let Some(icc) = icc {
+ enc.add_icc_profile(icc).map_err(e)?;
+ }
+ enc.encode(rgb, w16, h16, jpeg_encoder::ColorType::Rgb).map_err(e)?;
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn decode_rgba(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
+ let img = crate::decode(bytes).unwrap();
+ let (w, h) = img.dimensions();
+ (w, h, img.convert(crate::ChannelLayout::Rgba, crate::SampleType::U8).data().to_vec())
+ }
+
+ fn pattern(w: usize, h: usize, n: usize) -> Vec<u8> {
+ (0..w * h).map(|i| (((i % w) * 7 + (i / w) * 13 + (i * i) % 5) % n) as u8).collect()
+ }
+
+ #[test]
+ fn gif_roundtrips_through_the_decoder() {
+ let pal: Vec<[u8; 3]> = (0..200).map(|i| [i as u8, (255 - i) as u8, (i * 3 % 256) as u8]).collect();
+ for (w, h, interlaced) in [(1, 1, false), (37, 23, false), (37, 23, true), (300, 200, false)] {
+ let idx = pattern(w, h, pal.len());
+ let bytes = encode_gif_indexed(w as u32, h as u32, &idx, &pal, None, interlaced).unwrap();
+ let (dw, dh, px) = decode_rgba(&bytes);
+ assert_eq!((dw, dh), (w as u32, h as u32));
+ for (i, k) in idx.iter().enumerate() {
+ assert_eq!(&px[i * 4..i * 4 + 3], &pal[*k as usize], "pixel {i} of {w}x{h} interlaced={interlaced}");
+ }
+ }
+ }
+
+ #[test]
+ fn gif_small_palettes_and_transparency() {
+ let pal = [[255, 255, 255], [0, 0, 0], [255, 0, 0]];
+ let idx: Vec<u8> = (0..64 * 64).map(|i| (i % 3) as u8).collect();
+ let bytes = encode_gif_indexed(64, 64, &idx, &pal, Some(2), false).unwrap();
+ let (_, _, px) = decode_rgba(&bytes);
+ assert_eq!(px[3], 255);
+ assert_eq!(px[2 * 4 + 3], 0, "index 2 is transparent");
+ // Two-colour image: minimum code size 2.
+ let bw: Vec<u8> = (0..1000).map(|i| u8::from(i % 7 == 0)).collect();
+ let bytes = encode_gif_indexed(100, 10, &bw, &pal[..2], None, false).unwrap();
+ let (_, _, px) = decode_rgba(&bytes);
+ assert_eq!(px[0], 0, "index 1 = black at x 0");
+ assert!(encode_gif_indexed(2, 2, &[0, 1, 2, 3], &pal, None, false).is_err());
+ }
+
+ #[test]
+ fn gif_long_runs_hit_the_dictionary_limit() {
+ // Noise forces many codes and dictionary resets; flat areas make long strings.
+ let mut seed = 12345u32;
+ let idx: Vec<u8> = (0..512 * 512)
+ .map(|i| {
+ seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345);
+ if (i / 512) % 64 < 32 { (seed >> 16) as u8 } else { 7 }
+ })
+ .collect();
+ let pal: Vec<[u8; 3]> = (0..256).map(|i| [i as u8, i as u8, 255 - i as u8]).collect();
+ let bytes = encode_gif_indexed(512, 512, &idx, &pal, None, false).unwrap();
+ let (_, _, px) = decode_rgba(&bytes);
+ for (i, k) in idx.iter().enumerate().step_by(97) {
+ assert_eq!(px[i * 4], *k);
+ }
+ }
+
+ #[test]
+ fn wbmp_roundtrips() {
+ let px: Vec<bool> = (0..13 * 5).map(|i| i % 3 == 0).collect();
+ let bytes = encode_wbmp(13, 5, &px).unwrap();
+ assert_eq!(&bytes[..4], &[0, 0, 13, 5]);
+ assert_eq!(decode_wbmp(&bytes).unwrap(), (13, 5, px));
+ let big = encode_wbmp(300, 1, &[true; 300]).unwrap();
+ assert_eq!(&big[2..4], &[0x82, 0x2c], "300 as a multi-byte integer");
+ assert!(decode_wbmp(&big[..10]).is_err());
+ assert!(decode_wbmp(&[1, 0, 1, 1, 0]).is_err());
+ }
+
+ #[test]
+ fn progressive_jpeg_decodes() {
+ let rgb: Vec<u8> = (0..64 * 48 * 3).map(|i| (i % 251) as u8).collect();
+ let base = encode_jpeg_rgb8(64, 48, &rgb, 80, false, false, None, Some(72.0), Some("<x:xmpmeta/>")).unwrap();
+ let prog = encode_jpeg_rgb8(64, 48, &rgb, 80, true, true, None, None, None).unwrap();
+ assert_ne!(base, prog);
+ assert_eq!(crate::decode(&base).unwrap().meta.xmp.as_deref(), Some("<x:xmpmeta/>"));
+ // SOF2 marks a progressive frame.
+ assert!(prog.windows(2).any(|w| w == [0xFF, 0xC2]));
+ assert_eq!(crate::decode(&prog).unwrap().dimensions(), (64, 48));
+ }
+}
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs
index c691ddaf9..8eefd5dcf 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -19,7 +19,7 @@
use photocraft_color::blend::BlendMode;
use photocraft_doc::{
- Bevel, BevelStyle, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Layer, Shadow,
+ Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Layer, Shadow,
StrokePosition,
};
use photocraft_doc::Pattern;
@@ -318,48 +318,12 @@ fn local_coverage(s: &Map) -> Map {
/// Alpha above which a pixel belongs to the layer's shape (half an 8-bit step).
const INSIDE_EPS: f32 = 0.5 / 255.0;
-/// Photoshop's effect "size" → Gaussian sigma (fitted on the corpus).
-fn sigma_for(size: f32) -> f32 {
- // Least-squares fit of a drop shadow against Photoshop's composite
- // (ag-psd effects fixture): sigma = 0.4 × size, offsets rounded to pixels.
- size * 0.4
-}
-
-/// Separable Gaussian blur for an effect of `size` pixels.
+/// The soft falloff of an effect of `size` pixels: two box passes of width `size` (a tent),
+/// as Photoshop does. Fitted on psd-tools layer_effects.psd against the earlier Gaussian
+/// (sigma = 0.4 × size): drop shadow coverage error 0.0064 → 0.0038, satin 0.014 → 0.002.
fn blur(m: &mut Map, size: f32) {
- let sigma = sigma_for(size);
- if sigma < 0.2 {
- return;
- }
- let r = (sigma * 3.0).ceil() as i64;
- let kernel: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
- let sum: f32 = kernel.iter().sum();
- let kernel: Vec<f32> = kernel.iter().map(|k| k / sum).collect();
- let (w, h) = (m.w as i64, m.h as i64);
- let mut tmp = vec![0.0f32; m.v.len()];
- for y in 0..h {
- for x in 0..w {
- let mut acc = 0.0;
- for (k, kv) in kernel.iter().enumerate() {
- let xx = x + k as i64 - r;
- if xx >= 0 && xx < w {
- acc += m.v[(y * w + xx) as usize] * kv;
- }
- }
- tmp[(y * w + x) as usize] = acc;
- }
- }
- for y in 0..h {
- for x in 0..w {
- let mut acc = 0.0;
- for (k, kv) in kernel.iter().enumerate() {
- let yy = y + k as i64 - r;
- if yy >= 0 && yy < h {
- acc += tmp[(yy * w + x) as usize] * kv;
- }
- }
- m.v[(y * w + x) as usize] = acc;
- }
+ if size.is_finite() {
+ tent(m, size);
}
}
@@ -383,6 +347,37 @@ fn contour_lut(c: &Contour) -> Option<Vec<f32>> {
}
}
+/// Interpolated lookup in a 0..=1 table (as the GPU's `lut()`).
+fn lut_at(l: &[f32], v: f32) -> f32 {
+ let x = v.clamp(0.0, 1.0) * (l.len() - 1) as f32;
+ let i = x.floor() as usize;
+ let j = (i + 1).min(l.len() - 1);
+ l[i] + (l[j] - l[i]) * (x - i as f32)
+}
+
+/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's
+/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred
+/// edge's 0.5 to full strength). `None` = identity.
+pub fn glow_lut(g: &Glow) -> Option<Vec<f32>> {
+ let base = contour_lut(&g.contour);
+ let range = if g.range.is_finite() { g.range.clamp(0.01, 1.0) } else { 1.0 };
+ if range >= 0.999 {
+ return base;
+ }
+ let n = 4096;
+ Some((0..n).map(|k| {
+ let v = (k as f32 / (n - 1) as f32 / range).min(1.0);
+ base.as_ref().map_or(v, |l| lut_at(l, v))
+ }).collect())
+}
+
+fn apply_lut(m: Map, l: Option<Vec<f32>>) -> Map {
+ match l {
+ None => m,
+ Some(l) => m.map(|v| lut_at(&l, v)),
+ }
+}
+
fn apply_contour(m: Map, c: &Contour) -> Map {
match contour_lut(c) {
None => m,
@@ -531,7 +526,7 @@ fn glow_map(shape: &Map, g: &Glow, inner: bool) -> Map {
m
}
};
- m = apply_contour(m, &g.contour);
+ m = apply_lut(m, glow_lut(g));
if inner {
for (v, a) in m.v.iter_mut().zip(&shape.v) {
*v *= a;
@@ -581,48 +576,196 @@ fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, anchor:
}
}
-/// Bevel highlight and shadow maps for the inner (or outer) bevel.
-fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight) -> (Map, Map, bool) {
- let outer = b.style == BevelStyle::OuterBevel;
+/// Normalised weights of a centred box of (fractional) width `w`: tap `i` gets the overlap of
+/// `[i - 0.5, i + 0.5]` with `[-w/2, w/2]`.
+fn box_weights(w: f32) -> Vec<f32> {
+ let w = w.max(1.0);
+ let half = w / 2.0;
+ let r = (half - 0.5).ceil().max(0.0) as i64;
+ let v: Vec<f32> = (-r..=r).map(|i| ((i as f32 + 0.5).min(half) - (i as f32 - 0.5).max(-half)).max(0.0)).collect();
+ let sum: f32 = v.iter().sum();
+ v.iter().map(|x| x / sum).collect()
+}
+
+/// The 1D kernel of two box passes of width `w` (a tent of half-width ≈ `w`): `(radius, weights)`.
+/// Photoshop's bevel height maps are this blur of the shape (fitted on the corpus: a smooth
+/// inner bevel of size 5 matches within 0.7 % mean, size 41 within 2.6 %).
+pub fn tent_kernel(w: f32) -> (i32, Vec<f32>) {
+ let b = box_weights(w);
+ let n = b.len() * 2 - 1;
+ let mut t = vec![0.0f32; n];
+ for (i, x) in b.iter().enumerate() {
+ for (j, y) in b.iter().enumerate() {
+ t[i + j] += x * y;
+ }
+ }
+ ((n as i32 - 1) / 2, t)
+}
+
+/// Separable convolution with a symmetric 1D kernel (outside reads 0).
+fn convolve(m: &mut Map, r: i64, kernel: &[f32]) {
+ let (w, h) = (m.w as i64, m.h as i64);
+ let mut tmp = vec![0.0f32; m.v.len()];
+ for y in 0..h {
+ for x in 0..w {
+ let mut acc = 0.0;
+ for (k, kv) in kernel.iter().enumerate() {
+ let xx = x + k as i64 - r;
+ if xx >= 0 && xx < w {
+ acc += m.v[(y * w + xx) as usize] * kv;
+ }
+ }
+ tmp[(y * w + x) as usize] = acc;
+ }
+ }
+ for y in 0..h {
+ for x in 0..w {
+ let mut acc = 0.0;
+ for (k, kv) in kernel.iter().enumerate() {
+ let yy = y + k as i64 - r;
+ if yy >= 0 && yy < h {
+ acc += tmp[(yy * w + x) as usize] * kv;
+ }
+ }
+ m.v[(y * w + x) as usize] = acc;
+ }
+ }
+}
+
+fn tent(m: &mut Map, w: f32) {
+ let (r, k) = tent_kernel(w);
+ if r > 0 {
+ convolve(m, i64::from(r), &k);
+ }
+}
+
+/// Where a bevel's maps paint: inside the shape (with the layer), outside it (onto the
+/// backdrop), or both (emboss styles: maps 0–1 inside, 2–3 outside).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BevelPaint {
+ Inner,
+ Outer,
+ Both,
+}
+
+/// Bevel geometry shared by the CPU maps and the GPU programs.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct BevelGeom {
+ pub paint: BevelPaint,
+ /// Box width of the smooth height blur (size; half the size for emboss styles).
+ pub width: f32,
+ /// Height-map gradient scale: depth × width (smooth) or depth × size (chisel), signed by
+ /// direction.
+ pub depth: f32,
+ /// Pillow emboss: the outside slopes face the other way.
+ pub pillow: bool,
+ /// Chisel Soft: extra tent width over the chiselled height map.
+ pub chisel_soft: f32,
+}
+
+pub fn bevel_geom(b: &Bevel) -> BevelGeom {
let size = b.size.max(1.0);
- let (din, dout) = (dist_inside(shape), dist_outside(shape));
- let mut hmap = Map::new(shape.w, shape.h, 0.0);
- for i in 0..hmap.v.len() {
- hmap.v[i] = match b.style {
- BevelStyle::OuterBevel => 1.0 - (dout[i] / size).clamp(0.0, 1.0),
- BevelStyle::Emboss | BevelStyle::PillowEmboss => {
- if din[i] > 0.0 { 0.5 + 0.5 * (din[i] / (size / 2.0)).clamp(0.0, 1.0) } else { 0.5 - 0.5 * (dout[i] / (size / 2.0)).clamp(0.0, 1.0) }
+ let emboss = matches!(b.style, BevelStyle::Emboss | BevelStyle::PillowEmboss);
+ let paint = match b.style {
+ BevelStyle::OuterBevel => BevelPaint::Outer,
+ BevelStyle::Emboss | BevelStyle::PillowEmboss => BevelPaint::Both,
+ BevelStyle::InnerBevel | BevelStyle::StrokeEmboss => BevelPaint::Inner,
+ };
+ let width = if emboss { size / 2.0 } else { size };
+ let smooth = b.technique == BevelTechnique::Smooth;
+ let sign = if b.up { 1.0 } else { -1.0 };
+ BevelGeom {
+ paint,
+ width,
+ depth: b.depth * if smooth { width } else { size } * sign,
+ pillow: b.style == BevelStyle::PillowEmboss,
+ chisel_soft: if b.technique == BevelTechnique::ChiselSoft { (size / 4.0).max(1.0) } else { 0.0 },
+ }
+}
+
+/// Bevel height map in `0..=1`. Smooth: the shape blurred by two box passes of the bevel
+/// width. Chisel: linear ramps of the exact distance to the edge (size wide; emboss styles
+/// straddle the edge), slightly blurred for Chisel Soft. Soften blurs the result.
+fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom) -> Map {
+ let size = b.size.max(1.0);
+ let mut h = if b.technique == BevelTechnique::Smooth {
+ let mut h = shape.clone();
+ tent(&mut h, g.width);
+ h
+ } else {
+ let (din, dout) = (dist_inside(shape), dist_outside(shape));
+ let mut h = Map::new(shape.w, shape.h, 0.0);
+ for i in 0..h.v.len() {
+ h.v[i] = bevel_chisel_h(g.paint, size, din[i], dout[i]);
+ }
+ if g.chisel_soft > 0.0 {
+ tent(&mut h, g.chisel_soft);
+ }
+ h
+ };
+ if b.soften >= 1.0 {
+ tent(&mut h, b.soften);
+ }
+ h
+}
+
+/// Chiselled height from the inside / outside distances (keep in sync with `fs_mbevelh`).
+pub fn bevel_chisel_h(paint: BevelPaint, size: f32, din: f32, dout: f32) -> f32 {
+ match paint {
+ BevelPaint::Outer => 1.0 - (dout / size).clamp(0.0, 1.0),
+ BevelPaint::Both => {
+ if din > 0.0 {
+ 0.5 + 0.5 * (din / (size / 2.0)).clamp(0.0, 1.0)
+ } else {
+ 0.5 - 0.5 * (dout / (size / 2.0)).clamp(0.0, 1.0)
}
- _ => (din[i] / size).clamp(0.0, 1.0),
- };
+ }
+ BevelPaint::Inner => (din / size).clamp(0.0, 1.0),
}
- // Smooth technique: round the profile.
- hmap = hmap.map(|v| (v * std::f32::consts::FRAC_PI_2).sin());
- blur(&mut hmap, b.soften.max(1.0));
+}
+
+/// Bevel highlight and shadow maps: `[hi, sh]` (inner or outer) or `[hi, sh, hi_out, sh_out]`
+/// (emboss styles).
+fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight) -> (Vec<Map>, BevelPaint) {
+ let g = bevel_geom(b);
+ let hmap = bevel_height(shape, b, &g);
let (angle, altitude) = if b.use_global_light { (light.angle, light.altitude) } else { (b.angle, b.altitude) };
let (sa, ca) = angle.to_radians().sin_cos();
let (se, ce) = altitude.to_radians().sin_cos();
let light_v = [ca * ce, -sa * ce, se];
- let depth = b.depth * size * if b.up { 1.0 } else { -1.0 };
- let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0));
- for y in 0..shape.h as i64 {
- for x in 0..shape.w as i64 {
- let i = y as usize * shape.w + x as usize;
- let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth;
- let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth;
- let n = [-gx, -gy, 1.0];
- let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
- let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
- let region = if outer { (1.0 - shape.v[i]) * f32::from(hmap.v[i] > 0.0) } else { shape.v[i] };
- let k = shade - se;
- if k > 0.0 {
- hi.v[i] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
- } else {
- sh.v[i] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region;
+ let shade_into = |depth: f32, outer: bool| -> (Map, Map) {
+ let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0));
+ for y in 0..shape.h as i64 {
+ for x in 0..shape.w as i64 {
+ let i = y as usize * shape.w + x as usize;
+ let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth;
+ let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth;
+ let n = [-gx, -gy, 1.0];
+ let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
+ let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
+ let region = if outer { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && hmap.v[i] > 0.0) } else { shape.v[i] };
+ let k = shade - se;
+ if k > 0.0 {
+ hi.v[i] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
+ } else {
+ sh.v[i] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region;
+ }
}
}
- }
- (apply_contour(hi, &b.gloss_contour), apply_contour(sh, &b.gloss_contour), outer)
+ (apply_contour(hi, &b.gloss_contour), apply_contour(sh, &b.gloss_contour))
+ };
+ let maps = match g.paint {
+ BevelPaint::Inner | BevelPaint::Outer => {
+ let (hi, sh) = shade_into(g.depth, g.paint == BevelPaint::Outer);
+ vec![hi, sh]
+ }
+ BevelPaint::Both => {
+ let (hi, sh) = shade_into(g.depth, false);
+ let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, true);
+ vec![hi, sh, ho, so]
+ }
+ };
+ (maps, g.paint)
}
/// Effect maps derived from a layer's shape (its alpha), computed once over the layer's whole
@@ -633,7 +776,7 @@ pub struct FxMaps {
shape: Map,
/// Per enabled effect (in `items` order): the maps it paints through.
per: Vec<Vec<Map>>,
- outer_bevel: Vec<bool>,
+ bevel_paint: Vec<BevelPaint>,
din: Option<Vec<f32>>,
dout: Option<Vec<f32>>,
/// Shape layers: distance outside the vector outline (from local coverage).
@@ -675,8 +818,9 @@ fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map {
let (dx, dy) = offset(s.angle, s.distance);
let mut a = shape.shifted(dx, dy, 0.0);
let mut b = shape.shifted(-dx, -dy, 0.0);
- blur(&mut a, s.size);
- blur(&mut b, s.size);
+ // Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects).
+ tent(&mut a, s.size);
+ tent(&mut b, s.size);
let mut m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() };
if s.invert {
m = m.map(|v| 1.0 - v);
@@ -693,7 +837,7 @@ pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLigh
let (w, h) = (rect.width() as usize, rect.height() as usize);
let shape = Map { w, h, v: shape };
let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect();
- let mut outer_bevel = vec![false; items.len()];
+ let mut bevel_paint = vec![BevelPaint::Inner; items.len()];
let per: Vec<Vec<Map>> = items
.iter()
.enumerate()
@@ -704,9 +848,9 @@ pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLigh
Effect::InnerGlow(g) => vec![glow_map(&shape, g, true)],
Effect::Satin(s) => vec![satin_map(&shape, s)],
Effect::BevelEmboss(b) => {
- let (hi, sh, outer) = bevel_maps(&shape, b, light);
- outer_bevel[i] = outer;
- vec![hi, sh]
+ let (maps, paint) = bevel_maps(&shape, b, light);
+ bevel_paint[i] = paint;
+ maps
}
_ => Vec::new(),
})
@@ -715,7 +859,7 @@ pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLigh
let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_));
let (din, dout) = if has_stroke { (Some(dist_inside_by(&shape, Metric::Chamfer)), Some(dist_outside_by(&shape, Metric::Chamfer))) } else { (None, None) };
let vdout = (has_stroke && vector_shape).then(|| dist_outside_by(&local_coverage(&shape), Metric::Chamfer));
- FxMaps { rect, shape, per, outer_bevel, din, dout, vdout }
+ FxMaps { rect, shape, per, bevel_paint, din, dout, vdout }
}
/// Far outside any shape (distance fill for cropped distance fields).
@@ -839,7 +983,7 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
}
for (i, e) in rev() {
if let Effect::BevelEmboss(b) = e
- && !maps.outer_bevel[i]
+ && maps.bevel_paint[i] != BevelPaint::Outer
{
let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1)));
paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity);
@@ -904,9 +1048,10 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
}
for (i, e) in rev() {
if let Effect::BevelEmboss(b) = e
- && maps.outer_bevel[i]
+ && maps.bevel_paint[i] != BevelPaint::Inner
{
- let (hi, sh) = (fx(i, 0), fx(i, 1));
+ let k = if maps.bevel_paint[i] == BevelPaint::Both { 2 } else { 0 };
+ let (hi, sh) = (fx(i, k), fx(i, k + 1));
paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity);
paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity);
}
@@ -914,9 +1059,10 @@ pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Bu
// Layer (with interior effects) onto the exterior result, in the layer's mode.
let mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend };
+ let gamma = crate::text_gamma(layer);
for (wp, lp) in work.px.iter_mut().zip(&lay.px) {
if lp[3] > 0.0 {
- *wp = psblend::composite(mode, *wp, *lp, 1.0);
+ *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma);
}
}
// Layer opacity applies to the whole stack.
@@ -1051,6 +1197,108 @@ mod tests {
assert!(near.iter().all(|&n| n == 0));
}
+ #[test]
+ fn tent_kernel_is_two_boxes() {
+ let (r, k) = tent_kernel(5.0);
+ assert_eq!(r, 4);
+ let sum: f32 = k.iter().sum();
+ assert!((sum - 1.0).abs() < 1e-6);
+ assert!((k[4] - 5.0 / 25.0).abs() < 1e-6 && (k[0] - 1.0 / 25.0).abs() < 1e-6);
+ // Fractional widths taper the end taps; width 1 is the identity.
+ let (r, k) = tent_kernel(4.0);
+ assert_eq!(r, 4);
+ assert!(k[0] > 0.0 && k[0] < 1.0 / 25.0);
+ assert_eq!(tent_kernel(1.0), (0, vec![1.0]));
+ }
+
+ fn square(n: usize, x0: usize, x1: usize) -> Map {
+ let mut m = Map::new(n, n, 0.0);
+ for y in x0..x1 {
+ for x in x0..x1 {
+ m.v[y * n + x] = 1.0;
+ }
+ }
+ m
+ }
+
+ fn bevel_of(style: BevelStyle, technique: BevelTechnique) -> Bevel {
+ Bevel {
+ enabled: true,
+ style,
+ technique,
+ depth: 1.0,
+ up: true,
+ size: 5.0,
+ soften: 0.0,
+ angle: 90.0,
+ altitude: 30.0,
+ use_global_light: false,
+ gloss_contour: Contour::Linear,
+ highlight: photocraft_doc::FxCommon::new(BlendMode::Screen, 0.75),
+ highlight_color: photocraft_color::Color::WHITE,
+ shadow: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.75),
+ shadow_color: photocraft_color::Color::BLACK,
+ }
+ }
+
+ #[test]
+ fn smooth_inner_bevel_lights_the_top_edge_inside_only() {
+ let shape = square(40, 10, 30);
+ let (maps, paint) = bevel_maps(&shape, &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth), &GlobalLight::default());
+ assert_eq!(paint, BevelPaint::Inner);
+ let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x];
+ // Light from the top: highlight along the top edge, shadow along the bottom, flat middle.
+ assert!(at(&maps[0], 20, 10) > 0.5 && at(&maps[1], 20, 10) == 0.0);
+ assert!(at(&maps[1], 20, 29) > 0.5);
+ assert!(at(&maps[0], 20, 20) < 1e-3 && at(&maps[1], 20, 20) < 1e-3);
+ // Nothing outside the shape; the ramp reaches about `size` inside.
+ assert_eq!(at(&maps[0], 20, 8), 0.0);
+ assert!(at(&maps[0], 20, 15) < 0.05);
+ }
+
+ #[test]
+ fn emboss_paints_both_sides_and_pillow_flips_the_outside() {
+ let shape = square(40, 10, 30);
+ let l = GlobalLight::default();
+ let (e, paint) = bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l);
+ assert_eq!((paint, e.len()), (BevelPaint::Both, 4));
+ let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x];
+ // Emboss: the slope across the top edge faces the light on both sides.
+ assert!(at(&e[0], 20, 10) > 0.3 && at(&e[2], 20, 9) > 0.3);
+ let (p, _) = bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l);
+ assert!(at(&p[0], 20, 10) > 0.3 && at(&p[3], 20, 9) > 0.3, "pillow: outside top edge in shadow");
+ }
+
+ #[test]
+ fn chisel_hard_has_flat_facets() {
+ let shape = square(48, 10, 38);
+ let (m, _) = bevel_maps(&shape, &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard), &GlobalLight::default());
+ let at = |x: usize, y: usize| m[0].v[y * 48 + x];
+ // A constant slope: equal highlight along the top facet.
+ assert!(at(24, 12) > 0.1 && (at(24, 12) - at(24, 13)).abs() < 1e-3);
+ }
+
+ #[test]
+ fn glow_range_stretches_the_contour() {
+ let mut g = Glow {
+ common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0),
+ paint: FxPaint::Color(photocraft_color::Color::WHITE),
+ technique: GlowTechnique::Softer,
+ spread: 0.0,
+ size: 10.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ range: 0.5,
+ jitter: 0.0,
+ noise: 0.0,
+ source: GlowSource::Edge,
+ };
+ let l = glow_lut(&g).unwrap();
+ assert!((lut_at(&l, 0.25) - 0.5).abs() < 1e-3 && (lut_at(&l, 0.75) - 1.0).abs() < 1e-6);
+ g.range = 1.0;
+ assert!(glow_lut(&g).is_none());
+ }
+
#[test]
fn offsets_follow_light() {
let (dx, dy) = offset(120.0, 10.0);
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 8df3f324d..2c2ef3953 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -15,8 +15,11 @@
pub mod adjust;
pub mod effects;
+pub mod masks;
+pub mod multichannel;
pub mod pattern;
pub mod psblend;
+pub mod shape_split;
use photocraft_color::blend::BlendMode;
use psblend as blend;
@@ -76,9 +79,9 @@ pub fn render(doc: &Document, rect: Rect) -> Buffer {
/// [`render`] with an explicit tile size (tests check tile independence).
pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {
- let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns };
+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns, mode: doc.mode };
if rect.width() as i32 <= tile && rect.height() as i32 <= tile {
- let mut buf = Buffer::transparent(rect);
+ let mut buf = multichannel::backdrop(doc, rect);
composite_stack(&doc.layers, &mut buf, &cx);
return buf;
}
@@ -93,7 +96,7 @@ pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {
y += tile;
}
let run = |t: &Rect| {
- let mut b = Buffer::transparent(*t);
+ let mut b = multichannel::backdrop(doc, *t);
composite_stack(&doc.layers, &mut b, &cx);
b
};
@@ -124,7 +127,7 @@ pub fn flatten(doc: &Document) -> Buffer {
/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated.
pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
let mut buf = Buffer::transparent(rect);
- composite_stack(std::slice::from_ref(layer), &mut buf, &Ctx { canvas: rect, transfer: adjust::Transfer::Srgb, light: photocraft_doc::GlobalLight::default(), patterns: &[] });
+ composite_stack(std::slice::from_ref(layer), &mut buf, &Ctx { canvas: rect, transfer: adjust::Transfer::Srgb, light: photocraft_doc::GlobalLight::default(), patterns: &[], mode: photocraft_color::ColorMode::Rgb });
buf
}
@@ -177,6 +180,8 @@ struct Ctx<'a> {
light: photocraft_doc::GlobalLight,
/// The document's patterns (pattern fills and overlays).
patterns: &'a [Pattern],
+ /// The document's colour mode (channel restrictions name its channels).
+ mode: photocraft_color::ColorMode,
}
fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
@@ -271,7 +276,7 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
/// The alpha of `layer`'s own content over `rect` (masks applied, row-major): the shape its
/// effect maps are built from (for the GPU compositor). Zero for adjustment layers.
pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec<f32> {
- let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns };
+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns, mode: doc.mode };
render_content(layer, rect, &cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; rect.width() as usize * rect.height() as usize])
}
@@ -376,8 +381,49 @@ fn empty_in(layer: &Layer, rect: Rect) -> bool {
}
}
-/// Composite `layer` (plus its clipping group) onto `backdrop`.
+/// Blending Options › Channels as per-channel weights over display RGB (1 = the layer's result,
+/// 0 = the backdrop's value kept), or `None` when every channel blends. RGB documents map R, G, B
+/// directly and a grayscale document's single channel covers all three; other modes composite in
+/// display RGB, where a restriction to their own channels has no exact equivalent, so it is
+/// ignored there.
+pub fn channel_weights(layer: &Layer, mode: photocraft_color::ColorMode) -> Option<[f32; 3]> {
+ use photocraft_color::ColorMode as M;
+ let x = layer.excluded_channels;
+ if x == 0 {
+ return None;
+ }
+ let keep = |bit: u32| if x & (1 << bit) != 0 { 0.0 } else { 1.0 };
+ match mode {
+ M::Rgb => Some([keep(0), keep(1), keep(2)]),
+ M::Grayscale | M::Duotone => Some([keep(0); 3]),
+ _ => None,
+ }
+ .filter(|w| w != &[1.0; 3])
+}
+
+/// Put back the backdrop's values in the channels a layer leaves out (`w` from
+/// [`channel_weights`]); alpha stays the layer's result.
+fn restore_channels(out: &mut Buffer, before: &Buffer, w: [f32; 3]) {
+ for (p, b) in out.px.iter_mut().zip(&before.px) {
+ for c in 0..3 {
+ p[c] = b[c] + (p[c] - b[c]) * w[c];
+ }
+ }
+}
+
+/// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions.
fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
+ match channel_weights(layer, cx.mode) {
+ Some(w) => {
+ let before = backdrop.clone();
+ composite_layer_any(layer, clipped, backdrop, cx);
+ restore_channels(backdrop, &before, w);
+ }
+ None => composite_layer_any(layer, clipped, backdrop, cx),
+ }
+}
+
+fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) {
if let LayerContent::Group(g) = &layer.content
&& let Some(ab) = &g.artboard
{
@@ -523,7 +569,12 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
for c in clipped.iter().filter(|c| c.visible) {
composite_atop(c, &mut content, cx);
}
- blend_into(backdrop, &content, layer.blend, opacity);
+ blend_into_g(backdrop, &content, layer.blend, opacity, text_gamma(layer));
+}
+
+/// The coverage-mixing gamma of a layer: [`psblend::TEXT_GAMMA`] for type layers, else 1.
+pub fn text_gamma(layer: &Layer) -> f32 {
+ if matches!(layer.content, LayerContent::Text(_)) { psblend::TEXT_GAMMA } else { 1.0 }
}
/// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke
@@ -534,11 +585,9 @@ fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option
if sh.stroke.is_none() || !clipped.iter().any(|c| c.visible) {
return None;
}
- let fmt = photocraft_color::PixelFormat::RGBA8;
- let fill_only = photocraft_doc::vector::ShapeLayer { stroke: None, cache: None, ..sh.clone() };
- let stroke_only = photocraft_doc::vector::ShapeLayer { fill: None, cache: None, ..sh.clone() };
- let mut f = surface_to_buffer(&photocraft_vector::render_shape(&fill_only, fmt, cx.canvas.intersect(&rect)), rect);
- let mut s = surface_to_buffer(&photocraft_vector::render_shape(&stroke_only, fmt, cx.canvas.intersect(&rect)), rect);
+ let (fs, ss) = shape_split::split(sh, cx.canvas)?;
+ let mut f = surface_to_buffer(&fs, rect);
+ let mut s = surface_to_buffer(&ss, rect);
if let Some(m) = mask_vals(layer, rect) {
for ((a, b), k) in f.px.iter_mut().zip(s.px.iter_mut()).zip(&m) {
a[3] *= k;
@@ -693,8 +742,20 @@ fn effect_maps(layer: &Layer, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
maps
}
-/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics).
+/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics),
+/// honouring its channel restrictions.
fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
+ match channel_weights(layer, cx.mode) {
+ Some(w) => {
+ let before = base.clone();
+ composite_atop_any(layer, base, cx);
+ restore_channels(base, &before, w);
+ }
+ None => composite_atop_any(layer, base, cx),
+ }
+}
+
+fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
let rect = base.rect;
if let LayerContent::Adjustment(adj) = &layer.content {
let mut adjusted = base.clone();
@@ -727,6 +788,7 @@ fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
}
let Some(content) = render_content(layer, rect, cx) else { return };
let opacity = layer.opacity * layer.fill_opacity;
+ let gamma = text_gamma(layer);
for (i, p) in base.px.iter_mut().enumerate() {
let alpha = p[3];
if alpha <= 0.0 {
@@ -734,13 +796,18 @@ fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
}
let s = content.px[i];
// Blend as if the base were opaque, then keep the base's alpha.
- let r = blend::composite(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity);
+ let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma);
*p = [r[0], r[1], r[2], alpha];
}
}
/// Blend an isolated layer buffer into the backdrop.
fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) {
+ blend_into_g(backdrop, src, mode, opacity, 1.0);
+}
+
+/// [`blend_into`] mixing coverage in a `gamma` space (type layers).
+fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) {
let rect = backdrop.rect;
let w = rect.width() as i32;
for (i, b) in backdrop.px.iter_mut().enumerate() {
@@ -757,7 +824,7 @@ fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32
*b = blend::composite(mode, *b, s, 1.0);
continue;
}
- *b = blend::composite(mode, *b, s, opacity);
+ *b = blend::composite_gamma(mode, *b, s, opacity, gamma);
}
}
diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs
new file mode 100644
index 000000000..ea1e1ef96
--- /dev/null
+++ b/crates/compose/src/masks.rs
@@ -0,0 +1,133 @@
+//! A layer's effective mask (pixel mask × vector mask) as one surface, for backends that sample
+//! masks from textures (the GPU compositor). Rasterising a vector mask costs a path coverage
+//! pass, so results are cached per mask state; unchanged masks return the same tiles (cheap to
+//! clone, and the GPU sees no change).
+
+use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_doc::Layer;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+const FORMAT: PixelFormat = PixelFormat { mode: ColorMode::Grayscale, sample: SampleType::F32, alpha: false };
+
+struct Cache {
+ map: HashMap<u64, (Surface, u64)>,
+ tick: u64,
+}
+
+fn cache() -> &'static Mutex<Cache> {
+ static C: OnceLock<Mutex<Cache>> = OnceLock::new();
+ C.get_or_init(|| Mutex::new(Cache { map: HashMap::new(), tick: 0 }))
+}
+
+/// Entries kept (least recently used dropped first).
+const CAPACITY: usize = 64;
+
+fn key(layer: &Layer, canvas: Rect) -> u64 {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ layer.id.0.hash(&mut h);
+ (canvas.x0, canvas.y0, canvas.x1, canvas.y1).hash(&mut h);
+ format!("{:?}", layer.vector_mask).hash(&mut h);
+ if let Some(m) = &layer.mask {
+ (m.enabled, m.density.to_bits()).hash(&mut h);
+ format!("{:?}", m.surface.default_pixel()).hash(&mut h);
+ for (c, t) in m.surface.tiles() {
+ (c.tx, c.ty, Arc::as_ptr(t) as usize).hash(&mut h);
+ }
+ }
+ h.finish()
+}
+
+/// The layer's mask values (pixel mask with density × vector mask, exactly as the CPU
+/// compositor applies them) as a single-channel f32 surface over `canvas`, or `None` when the
+/// layer has no enabled vector mask (use the pixel mask directly). Values outside the computed
+/// area are the surface's default.
+pub fn combined_mask(layer: &Layer, canvas: Rect) -> Option<Surface> {
+ let vm = layer.vector_mask.as_ref().filter(|v| v.enabled)?;
+ let k = key(layer, canvas);
+ {
+ let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
+ c.tick += 1;
+ let tick = c.tick;
+ if let Some(e) = c.map.get_mut(&k) {
+ e.1 = tick;
+ return Some(e.0.clone());
+ }
+ }
+ // Far outside the path the vector mask is constant.
+ let far = Rect::from_xywh(canvas.x0 - 1_000_000, canvas.y0 - 1_000_000, 1, 1);
+ let v_out = photocraft_vector::vector_mask_values(vm, far)[0];
+ let pixel = layer.mask.as_ref().filter(|m| m.enabled);
+ let p_def = pixel.map_or(1.0, |m| {
+ let d = m.surface.default_pixel().first().copied().unwrap_or(1.0);
+ 1.0 - m.density * (1.0 - d)
+ });
+ // Where the product can differ from `p_def × v_out`: the path's bounds, plus the pixel
+ // mask's painted tiles when the vector mask lets them through outside the path.
+ let mut area = match vm.path.control_bounds() {
+ Some((x0, y0, x1, y1)) => Rect::new(x0.floor() as i32 - 2, y0.floor() as i32 - 2, x1.ceil() as i32 + 2, y1.ceil() as i32 + 2),
+ None => Rect::EMPTY,
+ };
+ if let Some(m) = pixel
+ && v_out > 0.0
+ {
+ let b = m.surface.content_bounds();
+ area = if area.is_empty() { b } else if b.is_empty() { area } else { area.union(&b) };
+ }
+ let area = area.intersect(&canvas);
+ let mut s = Surface::with_default(FORMAT, &[p_def * v_out]);
+ if !area.is_empty() {
+ let mut v = photocraft_vector::vector_mask_values(vm, area);
+ if let Some(m) = pixel {
+ let mut pm = Vec::new();
+ m.values_into(area, &mut pm);
+ for (a, b) in v.iter_mut().zip(pm) {
+ *a *= b;
+ }
+ }
+ s.write_region(area, &v);
+ }
+ let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
+ if c.map.len() >= CAPACITY
+ && let Some(old) = c.map.iter().min_by_key(|e| e.1.1).map(|e| *e.0)
+ {
+ c.map.remove(&old);
+ }
+ let tick = c.tick;
+ c.map.insert(k, (s.clone(), tick));
+ Some(s)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask};
+
+ #[test]
+ fn matches_the_cpu_mask_and_is_cached() {
+ let mut l = Layer::raster("l", PixelFormat::RGBA8);
+ let pts = [(5.0, 5.0), (30.0, 6.0), (20.0, 28.0)];
+ let knots = pts.iter().map(|&(x, y)| Knot::corner(x, y)).collect();
+ let mut path = Path::default();
+ path.subpaths.push(Subpath { knots, closed: true, ..Default::default() });
+ let mut vm = VectorMask::new(path);
+ vm.density = 0.9;
+ l.vector_mask = Some(vm);
+ let canvas = Rect::new(0, 0, 40, 32);
+ let s = combined_mask(&l, canvas).unwrap();
+ let want = photocraft_vector::vector_mask_values(l.vector_mask.as_ref().unwrap(), canvas);
+ let mut got = Vec::new();
+ s.read_region_into(canvas, &mut got);
+ for (a, b) in got.iter().zip(&want) {
+ assert!((a - b).abs() < 1e-6);
+ }
+ let again = combined_mask(&l, canvas).unwrap();
+ assert!(s.tiles().zip(again.tiles()).all(|(a, b)| Arc::ptr_eq(a.1, b.1)));
+ l.vector_mask = None;
+ assert!(combined_mask(&l, canvas).is_none());
+ }
+}
diff --git a/crates/compose/src/multichannel.rs b/crates/compose/src/multichannel.rs
new file mode 100644
index 000000000..63bec04bf
--- /dev/null
+++ b/crates/compose/src/multichannel.rs
@@ -0,0 +1,72 @@
+//! Display of Multichannel documents: every spot (ink) channel printed over white paper.
+//!
+//! Ink density `v` (the channel value, 1 = solid) of an ink with display colour `c` and solidity
+//! `s` turns the colour underneath `p` into `(1 − s·v)·p·(1 − v + v·c) + s·v·c`: transparent inks
+//! (solidity 0) multiply like overprinted process inks, opaque ones cover what is below, which is
+//! how Photoshop previews spot channels.
+
+use photocraft_doc::Document;
+use photocraft_geom::Rect;
+
+use crate::Buffer;
+
+/// The printed inks of `doc` over `rect` (opaque).
+pub fn inks(doc: &Document, rect: Rect) -> Buffer {
+ let mut buf = Buffer::filled(rect, [1.0, 1.0, 1.0, 1.0]);
+ let mut vals = Vec::new();
+ for ch in &doc.channels {
+ let Some((ink, solidity)) = ch.spot else { continue };
+ if ch.surface.content_bounds().intersect(&rect).is_empty() {
+ continue;
+ }
+ let c = ink.to_rgb();
+ let s = solidity.clamp(0.0, 1.0);
+ let n = ch.surface.channels();
+ ch.surface.read_region_into(rect, &mut vals);
+ for (p, v) in buf.px.iter_mut().zip(vals.chunks_exact(n)) {
+ let v = v[0].clamp(0.0, 1.0);
+ if v <= 0.0 {
+ continue;
+ }
+ let keep = 1.0 - s * v;
+ for j in 0..3 {
+ p[j] = keep * p[j] * (1.0 - v + v * c[j]) + s * v * c[j];
+ }
+ }
+ }
+ buf
+}
+
+/// The starting backdrop of a document render: the inks for Multichannel, else transparent.
+pub(crate) fn backdrop(doc: &Document, rect: Rect) -> Buffer {
+ if doc.mode == photocraft_color::ColorMode::Multichannel { inks(doc, rect) } else { Buffer::transparent(rect) }
+}
+
+#[cfg(test)]
+mod tests {
+ use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+ use photocraft_doc::{AlphaChannel, Document, Size};
+ use photocraft_raster::Surface;
+
+ use super::*;
+
+ #[test]
+ fn inks_multiply_over_paper() {
+ let mut doc = Document::new("m", Size::new(4, 1), ColorMode::Multichannel, SampleType::U8);
+ let fmt = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
+ let mut a = Surface::new(fmt);
+ a.write_region(Rect::new(0, 0, 4, 1), &[0.0, 1.0, 1.0, 0.0]);
+ let mut b = Surface::new(fmt);
+ b.write_region(Rect::new(0, 0, 4, 1), &[0.0, 0.0, 1.0, 1.0]);
+ doc.channels.push(AlphaChannel { spot: Some((Color::rgb(0.0, 1.0, 1.0), 0.0)), ..AlphaChannel::new("Cyan", a) });
+ doc.channels.push(AlphaChannel { spot: Some((Color::rgb(1.0, 0.0, 1.0), 0.0)), ..AlphaChannel::new("Magenta", b) });
+ let r = crate::flatten(&doc);
+ assert_eq!(r.px[0], [1.0, 1.0, 1.0, 1.0]);
+ assert_eq!(r.px[1], [0.0, 1.0, 1.0, 1.0]);
+ assert_eq!(r.px[2], [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!(r.px[3], [1.0, 0.0, 1.0, 1.0]);
+ // Alpha channels and other modes are not inks.
+ doc.mode = ColorMode::Rgb;
+ assert_eq!(crate::flatten(&doc).px[1][3], 0.0);
+ }
+}
diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rs
index 90fa9ab69..d762428b8 100644
--- a/crates/compose/src/psblend.rs
+++ b/crates/compose/src/psblend.rs
@@ -24,16 +24,41 @@ fn vivid_light_ps(cb: f32, cs: f32) -> f32 {
}
}
+/// Backdrop values within `EDGE` of 0 / 1 count as exact in the modes whose result jumps there
+/// (Color Burn / Dodge, Hard Mix): a composited value that should be 1 can come out a rounding
+/// step below it (and differently on the GPU), flipping the corner case by up to 255 levels.
+pub const EDGE: f32 = 1e-4;
+
+fn color_burn(cb: f32, cs: f32) -> f32 {
+ if cb >= 1.0 - EDGE {
+ 1.0
+ } else if cs <= 0.0 {
+ 0.0
+ } else {
+ 1.0 - ((1.0 - cb) / cs).min(1.0)
+ }
+}
+
+fn color_dodge(cb: f32, cs: f32) -> f32 {
+ if cb <= EDGE {
+ 0.0
+ } else if cs >= 1.0 {
+ 1.0
+ } else {
+ (cb / (1.0 - cs)).min(1.0)
+ }
+}
+
fn vivid_light_generic(cb: f32, cs: f32) -> f32 {
if cs <= 0.5 {
- if cb >= 1.0 {
+ if cb >= 1.0 - EDGE {
1.0
} else if cs <= 0.0 {
0.0
} else {
1.0 - ((1.0 - cb) / (2.0 * cs)).min(1.0)
}
- } else if cb <= 0.0 {
+ } else if cb <= EDGE {
0.0
} else if cs >= 1.0 {
1.0
@@ -51,6 +76,8 @@ pub fn blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
match mode {
BlendMode::VividLight => std::array::from_fn(|i| vivid_light_ps(cb[i], cs[i])),
BlendMode::HardMix => std::array::from_fn(|i| hard_mix_ps(cb[i], cs[i])),
+ BlendMode::ColorBurn => std::array::from_fn(|i| color_burn(cb[i], cs[i])),
+ BlendMode::ColorDodge => std::array::from_fn(|i| color_dodge(cb[i], cs[i])),
m => generic::blend_rgb(m, cb, cs),
}
}
@@ -92,8 +119,50 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity:
out
}
+/// Photoshop's "Blend Text Colors Using Gamma" (Color Settings › Advanced, on at 1.45 by
+/// default): type layers mix their colour with the backdrop in a gamma-1.45 space, so
+/// anti-aliased glyph edges come out lighter over dark backdrops than a linear mix (fitted on
+/// psd-tools layer_effects.psd: a 69 % edge pixel of a blue overlay over grey is 57/255 in red,
+/// a linear mix gives 40).
+pub const TEXT_GAMMA: f32 = 1.45;
+
+/// [`composite`] with the coverage mix done in a `gamma` space (`gamma == 1` is [`composite`]).
+pub fn composite_gamma(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: f32, gamma: f32) -> [f32; 4] {
+ if gamma == 1.0 {
+ return composite(mode, backdrop, source, opacity);
+ }
+ let ab = backdrop[3];
+ let as_ = source[3] * opacity;
+ if as_ <= 0.0 {
+ return backdrop;
+ }
+ let ao = as_ + ab * (1.0 - as_);
+ if ao <= 0.0 {
+ return [0.0; 4];
+ }
+ let cb = [backdrop[0], backdrop[1], backdrop[2]];
+ let cs = [source[0], source[1], source[2]];
+ let b = blend_rgb(mode, cb, cs);
+ let (wb, ws, wbs) = ((1.0 - as_) * ab / ao, (1.0 - ab) * as_ / ao, as_ * ab / ao);
+ let g = |v: f32| v.max(0.0).powf(gamma);
+ let mut out = [0.0f32; 4];
+ for i in 0..3 {
+ out[i] = (wb * g(cb[i]) + ws * g(cs[i]) + wbs * g(b[i])).powf(1.0 / gamma);
+ }
+ out[3] = ao;
+ out
+}
+
#[cfg(test)]
mod tests {
+ #[test]
+ fn text_gamma_lightens_dark_edges() {
+ // 69 % blue (0, 51, 153) over grey 129: Photoshop shows (57, 80, 146).
+ let r = composite_gamma(BlendMode::Normal, [129.0 / 255.0, 129.0 / 255.0, 129.0 / 255.0, 1.0], [0.0, 0.2, 0.6, 0.686], 1.0, TEXT_GAMMA);
+ assert!((r[0] * 255.0 - 57.0).abs() < 2.0 && (r[1] * 255.0 - 80.0).abs() < 2.0 && (r[2] * 255.0 - 146.0).abs() < 2.0, "{r:?}");
+ assert_eq!(composite_gamma(BlendMode::Multiply, [0.2, 0.4, 0.6, 0.7], [0.5, 0.1, 0.9, 0.5], 0.8, 1.0), composite(BlendMode::Multiply, [0.2, 0.4, 0.6, 0.7], [0.5, 0.1, 0.9, 0.5], 0.8));
+ }
+
use super::*;
#[test]
@@ -112,10 +181,18 @@ mod tests {
assert_eq!(hard_mix_ps(0.3, 0.3), 0.0);
}
+ #[test]
+ fn burn_and_dodge_treat_near_extremes_as_exact() {
+ assert_eq!(color_burn(1.0 - 1e-6, 0.0), 1.0);
+ assert_eq!(color_dodge(1e-6, 1.0), 0.0);
+ assert!((color_burn(0.5, 0.5) - 0.0).abs() < 1e-6);
+ assert!((color_dodge(0.25, 0.5) - 0.5).abs() < 1e-6);
+ }
+
#[test]
fn other_modes_delegate() {
for m in BlendMode::LAYER_MODES {
- if matches!(m, BlendMode::VividLight | BlendMode::HardMix) {
+ if matches!(m, BlendMode::VividLight | BlendMode::HardMix | BlendMode::ColorBurn | BlendMode::ColorDodge) {
continue;
}
let (cb, cs) = ([0.2, 0.5, 0.9], [0.7, 0.1, 0.4]);
diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs
new file mode 100644
index 000000000..e802a26c9
--- /dev/null
+++ b/crates/compose/src/shape_split.rs
@@ -0,0 +1,53 @@
+//! A stroked shape layer split into its fill and its vector stroke (rasterised over the canvas),
+//! for shapes with clipped layers: Photoshop draws the stroke above the clipped layers. Cached
+//! per shape state, so tiles (and the GPU's textures) reuse one rasterisation.
+
+use std::collections::HashMap;
+use std::hash::{Hash, Hasher};
+use std::sync::{Mutex, OnceLock};
+
+use photocraft_color::PixelFormat;
+use photocraft_doc::vector::ShapeLayer;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+type Entry = ((Surface, Surface), u64);
+
+fn cache() -> &'static Mutex<(HashMap<u64, Entry>, u64)> {
+ static C: OnceLock<Mutex<(HashMap<u64, Entry>, u64)>> = OnceLock::new();
+ C.get_or_init(|| Mutex::new((HashMap::new(), 0)))
+}
+
+const CAPACITY: usize = 32;
+
+/// (fill only, stroke only) of a stroked shape, rendered over `canvas` (RGBA8, as the CPU
+/// compositor's split always was). `None` without a stroke.
+pub fn split(sh: &ShapeLayer, canvas: Rect) -> Option<(Surface, Surface)> {
+ sh.stroke.as_ref()?;
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ (canvas.x0, canvas.y0, canvas.x1, canvas.y1).hash(&mut h);
+ format!("{:?}{:?}{:?}{:?}", sh.path, sh.fill, sh.stroke, sh.live).hash(&mut h);
+ let key = h.finish();
+ {
+ let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
+ c.1 += 1;
+ let tick = c.1;
+ if let Some(e) = c.0.get_mut(&key) {
+ e.1 = tick;
+ return Some(e.0.clone());
+ }
+ }
+ let fmt = PixelFormat::RGBA8;
+ let fill_only = ShapeLayer { stroke: None, cache: None, ..sh.clone() };
+ let stroke_only = ShapeLayer { fill: None, cache: None, ..sh.clone() };
+ let parts = (photocraft_vector::render_shape(&fill_only, fmt, canvas), photocraft_vector::render_shape(&stroke_only, fmt, canvas));
+ let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());
+ if c.0.len() >= CAPACITY
+ && let Some(old) = c.0.iter().min_by_key(|e| (e.1).1).map(|e| *e.0)
+ {
+ c.0.remove(&old);
+ }
+ let tick = c.1;
+ c.0.insert(key, (parts.clone(), tick));
+ Some(parts)
+}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 4b9869b69..51e05e037 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -642,7 +642,7 @@ fn effect_maps_are_cached_and_invalidated_by_pixel_changes() {
let mut l = solid_layer("fx", Rect::new(16, 16, 48, 48), [1.0, 0.0, 0.0, 1.0]);
l.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
doc.layers.push(l);
- let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::Srgb, light: doc.global_light, patterns: &doc.patterns };
+ let cx = Ctx { canvas: doc.bounds(), transfer: adjust::Transfer::Srgb, light: doc.global_light, patterns: &doc.patterns, mode: doc.mode };
let a = effect_maps(&doc.layers[1], &cx);
let b = effect_maps(&doc.layers[1], &cx);
assert!(std::sync::Arc::ptr_eq(&a, &b), "second request hits the cache");
@@ -756,3 +756,21 @@ fn linked_pattern_overlay_anchors_at_the_effects_reference_point() {
assert!(close4(px(&d, 11, 20), [1.0, 0.0, 0.0, 1.0]), "{:?}", px(&d, 11, 20));
assert!(close4(px(&d, 12, 20), [0.0, 0.0, 1.0, 1.0]), "{:?}", px(&d, 12, 20));
}
+
+#[test]
+fn channel_restrictions_keep_the_backdrop() {
+ // Blue left out (Photoshop's Advanced Blending › Channels: R, G only).
+ let mut d = doc_white(8, 8);
+ let mut l = solid_layer("dark", Rect::new(0, 0, 8, 8), [0.2, 0.3, 0.4, 1.0]);
+ l.excluded_channels = 0b100;
+ d.layers.push(l);
+ assert!(close4(px(&d, 1, 1), [0.2, 0.3, 1.0, 1.0]));
+ // Adjustment layers honour it too.
+ let mut inv = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert));
+ inv.excluded_channels = 0b001;
+ d.layers.push(inv);
+ assert!(close4(px(&d, 1, 1), [0.2, 0.7, 0.0, 1.0]));
+ // CMYK documents composite in display RGB: no exact equivalent, ignored.
+ assert_eq!(channel_weights(&d.layers[1], ColorMode::Cmyk), None);
+ assert_eq!(channel_weights(&d.layers[1], ColorMode::Rgb), Some([1.0, 1.0, 0.0]));
+}
diff --git a/crates/doc/src/analysis.rs b/crates/doc/src/analysis.rs
new file mode 100644
index 000000000..51845a6a7
--- /dev/null
+++ b/crates/doc/src/analysis.rs
@@ -0,0 +1,138 @@
+//! Image › Analysis data stored with a document (measurement scale, count groups, the ruler line)
+//! and annotations (Notes). Pure data; the measuring itself lives in the engine.
+
+use photocraft_color::Color;
+use serde::{Deserialize, Serialize};
+
+/// Image › Analysis › Set Measurement Scale: `pixel_length` pixels equal `logical_length`
+/// `units`. The default is 1 pixel = 1 pixel.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct MeasurementScale {
+ pub pixel_length: f64,
+ pub logical_length: f64,
+ pub units: String,
+}
+
+impl Default for MeasurementScale {
+ fn default() -> Self {
+ Self { pixel_length: 1.0, logical_length: 1.0, units: "pixels".into() }
+ }
+}
+
+impl MeasurementScale {
+ /// Logical units per pixel.
+ pub fn factor(&self) -> f64 {
+ if self.pixel_length > 0.0 { self.logical_length / self.pixel_length } else { 1.0 }
+ }
+ pub fn is_default(&self) -> bool {
+ *self == Self::default()
+ }
+ /// Photoshop's "Scale" column text, e.g. `1 pixels = 1.0000 pixels`.
+ pub fn describe(&self) -> String {
+ format!("{} pixels = {:.4} {}", trim(self.pixel_length), self.logical_length, self.units)
+ }
+}
+
+fn trim(v: f64) -> String {
+ if v.fract() == 0.0 { format!("{}", v as i64) } else { format!("{v}") }
+}
+
+/// One Count tool group: its numbered markers (document pixel coordinates, in click order).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct CountGroup {
+ pub name: String,
+ pub color: Color,
+ /// Marker (dot) size and label font size, in screen pixels (Photoshop: 1–10 and 8–72).
+ pub marker_size: u32,
+ pub label_size: u32,
+ pub visible: bool,
+ pub points: Vec<[f64; 2]>,
+}
+
+impl Default for CountGroup {
+ fn default() -> Self {
+ Self { name: "Count Group 1".into(), color: Color::rgb(1.0, 0.0, 0.0), marker_size: 1, label_size: 8, visible: true, points: Vec::new() }
+ }
+}
+
+/// The Ruler tool line, optionally with a protractor second arm (⌥-drag from an end point).
+/// `start` is the vertex the angle is measured at when there is a protractor.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Ruler {
+ pub start: [f64; 2],
+ pub end: [f64; 2],
+ #[serde(default)]
+ pub protractor: Option<[f64; 2]>,
+}
+
+/// Measurement settings and marks of a document.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Measurement {
+ pub scale: MeasurementScale,
+ pub count_groups: Vec<CountGroup>,
+ /// Index into `count_groups` that new markers go to.
+ pub active_count_group: usize,
+ pub ruler: Option<Ruler>,
+}
+
+impl Measurement {
+ pub fn is_empty(&self) -> bool {
+ *self == Self::default()
+ }
+ /// Total markers over every group.
+ pub fn count_total(&self) -> usize {
+ self.count_groups.iter().map(|g| g.points.len()).sum()
+ }
+}
+
+/// A Note tool annotation (PSD `Anno` text annotation).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Note {
+ pub author: String,
+ pub color: Color,
+ pub text: String,
+ /// Icon position (top-left, document pixels).
+ pub position: [f64; 2],
+ /// Popup rectangle [left, top, right, bottom] (document pixels), as stored in PSD.
+ pub popup: [f64; 4],
+ /// Popup shown open.
+ pub open: bool,
+ /// Modification date as PDF date text (`D:YYYYMMDDhhmmss…`); empty when unknown.
+ pub modified: String,
+}
+
+impl Default for Note {
+ fn default() -> Self {
+ // Photoshop's default note colour (pale yellow).
+ Self { author: String::new(), color: Color::rgb(1.0, 1.0, 0.51), text: String::new(), position: [0.0, 0.0], popup: [0.0, 0.0, 0.0, 0.0], open: false, modified: String::new() }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn scale_factor_and_text() {
+ let s = MeasurementScale { pixel_length: 100.0, logical_length: 2.5, units: "cm".into() };
+ assert!((s.factor() - 0.025).abs() < 1e-12);
+ assert_eq!(s.describe(), "100 pixels = 2.5000 cm");
+ assert!(MeasurementScale::default().is_default());
+ assert_eq!(MeasurementScale { pixel_length: 0.0, ..Default::default() }.factor(), 1.0);
+ }
+
+ #[test]
+ fn serde_defaults_fill_missing_fields() {
+ let m: Measurement = serde_json::from_str("{}").unwrap();
+ assert!(m.is_empty());
+ let n: Note = serde_json::from_str(r#"{"text":"hi"}"#).unwrap();
+ assert_eq!(n.text, "hi");
+ let g = CountGroup { points: vec![[1.0, 2.0], [3.0, 4.0]], ..Default::default() };
+ let m = Measurement { count_groups: vec![g.clone(), g], ..Default::default() };
+ assert_eq!(m.count_total(), 4);
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 5c65d90e2..a5765a846 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -8,17 +8,21 @@
#![forbid(unsafe_code)]
pub mod adjust;
+pub mod analysis;
pub mod comps;
pub mod effects;
pub mod mode;
pub mod pattern;
+pub mod slices;
pub mod text;
+pub mod text_styles;
pub mod vector;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
pub use adjust::Adjustment;
+pub use analysis::{CountGroup, Measurement, MeasurementScale, Note, Ruler};
pub use comps::{Artboard, ArtboardBackground, CompAppearance, CompLayerState, LayerComp};
pub use effects::{
Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, GlobalLight, Glow, GlowSource, GlowTechnique, Gradient,
@@ -29,6 +33,8 @@ pub use photocraft_geom::{Affine, Rect, Size};
pub use photocraft_raster::Surface;
pub use mode::{ColorTable, Duotone, DuotoneInk, StackMode};
pub use pattern::Pattern;
+pub use slices::{Slice, SliceKind, SliceOrigin, Slices};
+pub use text_styles::TextStyles;
pub use vector::{
ClippingPath, FillRule, Knot, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath,
VectorMask,
@@ -408,6 +414,10 @@ pub struct Layer {
pub fill_cache: Option<FillCache>,
/// Layer › Link Layers: layers sharing a link group move together. `None` = not linked.
pub link_group: Option<u64>,
+ /// Blending Options › Advanced Blending › Channels: bit `i` set = colour channel `i` of the
+ /// document's mode (R, G, B / C, M, Y, K / L, a, b / Gray) is left out of blending, so the
+ /// backdrop's value is kept there. 0 = every channel blends (the default). PSD `brst`.
+ pub excluded_channels: u32,
}
impl Layer {
@@ -430,6 +440,7 @@ impl Layer {
psd_id: None,
fill_cache: None,
link_group: None,
+ excluded_channels: 0,
}
}
pub fn raster(name: impl Into<String>, format: PixelFormat) -> Self {
@@ -590,6 +601,14 @@ pub struct Document {
/// "Last Document State": layer state saved when a comp is applied over the document's own
/// state, restored by `layerComp.restoreLastDocumentState`. Its id is 0.
pub last_document_state: Option<LayerComp>,
+ /// Image › Analysis: measurement scale, Count tool groups and the Ruler line.
+ pub measurement: Measurement,
+ /// Note tool annotations (PSD `Anno`).
+ pub notes: Vec<Note>,
+ /// Character and paragraph styles (Window › Character Styles / Paragraph Styles).
+ pub text_styles: TextStyles,
+ /// Web slices (Slice tool, layer-based slices; PSD resource 1050). Auto slices are derived.
+ pub slices: Slices,
}
/// Where a layer lives in the tree: indices from the root down.
@@ -621,6 +640,10 @@ impl Document {
layer_comps: Vec::new(),
last_applied_comp: None,
last_document_state: None,
+ measurement: Measurement::default(),
+ notes: Vec::new(),
+ text_styles: TextStyles::default(),
+ slices: Slices::default(),
}
}
diff --git a/crates/doc/src/mode.rs b/crates/doc/src/mode.rs
index 8b0bd4166..56b106496 100644
--- a/crates/doc/src/mode.rs
+++ b/crates/doc/src/mode.rs
@@ -78,6 +78,13 @@ pub struct Duotone {
pub psd_raw: Option<Vec<u8>>,
}
+impl DuotoneInk {
+ /// Ink density for a gray density (0 = paper, 1 = solid) through the ink's curve.
+ pub fn density(&self, gray_density: f32) -> f32 {
+ curve_eval(&self.curve, gray_density.clamp(0.0, 1.0)).clamp(0.0, 1.0)
+ }
+}
+
impl Duotone {
/// Simulated print colour of a gray value (0 = black, 1 = white): inks multiply over white paper.
pub fn render(&self, gray: f32) -> [f32; 3] {
diff --git a/crates/doc/src/slices.rs b/crates/doc/src/slices.rs
new file mode 100644
index 000000000..5890dbc3a
--- /dev/null
+++ b/crates/doc/src/slices.rs
@@ -0,0 +1,304 @@
+//! Web slices (Slice tool, Layer › New Layer Based Slice, Save for Web): pure data plus the
+//! auto-slice partition and Photoshop-style numbering.
+//!
+//! A document keeps its *user* slices (drawn with the Slice tool) and *layer-based* slices (they
+//! follow a layer's bounds, effects included). *Auto* slices are never stored: they are the
+//! rectangles that fill the rest of the canvas, recomputed whenever they are needed, exactly like
+//! Photoshop regenerates them after every slice edit.
+
+use photocraft_geom::Rect;
+use serde::{Deserialize, Serialize};
+
+use crate::{Document, LayerId};
+
+/// Where a slice comes from (PSD `ESliceOrigin`).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SliceOrigin {
+ /// Fills the canvas around user and layer slices; regenerated, never edited.
+ Auto,
+ /// Follows a layer's content bounds (Layer › New Layer Based Slice).
+ Layer,
+ /// Drawn with the Slice tool (or promoted from an auto slice).
+ #[default]
+ User,
+}
+
+impl SliceOrigin {
+ /// PSD resource 1050 code: 0 auto, 1 layer, 2 user.
+ pub fn code(self) -> u32 {
+ match self {
+ SliceOrigin::Auto => 0,
+ SliceOrigin::Layer => 1,
+ SliceOrigin::User => 2,
+ }
+ }
+ pub fn from_code(c: u32) -> Self {
+ match c {
+ 0 => SliceOrigin::Auto,
+ 1 => SliceOrigin::Layer,
+ _ => SliceOrigin::User,
+ }
+ }
+ pub fn id(self) -> &'static str {
+ match self {
+ SliceOrigin::Auto => "auto",
+ SliceOrigin::Layer => "layer",
+ SliceOrigin::User => "user",
+ }
+ }
+}
+
+/// Slice Options › Slice Type.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SliceKind {
+ /// Exported as an image file.
+ #[default]
+ Image,
+ /// An HTML cell with text (or nothing); no image is written.
+ NoImage,
+ /// A nested table (ImageReady legacy; exported like Image).
+ Table,
+}
+
+impl SliceKind {
+ /// PSD resource 1050 code: 0 no image, 1 image, 2 table.
+ pub fn code(self) -> u32 {
+ match self {
+ SliceKind::NoImage => 0,
+ SliceKind::Image => 1,
+ SliceKind::Table => 2,
+ }
+ }
+ pub fn from_code(c: u32) -> Self {
+ match c {
+ 0 => SliceKind::NoImage,
+ 2 => SliceKind::Table,
+ _ => SliceKind::Image,
+ }
+ }
+ pub fn id(self) -> &'static str {
+ match self {
+ SliceKind::Image => "image",
+ SliceKind::NoImage => "noImage",
+ SliceKind::Table => "table",
+ }
+ }
+ pub fn from_id(s: &str) -> Option<Self> {
+ Some(match s {
+ "image" | "img" => SliceKind::Image,
+ "noImage" | "none" | "no-image" => SliceKind::NoImage,
+ "table" => SliceKind::Table,
+ _ => return None,
+ })
+ }
+}
+
+/// One slice and its Slice Options.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Slice {
+ /// Stable id (PSD `sliceID`), unique within the document.
+ pub id: u32,
+ pub group_id: u32,
+ pub origin: SliceOrigin,
+ /// The layer a layer-based slice follows.
+ pub layer: Option<LayerId>,
+ /// Slice Options › Name (empty = the generated `<document>_<NN>`).
+ pub name: String,
+ /// Document pixels. Layer-based slices: the layer's bounds (with effects) plus `outsets`.
+ pub rect: Rect,
+ pub kind: SliceKind,
+ pub url: String,
+ pub target: String,
+ pub message: String,
+ pub alt: String,
+ pub cell_text_is_html: bool,
+ pub cell_text: String,
+ /// HTML alignment of no-image cells (0 default, 1 left, 2 centre, 3 right / top, middle, …).
+ pub horizontal_align: u32,
+ pub vertical_align: u32,
+ /// Slice background (ARGB, 8-bit); None = none.
+ pub background: Option<[u8; 4]>,
+ /// Layer-based slices: extra margin [top, left, bottom, right].
+ pub outsets: [i32; 4],
+}
+
+/// The document's slices (PSD resource 1050).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Slices {
+ /// Group name (PSD: the base name, usually the document name).
+ pub group_name: String,
+ /// User and layer-based slices, in creation order (later slices are on top).
+ pub list: Vec<Slice>,
+}
+
+impl Slices {
+ pub fn is_empty(&self) -> bool {
+ self.list.is_empty()
+ }
+ /// A fresh slice id (Photoshop counts from 1; auto slices use ids too, so leave room).
+ pub fn next_id(&self) -> u32 {
+ self.list.iter().map(|s| s.id).max().unwrap_or(0) + 1
+ }
+ pub fn get(&self, id: u32) -> Option<&Slice> {
+ self.list.iter().find(|s| s.id == id)
+ }
+ pub fn get_mut(&mut self, id: u32) -> Option<&mut Slice> {
+ self.list.iter_mut().find(|s| s.id == id)
+ }
+}
+
+/// A slice as shown and exported: user/layer slices plus generated auto slices, numbered the way
+/// Photoshop numbers them (top-to-bottom, left-to-right, from 1).
+#[derive(Clone, Debug, PartialEq)]
+pub struct ResolvedSlice {
+ /// 1-based display number.
+ pub number: usize,
+ /// The stored slice (None for auto slices).
+ pub id: Option<u32>,
+ pub origin: SliceOrigin,
+ pub rect: Rect,
+ /// The slice's name, or the generated `<base>_<NN>`.
+ pub name: String,
+ pub kind: SliceKind,
+}
+
+/// The visible part of every stored slice (later slices cover earlier ones, as in Photoshop),
+/// clipped to the canvas.
+fn clipped(doc: &Document) -> Vec<(u32, Rect)> {
+ let canvas = doc.bounds();
+ doc.slices.list.iter().map(|s| (s.id, s.rect.intersect(&canvas))).filter(|(_, r)| !r.is_empty()).collect()
+}
+
+/// Rectangles that tile `canvas` minus `taken`. The canvas is cut into a grid along every slice
+/// edge; free cells merge into horizontal runs per row band, then runs with identical columns
+/// merge down, which yields the few large auto slices Photoshop shows.
+pub fn auto_slices(canvas: Rect, taken: &[Rect]) -> Vec<Rect> {
+ if canvas.is_empty() {
+ return Vec::new();
+ }
+ let mut xs = vec![canvas.x0, canvas.x1];
+ let mut ys = vec![canvas.y0, canvas.y1];
+ for r in taken {
+ let r = r.intersect(&canvas);
+ if r.is_empty() {
+ continue;
+ }
+ xs.extend([r.x0, r.x1]);
+ ys.extend([r.y0, r.y1]);
+ }
+ xs.sort_unstable();
+ xs.dedup();
+ ys.sort_unstable();
+ ys.dedup();
+ let covered = |x0: i32, y0: i32| taken.iter().any(|r| x0 >= r.x0 && x0 < r.x1 && y0 >= r.y0 && y0 < r.y1);
+ // Horizontal runs per row band.
+ let mut runs: Vec<Rect> = Vec::new();
+ for yw in ys.windows(2) {
+ let mut start: Option<i32> = None;
+ for xw in xs.windows(2) {
+ let free = !covered(xw[0], yw[0]);
+ match (free, start) {
+ (true, None) => start = Some(xw[0]),
+ (false, Some(s)) => {
+ runs.push(Rect::new(s, yw[0], xw[0], yw[1]));
+ start = None;
+ }
+ _ => {}
+ }
+ }
+ if let Some(s) = start {
+ runs.push(Rect::new(s, yw[0], *xs.last().unwrap_or(&canvas.x1), yw[1]));
+ }
+ }
+ // Merge vertically adjacent runs with the same columns.
+ let mut out: Vec<Rect> = Vec::new();
+ for r in runs {
+ if let Some(prev) = out.iter_mut().find(|p| p.x0 == r.x0 && p.x1 == r.x1 && p.y1 == r.y0) {
+ prev.y1 = r.y1;
+ } else {
+ out.push(r);
+ }
+ }
+ out
+}
+
+/// Every slice of `doc` in display order (see [`ResolvedSlice`]). Without user or layer slices
+/// the whole canvas is one auto slice named `<base>` alone (as Photoshop's Save for Web names
+/// it); with several, generated names are numbered `<base>_NN`.
+pub fn resolve(doc: &Document) -> Vec<ResolvedSlice> {
+ let base = base_name(doc);
+ let stored = clipped(doc);
+ let rects: Vec<Rect> = stored.iter().map(|(_, r)| *r).collect();
+ let mut all: Vec<(Option<u32>, Rect)> = stored.iter().map(|(id, r)| (Some(*id), *r)).collect();
+ all.extend(auto_slices(doc.bounds(), &rects).into_iter().map(|r| (None, r)));
+ all.sort_by_key(|(_, r)| (r.y0, r.x0));
+ let single = all.len() == 1;
+ all.into_iter()
+ .enumerate()
+ .map(|(i, (id, rect))| {
+ let s = id.and_then(|id| doc.slices.get(id));
+ let number = i + 1;
+ let name = match s.map(|s| s.name.as_str()).filter(|n| !n.is_empty()) {
+ Some(n) => n.to_string(),
+ None if single => base.clone(),
+ None => format!("{base}_{number:02}"),
+ };
+ ResolvedSlice { number, id, origin: s.map_or(SliceOrigin::Auto, |s| s.origin), rect, name, kind: s.map_or(SliceKind::Image, |s| s.kind) }
+ })
+ .collect()
+}
+
+/// The base of generated slice names: the document name without extension, file-name safe.
+pub fn base_name(doc: &Document) -> String {
+ let n = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a);
+ let s: String = n.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
+ if s.is_empty() { "Untitled".into() } else { s }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{ColorMode, SampleType, Size};
+
+ fn area(rs: &[Rect]) -> i64 {
+ rs.iter().map(|r| i64::from(r.width()) * i64::from(r.height())).sum()
+ }
+
+ #[test]
+ fn auto_slices_tile_the_rest_of_the_canvas() {
+ let canvas = Rect::new(0, 0, 100, 80);
+ let user = [Rect::new(20, 10, 60, 30)];
+ let auto = auto_slices(canvas, &user);
+ assert_eq!(area(&auto) + area(&user), 100 * 80);
+ for (i, a) in auto.iter().enumerate() {
+ assert!(a.intersect(&user[0]).is_empty());
+ for b in &auto[i + 1..] {
+ assert!(a.intersect(b).is_empty(), "{a:?} overlaps {b:?}");
+ }
+ }
+ // Above band, left, right, below band.
+ assert_eq!(auto.len(), 4);
+ assert_eq!(auto[0], Rect::new(0, 0, 100, 10));
+ assert_eq!(auto_slices(canvas, &[]), vec![canvas]);
+ }
+
+ #[test]
+ fn resolve_numbers_top_to_bottom() {
+ let mut d = Document::new("site.psd", Size::new(100, 80), ColorMode::Rgb, SampleType::U8);
+ assert_eq!(resolve(&d).len(), 1);
+ assert_eq!(resolve(&d)[0].name, "site");
+ d.slices.list.push(Slice { id: 1, rect: Rect::new(20, 10, 60, 30), ..Default::default() });
+ let r = resolve(&d);
+ assert_eq!(r.len(), 5);
+ assert_eq!(r[0].name, "site_01");
+ let user = r.iter().find(|s| s.id == Some(1)).unwrap();
+ assert_eq!(user.number, 3, "after the top band and the left cell");
+ assert_eq!(user.origin, SliceOrigin::User);
+ d.slices.list[0].name = "logo".into();
+ assert!(resolve(&d).iter().any(|s| s.name == "logo"));
+ }
+}
diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs
index 4fd5236f1..b0c1b9098 100644
--- a/crates/doc/src/text.rs
+++ b/crates/doc/src/text.rs
@@ -85,6 +85,10 @@ pub struct CharStyle {
pub variations: Vec<FontVariation>,
/// BCP-47 language tag (affects shaping and line breaking).
pub language: Option<String>,
+ /// Applied character style (id in [`crate::TextStyles`]); `None` = "None". Attributes above
+ /// stay fully resolved; differences from the style are local overrides.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub style_sheet: Option<u32>,
}
impl Default for CharStyle {
@@ -113,6 +117,7 @@ impl Default for CharStyle {
features: Vec::new(),
variations: Vec::new(),
language: None,
+ style_sheet: None,
}
}
}
@@ -172,6 +177,9 @@ pub struct ParagraphStyle {
pub auto_leading: f32,
pub direction: TextDirection,
pub hyphenate: bool,
+ /// Applied paragraph style (id in [`crate::TextStyles`]); `None` = Basic Paragraph.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub style_sheet: Option<u32>,
}
impl Default for ParagraphStyle {
@@ -186,6 +194,7 @@ impl Default for ParagraphStyle {
auto_leading: 1.2,
direction: TextDirection::Auto,
hyphenate: false,
+ style_sheet: None,
}
}
}
diff --git a/crates/doc/src/text_styles.rs b/crates/doc/src/text_styles.rs
new file mode 100644
index 000000000..105b65a47
--- /dev/null
+++ b/crates/doc/src/text_styles.rs
@@ -0,0 +1,310 @@
+//! Named type styles (Photoshop's Character Styles and Paragraph Styles panels).
+//!
+//! A document owns a list of **character styles** (partial character attributes) and
+//! **paragraph styles** (partial paragraph *and* character attributes). "None" (no character
+//! style) and "Basic Paragraph" (the default paragraph style, which can be redefined but not
+//! deleted) are implicit.
+//!
+//! Text keeps fully resolved attributes in its runs (so layout never needs the style list). A run
+//! references its styles through [`CharStyle::style_sheet`] (character style id) and the
+//! paragraph's [`ParagraphStyle::style_sheet`] (paragraph style id, `None` = Basic Paragraph).
+//! The attributes a run would have from its styles alone are
+//! `defaults ← Basic Paragraph ← paragraph style ← character style`; whatever differs from that
+//! is a **local override**, shown as "+" after the style name, as in Photoshop.
+//!
+//! Attribute sets are JSON objects keyed by the serde field names of [`CharStyle`] /
+//! [`ParagraphStyle`] (`size_pt`, `font_family`, `align`, …), so a set can name any subset of
+//! the fields and new fields need no extra code.
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value};
+
+use crate::text::{CharStyle, ParagraphStyle};
+
+/// A partial attribute set: serde field name → value.
+pub type StyleAttrs = Map<String, Value>;
+
+/// The key that holds a run's style reference; never part of an attribute set.
+const REF_KEY: &str = "style_sheet";
+
+/// A named character style.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct CharacterStyleDef {
+ /// Stable id (≥ 1), referenced by [`CharStyle::style_sheet`].
+ pub id: u32,
+ pub name: String,
+ /// Character attributes this style sets (others come from the paragraph style).
+ pub attrs: StyleAttrs,
+}
+
+/// A named paragraph style (or Basic Paragraph).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ParagraphStyleDef {
+ /// Stable id (≥ 1; Basic Paragraph is 0), referenced by [`ParagraphStyle::style_sheet`].
+ pub id: u32,
+ pub name: String,
+ /// Paragraph attributes this style sets.
+ pub para_attrs: StyleAttrs,
+ /// Character attributes this style sets (the basis of every run in its paragraphs).
+ pub char_attrs: StyleAttrs,
+}
+
+/// The document's named type styles.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct TextStyles {
+ /// Character styles in panel order ("None" is implicit and first).
+ pub character: Vec<CharacterStyleDef>,
+ /// Paragraph styles in panel order (Basic Paragraph is `basic`, listed first).
+ pub paragraph: Vec<ParagraphStyleDef>,
+ /// Basic Paragraph (id 0). Empty attribute sets = the defaults.
+ pub basic: ParagraphStyleDef,
+ /// Style sheets of the PSD text engine this document was read from (`ResourceDict`
+ /// `StyleSheetSet` / `ParagraphSheetSet`), kept so unmapped data survives a round trip.
+ pub psd_raw: Option<Value>,
+}
+
+/// Name of the implicit default paragraph style.
+pub const BASIC_PARAGRAPH: &str = "Basic Paragraph";
+/// Name of the implicit "no character style" entry.
+pub const NO_CHARACTER_STYLE: &str = "None";
+
+impl Default for TextStyles {
+ fn default() -> Self {
+ Self {
+ character: Vec::new(),
+ paragraph: Vec::new(),
+ basic: ParagraphStyleDef { id: 0, name: BASIC_PARAGRAPH.into(), ..Default::default() },
+ psd_raw: None,
+ }
+ }
+}
+
+/// Serializes a style to its JSON object (without the style reference).
+fn object<T: Serialize>(s: &T) -> StyleAttrs {
+ match serde_json::to_value(s) {
+ Ok(Value::Object(mut m)) => {
+ m.remove(REF_KEY);
+ m
+ }
+ _ => Map::new(),
+ }
+}
+
+/// `base` with `attrs` applied. Fails if an attribute has the wrong type.
+pub fn apply_attrs<T: Serialize + serde::de::DeserializeOwned>(base: &T, attrs: &StyleAttrs) -> Result<T, String> {
+ if attrs.is_empty() {
+ return serde_json::from_value(serde_json::to_value(base).map_err(|e| e.to_string())?).map_err(|e| e.to_string());
+ }
+ let mut v = serde_json::to_value(base).map_err(|e| e.to_string())?;
+ let Value::Object(m) = &mut v else { return Err("style is not an object".into()) };
+ for (k, x) in attrs {
+ if k == REF_KEY {
+ continue;
+ }
+ if !m.contains_key(k) {
+ return Err(format!("unknown style attribute {k:?}"));
+ }
+ m.insert(k.clone(), x.clone());
+ }
+ serde_json::from_value(v).map_err(|e| e.to_string())
+}
+
+/// Attributes of `style` that differ from `base` (the style reference is ignored).
+pub fn diff_attrs<T: Serialize>(style: &T, base: &T) -> StyleAttrs {
+ let (a, b) = (object(style), object(base));
+ a.into_iter().filter(|(k, v)| b.get(k) != Some(v)).collect()
+}
+
+/// Every attribute of a character style (a full set, for "redefine from text").
+pub fn char_attrs(s: &CharStyle) -> StyleAttrs {
+ object(s)
+}
+
+/// Every attribute of a paragraph style.
+pub fn para_attrs(s: &ParagraphStyle) -> StyleAttrs {
+ object(s)
+}
+
+/// Checks that `attrs` only names fields of `T` with values of the right type.
+pub fn validate<T: Serialize + serde::de::DeserializeOwned + Default>(attrs: &StyleAttrs) -> Result<(), String> {
+ apply_attrs(&T::default(), attrs).map(|_| ())
+}
+
+impl TextStyles {
+ pub fn is_empty(&self) -> bool {
+ self.character.is_empty() && self.paragraph.is_empty() && self.basic.char_attrs.is_empty() && self.basic.para_attrs.is_empty()
+ }
+
+ pub fn char_style(&self, id: u32) -> Option<&CharacterStyleDef> {
+ self.character.iter().find(|s| s.id == id)
+ }
+
+ pub fn char_style_mut(&mut self, id: u32) -> Option<&mut CharacterStyleDef> {
+ self.character.iter_mut().find(|s| s.id == id)
+ }
+
+ /// Paragraph style by id (0 = Basic Paragraph).
+ pub fn para_style(&self, id: u32) -> Option<&ParagraphStyleDef> {
+ if id == 0 { Some(&self.basic) } else { self.paragraph.iter().find(|s| s.id == id) }
+ }
+
+ pub fn para_style_mut(&mut self, id: u32) -> Option<&mut ParagraphStyleDef> {
+ if id == 0 { Some(&mut self.basic) } else { self.paragraph.iter_mut().find(|s| s.id == id) }
+ }
+
+ /// A fresh character style id.
+ pub fn next_char_id(&self) -> u32 {
+ self.character.iter().map(|s| s.id).max().unwrap_or(0) + 1
+ }
+
+ /// A fresh paragraph style id.
+ pub fn next_para_id(&self) -> u32 {
+ self.paragraph.iter().map(|s| s.id).max().unwrap_or(0) + 1
+ }
+
+ /// "Character Style N" / "Paragraph Style N" with the first unused N.
+ pub fn unique_name(&self, paragraph: bool, base: &str) -> String {
+ let taken = |n: &str| {
+ if paragraph {
+ n == BASIC_PARAGRAPH || self.paragraph.iter().any(|s| s.name == n)
+ } else {
+ n == NO_CHARACTER_STYLE || self.character.iter().any(|s| s.name == n)
+ }
+ };
+ (1..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default()
+ }
+
+ /// Paragraph attributes from Basic Paragraph and `para` (a missing id falls back to Basic
+ /// Paragraph). The result references `para`.
+ pub fn resolve_para(&self, para: Option<u32>) -> ParagraphStyle {
+ let mut s = apply_attrs(&ParagraphStyle::default(), &self.basic.para_attrs).unwrap_or_default();
+ if let Some(def) = para.and_then(|id| self.para_style(id)) {
+ s = apply_attrs(&s, &def.para_attrs).unwrap_or(s);
+ }
+ s.style_sheet = para.filter(|id| *id != 0 && self.para_style(*id).is_some());
+ s
+ }
+
+ /// Character attributes a run gets from its styles alone: defaults (with `default_family`
+ /// for an unset family) ← Basic Paragraph ← paragraph style ← character style. The result
+ /// references `chr`.
+ pub fn resolve_char(&self, para: Option<u32>, chr: Option<u32>, default_family: &str) -> CharStyle {
+ let base = CharStyle { font_family: default_family.to_string(), ..Default::default() };
+ let mut s = apply_attrs(&base, &self.basic.char_attrs).unwrap_or(base);
+ if let Some(def) = para.and_then(|id| self.para_style(id)).filter(|d| d.id != 0) {
+ s = apply_attrs(&s, &def.char_attrs).unwrap_or(s);
+ }
+ let chr = chr.filter(|id| self.char_style(*id).is_some());
+ if let Some(def) = chr.and_then(|id| self.char_style(id)) {
+ s = apply_attrs(&s, &def.attrs).unwrap_or(s);
+ }
+ s.style_sheet = chr;
+ s
+ }
+
+ /// The local overrides of a run (attributes that differ from its styles).
+ pub fn char_overrides(&self, run: &CharStyle, para: Option<u32>, default_family: &str) -> StyleAttrs {
+ let base = self.resolve_char(para, run.style_sheet, default_family);
+ diff_attrs(run, &base)
+ }
+
+ /// The local overrides of a paragraph.
+ pub fn para_overrides(&self, p: &ParagraphStyle) -> StyleAttrs {
+ diff_attrs(p, &self.resolve_para(p.style_sheet))
+ }
+
+ /// Re-resolves a run against (possibly changed) styles, keeping its overrides: `old` gives
+ /// the styles as they were when the overrides were made.
+ pub fn restyle_char(&self, old: &TextStyles, run: &CharStyle, old_para: Option<u32>, new_para: Option<u32>, new_chr: Option<u32>, family: &str) -> CharStyle {
+ let overrides = old.char_overrides(run, old_para, family);
+ let base = self.resolve_char(new_para, new_chr, family);
+ apply_attrs(&base, &overrides).unwrap_or(base)
+ }
+
+ /// Re-resolves a paragraph against (possibly changed) styles, keeping its overrides.
+ pub fn restyle_para(&self, old: &TextStyles, p: &ParagraphStyle, new_para: Option<u32>) -> ParagraphStyle {
+ let overrides = old.para_overrides(p);
+ let base = self.resolve_para(new_para);
+ let mut s = apply_attrs(&base, &overrides).unwrap_or(base);
+ s.style_sheet = new_para.filter(|id| *id != 0 && self.para_style(*id).is_some());
+ s
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::text::TextAlign;
+ use serde_json::json;
+
+ fn attrs(v: Value) -> StyleAttrs {
+ v.as_object().unwrap().clone()
+ }
+
+ fn styles() -> TextStyles {
+ let mut s = TextStyles::default();
+ s.character.push(CharacterStyleDef { id: 1, name: "Big".into(), attrs: attrs(json!({"size_pt": 40.0, "underline": true})) });
+ s.paragraph.push(ParagraphStyleDef { id: 1, name: "Head".into(), para_attrs: attrs(json!({"align": "Center"})), char_attrs: attrs(json!({"size_pt": 20.0, "weight": 700})) });
+ s
+ }
+
+ #[test]
+ fn resolution_layers_styles() {
+ let s = styles();
+ let none = s.resolve_char(None, None, "Inter");
+ assert_eq!((none.font_family.as_str(), none.size_pt, none.style_sheet), ("Inter", 12.0, None));
+ let head = s.resolve_char(Some(1), None, "Inter");
+ assert_eq!((head.size_pt, head.weight), (20.0, 700));
+ let big = s.resolve_char(Some(1), Some(1), "Inter");
+ assert_eq!((big.size_pt, big.weight, big.underline, big.style_sheet), (40.0, 700, true, Some(1)));
+ // Missing ids fall back.
+ assert_eq!(s.resolve_char(Some(9), Some(9), "Inter").style_sheet, None);
+ let p = s.resolve_para(Some(1));
+ assert_eq!((p.align, p.style_sheet), (TextAlign::Center, Some(1)));
+ assert_eq!(s.resolve_para(None).align, TextAlign::Left);
+ }
+
+ #[test]
+ fn overrides_survive_restyling() {
+ let old = styles();
+ let mut run = old.resolve_char(None, Some(1), "Inter");
+ assert!(old.char_overrides(&run, None, "Inter").is_empty());
+ run.italic = true;
+ let ov = old.char_overrides(&run, None, "Inter");
+ assert_eq!(ov, attrs(json!({"italic": true})));
+ // Redefine "Big" to 50 pt: the run follows and keeps its italic override.
+ let mut new = old.clone();
+ new.char_style_mut(1).unwrap().attrs.insert("size_pt".into(), json!(50.0));
+ let r = new.restyle_char(&old, &run, None, None, Some(1), "Inter");
+ assert_eq!((r.size_pt, r.italic, r.underline), (50.0, true, true));
+ // Clearing the character style keeps overrides on the paragraph basis.
+ let r = new.restyle_char(&old, &run, None, None, None, "Inter");
+ assert_eq!((r.size_pt, r.italic, r.underline, r.style_sheet), (12.0, true, false, None));
+ }
+
+ #[test]
+ fn attrs_validate_and_diff() {
+ assert!(validate::<CharStyle>(&attrs(json!({"size_pt": 3.0}))).is_ok());
+ assert!(validate::<CharStyle>(&attrs(json!({"size_pt": "big"}))).is_err());
+ assert!(validate::<CharStyle>(&attrs(json!({"nope": 1}))).is_err());
+ let a = CharStyle { size_pt: 30.0, style_sheet: Some(3), ..Default::default() };
+ assert_eq!(diff_attrs(&a, &CharStyle::default()), attrs(json!({"size_pt": 30.0})));
+ assert!(!char_attrs(&a).contains_key("style_sheet"));
+ }
+
+ #[test]
+ fn names_and_ids() {
+ let s = styles();
+ assert_eq!(s.unique_name(false, "Character Style"), "Character Style 1");
+ assert_eq!((s.next_char_id(), s.next_para_id()), (2, 2));
+ assert_eq!(s.para_style(0).unwrap().name, BASIC_PARAGRAPH);
+ let v = serde_json::to_value(&s).unwrap();
+ let back: TextStyles = serde_json::from_value(v).unwrap();
+ assert_eq!(back, s);
+ let empty: TextStyles = serde_json::from_str("{}").unwrap();
+ assert_eq!(empty.basic.name, BASIC_PARAGRAPH);
+ }
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 6a2b7d3b1..5c05f3108 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -18,6 +18,7 @@ photocraft-compose = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+rayon = { workspace = true }
photocraft-paint = { workspace = true }
photocraft-algo = { workspace = true }
photocraft-text = { workspace = true }
@@ -25,3 +26,5 @@ photocraft-vector = { workspace = true }
photocraft-io = { workspace = true }
photocraft-format = { workspace = true }
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
+photocraft-codecs = { workspace = true }
+flate2 = { workspace = true }
diff --git a/crates/engine/examples/bench_web.rs b/crates/engine/examples/bench_web.rs
new file mode 100644
index 000000000..bcd4e0e8e
--- /dev/null
+++ b/crates/engine/examples/bench_web.rs
@@ -0,0 +1,48 @@
+//! Timing: File › Export › Save for Web (Legacy) and File › Print on a 6000×4000 (24 MP) image.
+//! `cargo run --release -p photocraft-engine --example bench_web [width] [height]`
+//!
+//! Each line is one full command (flatten, sRGB, quantise/encode), estimate-only (no file).
+use std::time::Instant;
+
+use photocraft_engine::Session;
+use photocraft_geom::Rect;
+use serde_json::json;
+
+fn main() {
+ let w: i32 = std::env::args().nth(1).and_then(|v| v.parse().ok()).unwrap_or(6000);
+ let h: i32 = std::env::args().nth(2).and_then(|v| v.parse().ok()).unwrap_or(4000);
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": w, "height": h})).unwrap();
+ s.edit("texture", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ let fmt = surf.format();
+ let mut data = Vec::with_capacity(w as usize * h as usize * 4);
+ for y in 0..h {
+ for x in 0..w {
+ let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) as u32 % 1000) as f32 / 1000.0 * 0.06;
+ data.extend(photocraft_raster::from_rgba(&fmt, [x as f32 / w as f32 + n, 0.5 + ((x + y) as f32 * 0.002).sin() * 0.3, y as f32 / h as f32, 1.0]));
+ }
+ }
+ surf.write_region(Rect::new(0, 0, w, h), &data);
+ Ok(())
+ })
+ .unwrap();
+ for (label, p) in [
+ ("GIF 128 no dither", json!({"format": "gif", "colors": 128, "dither": "none"})),
+ ("GIF 128 pattern", json!({"format": "gif", "colors": 128, "dither": "pattern"})),
+ ("GIF 128 diffusion", json!({"format": "gif", "colors": 128, "dither": "diffusion"})),
+ ("PNG-8 64 no dither", json!({"format": "png8", "colors": 64, "dither": "none"})),
+ ("PNG-24", json!({"format": "png24"})),
+ ("JPEG 60", json!({"format": "jpeg", "quality": 60})),
+ ("JPEG 60 progressive", json!({"format": "jpeg", "quality": 60, "progressive": true})),
+ ("WBMP diffusion", json!({"format": "wbmp"})),
+ ] {
+ let t = Instant::now();
+ let r = s.execute("file.export.saveForWebLegacy", p).unwrap();
+ println!("{label:24} {:8.0} ms {:>10} bytes", t.elapsed().as_secs_f64() * 1000.0, r["bytes"]);
+ }
+ let t = Instant::now();
+ let r = s.execute("file.print", json!({"dryRun": true, "scaleToFit": true})).unwrap();
+ println!("{:24} {:8.0} ms {:>10} bytes", "Print (PDF, dry run)", t.elapsed().as_secs_f64() * 1000.0, r["bytes"]);
+ let _ = std::fs::remove_file(r["pdf"].as_str().unwrap_or_default());
+}
diff --git a/crates/engine/src/align_cmds.rs b/crates/engine/src/align_cmds.rs
index fb6059a95..afdcbce4a 100644
--- a/crates/engine/src/align_cmds.rs
+++ b/crates/engine/src/align_cmds.rs
@@ -1,30 +1,30 @@
//! Edit › Auto-Align Layers and Auto-Blend Layers, on the selected pixel layers.
//!
-//! Auto-Align registers every selected layer onto a reference layer with Harris corners,
-//! steered-BRIEF descriptors and RANSAC ([`photocraft_algo::features`]) and warps it with the
-//! Free Transform resampler. Projections: Reposition (translation), Collage (rotation, uniform
-//! scale, translation), Perspective (homography) and Auto (perspective when it is well
-//! supported, otherwise collage). Cylindrical and spherical projections are not implemented.
+//! Both share Photomerge's registration and blending ([`photocraft_algo::panorama`] via
+//! `photo_cmds`). Auto-Align matches Harris / steered-BRIEF features between every pair of
+//! layers, chains the verified pairs from the reference layer (maximum spanning tree) and
+//! bundle-adjusts all of them, then warps each layer. Projections: Auto, Perspective
+//! (homography), Cylindrical and Spherical (rigid motion on the cylinder / sphere, focal length
+//! from the homographies or EXIF), Collage (similarity) and Reposition (translation). The
+//! reference stays put in the planar projections.
//!
//! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest
-//! layer (Stack Images, for focus stacking) or the layer whose content the pixel lies deepest in
-//! (Panorama). With Seamless Tones and Colors it also adds a merged layer blended with Laplacian
-//! pyramids ([`photocraft_algo::pyramid`]) so transitions are invisible.
+//! layer (Stack Images, for focus stacking) or one layer per region with seams routed where the
+//! layers agree (Panorama). With Seamless Tones and Colors it also adds a merged layer blended
+//! with Laplacian pyramids so transitions are invisible.
-use photocraft_algo::features::{Model, register};
+use photocraft_algo::panorama::Layout;
use photocraft_algo::pyramid;
-use photocraft_algo::transform::{Homography, Interp, warp_surface};
+use photocraft_algo::transform::Interp;
use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask};
use photocraft_geom::Rect;
use photocraft_raster::{Surface, to_rgba};
use serde_json::{Value, json};
use crate::commands::CommandSpec;
+use crate::photo_cmds::{plane_matrix, register, seam_blend, seam_order, warp_placed};
use crate::{EngineError, Result, Session};
-/// Longest side images are registered at (larger layers are downsampled for detection).
-const REGISTER_SIDE: usize = 1024;
-
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
@@ -40,30 +40,6 @@ fn two_layers(s: &Session) -> std::result::Result<(), String> {
if selected_pixel_layers(s).len() < 2 { Err("select two or more pixel layers in the Layers panel".into()) } else { Ok(()) }
}
-/// Luminance and opacity of a surface over `area`, downsampled by the integer factor `k`.
-fn luma_alpha(surf: &Surface, area: Rect, k: usize) -> (usize, usize, Vec<f32>, Vec<f32>) {
- let fmt = surf.format();
- let n = fmt.channels();
- let raw = surf.read_region(area);
- let (w, h) = (area.width() as usize, area.height() as usize);
- let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
- let (mut l, mut a, mut cnt) = (vec![0.0f32; sw * sh], vec![0.0f32; sw * sh], vec![0.0f32; sw * sh]);
- for y in 0..h {
- for x in 0..w {
- let p = to_rgba(&fmt, &raw[(y * w + x) * n..(y * w + x + 1) * n]);
- let i = (y / k) * sw + x / k;
- l[i] += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2];
- a[i] += p[3];
- cnt[i] += 1.0;
- }
- }
- for i in 0..sw * sh {
- l[i] /= cnt[i].max(1.0);
- a[i] /= cnt[i].max(1.0);
- }
- (sw, sh, l, a)
-}
-
fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "edit.autoAlignLayers";
let ids = selected_pixel_layers(s);
@@ -71,14 +47,7 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "select two or more pixel layers"));
}
let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto");
- let models: Vec<Model> = match projection {
- "auto" => vec![Model::Homography, Model::Similarity, Model::Translation],
- "perspective" => vec![Model::Homography],
- "collage" => vec![Model::Similarity],
- "reposition" => vec![Model::Translation],
- "cylindrical" | "spherical" => return Err(bad(cmd, format!("the {projection} projection is not supported (auto|perspective|collage|reposition)"))),
- other => return Err(bad(cmd, format!("unknown projection `{other}` (auto|perspective|collage|reposition)"))),
- };
+ let layout = Layout::parse(projection).ok_or_else(|| bad(cmd, format!("unknown projection `{projection}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let doc = st.doc.clone();
let reference = match p.get("reference").and_then(Value::as_u64) {
@@ -86,71 +55,68 @@ fn auto_align(s: &mut Session, p: &Value) -> Result<Value> {
Some(r) => return Err(bad(cmd, format!("reference {r} is not a selected pixel layer"))),
None => ids[0],
};
+ let ref_idx = ids.iter().position(|i| *i == reference).unwrap_or(0);
let area = doc.bounds();
- let k = (area.width().max(area.height()) as usize).div_ceil(REGISTER_SIDE).max(1);
- let prep = |id: LayerId| -> Option<(usize, usize, Vec<f32>, Vec<bool>)> {
- let surf = doc.layer(id)?.surface()?;
- let (w, h, l, a) = luma_alpha(surf, area, k);
- Some((w, h, l, a.iter().map(|v| *v > 0.5).collect()))
- };
- let (w, h, ref_l, ref_ok) = prep(reference).ok_or(EngineError::NoLayer(reference))?;
- let scale = k as f64;
- let mut moves: Vec<(LayerId, Homography, &'static str, usize)> = Vec::new();
- let mut failed: Vec<u64> = Vec::new();
- for &id in ids.iter().filter(|id| **id != reference) {
- let Some((_, _, l, ok)) = prep(id) else { continue };
- let mut found = None;
- for &m in &models {
- if let Some((hm, n)) = register(w, h, &ref_l, &l, Some(&ref_ok), Some(&ok), m) {
- // Auto: a perspective fit must be well supported and not wildly projective.
- let wild = m == Model::Homography && (hm.0[6].abs() + hm.0[7].abs()) * (w.max(h) as f64) > 0.5;
- if projection == "auto" && m == Model::Homography && (n < 20 || wild) {
- continue;
- }
- found = Some((hm, m, n));
- break;
- }
- }
- match found {
- Some((hm, m, n)) => {
- // Registration ran on a k× downsampled grid: conjugate by the scale.
- let up = Homography([scale, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 1.0]);
- let down = Homography([1.0 / scale, 0.0, 0.0, 0.0, 1.0 / scale, 0.0, 0.0, 0.0, 1.0]);
- let full = up.mul(&hm).mul(&down);
- let name = match m {
- Model::Translation => "reposition",
- Model::Similarity => "collage",
- Model::Homography => "perspective",
- };
- moves.push((id, full, name, n));
- }
- None => failed.push(id.0),
- }
+ let surfs: Vec<&Surface> = ids.iter().map(|id| doc.layer(*id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*id))).collect::<Result<_>>()?;
+ let images: Vec<(&Surface, Rect)> = surfs.iter().map(|s| (*s, area)).collect();
+ let focal35 = doc.metadata.exif.as_ref().and_then(|e| photocraft_algo::exif::read(e).focal_length_35mm);
+ let geometric = p.get("geometricCorrection").and_then(Value::as_bool).unwrap_or(false);
+ let al = register(&images, layout, Some(ref_idx), geometric, focal35).ok_or_else(|| EngineError::Other("Auto-Align couldn't find enough matching detail between the layers".into()))?;
+ let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));
+ let planar = matches!(al.layout, Layout::Perspective | Layout::Collage | Layout::Reposition);
+ let mut inliers = vec![0usize; ids.len()];
+ for &(a, b, n) in &al.pairs {
+ inliers[a] += n;
+ inliers[b] += n;
}
+ // Everything but the reference moves in planar layouts; every layer is reprojected otherwise.
+ let moves: Vec<usize> = (0..ids.len()).filter(|&i| al.placements[i].is_some() && (i != ref_idx || !planar)).collect();
+ let failed: Vec<u64> = (0..ids.len()).filter(|&i| al.placements[i].is_none()).map(|i| ids[i].0).collect();
if moves.is_empty() {
return Err(EngineError::Other("Auto-Align couldn't find enough matching detail between the layers".into()));
}
- let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));
+ let warped: Vec<(LayerId, Surface, Option<Surface>)> = moves
+ .iter()
+ .map(|&i| {
+ let pl = al.placements[i].as_ref().expect("placed");
+ let l = doc.layer(ids[i]).expect("exists");
+ let surf = l.surface().expect("raster");
+ let b = surf.content_bounds();
+ let px = if b.is_empty() { surf.clone() } else { warp_placed(surf, b, (0.0, 0.0), pl, (0.0, 0.0), interp) };
+ let mask = l.mask.as_ref().map(|m| {
+ let mb = m.surface.content_bounds();
+ if mb.is_empty() { m.surface.clone() } else { warp_placed(&m.surface, mb, (0.0, 0.0), pl, (0.0, 0.0), Interp::Bilinear) }
+ });
+ (ids[i], px, mask)
+ })
+ .collect();
s.edit("Auto-Align Layers", |doc, _| {
- for (id, hm, _, _) in &moves {
+ for (id, px, mask) in &warped {
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
- let surf = l.surface_mut().ok_or(EngineError::NoLayer(*id))?;
- let b = surf.content_bounds();
- if b.is_empty() {
- continue;
+ if let Some(surf) = l.surface_mut() {
+ *surf = px.clone();
}
- *surf = warp_surface(surf, b, hm, interp);
- if let Some(m) = &mut l.mask {
- let mb = m.surface.content_bounds();
- if !mb.is_empty() {
- m.surface = warp_surface(&m.surface, mb, hm, Interp::Bilinear);
- }
+ if let (Some(m), Some(ms)) = (&mut l.mask, mask) {
+ m.surface = ms.clone();
}
}
Ok(())
})?;
- let aligned: Vec<Value> = moves.iter().map(|(id, hm, model, n)| json!({"layer": id.0, "model": model, "matches": n, "matrix": hm.0})).collect();
- Ok(json!({"reference": reference.0, "aligned": aligned, "failed": failed}))
+ let model = match al.layout {
+ Layout::Reposition => "reposition",
+ Layout::Collage => "collage",
+ Layout::Perspective | Layout::Auto => "perspective",
+ Layout::Cylindrical => "cylindrical",
+ Layout::Spherical => "spherical",
+ };
+ let aligned: Vec<Value> = moves
+ .iter()
+ .map(|&i| {
+ let pl = al.placements[i].as_ref().expect("placed");
+ json!({"layer": ids[i].0, "model": model, "matches": inliers[i], "matrix": plane_matrix(pl, (0.0, 0.0)).map(|h| h.0.to_vec())})
+ })
+ .collect();
+ Ok(json!({"reference": reference.0, "layout": al.layout.name(), "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed}))
}
/// Native-channel pixels of a layer over `area` (transparent outside its content).
@@ -206,11 +172,22 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
alpha.push(av);
}
let fmt = fmt.ok_or(EngineError::NoDocument)?;
- let weights = if method == "stack" { pyramid::stack_weights(w, h, &luma, &alpha) } else { pyramid::panorama_weights(w, h, &alpha) };
- let blended = seamless.then(|| {
- let refs: Vec<&[f32]> = imgs.iter().map(Vec::as_slice).collect();
- pyramid::blend(w, h, fmt.channels(), &refs, &weights, pyramid::auto_levels(w, h))
- });
+ let (weights, blended) = if method == "stack" {
+ let weights = pyramid::stack_weights(w, h, &luma, &alpha);
+ let blended = seamless.then(|| {
+ let refs: Vec<&[f32]> = imgs.iter().map(Vec::as_slice).collect();
+ pyramid::blend(w, h, fmt.channels(), &refs, &weights, pyramid::auto_levels(w, h))
+ });
+ (weights, blended)
+ } else {
+ // Panorama: seams routed through agreement, multi-band blended (photo_cmds).
+ let surfs: Vec<Surface> = ids.iter().map(|id| doc.layer(*id).and_then(|l| l.surface()).cloned().ok_or(EngineError::NoLayer(*id))).collect::<Result<_>>()?;
+ let order = seam_order(&surfs, 0);
+ let b = seam_blend(&surfs, area, &order, seamless, false, None);
+ let weights: Vec<Vec<f32>> = b.layers.iter().map(|(_, m)| m.read_region(area)).collect();
+ let blended = seamless.then(|| b.composite.read_region(area));
+ (weights, blended)
+ };
let top = *ids.last().expect("two or more");
let label = "Auto-Blend Layers";
let new_layer = s.edit(label, |doc, active| {
@@ -242,7 +219,7 @@ macro_rules! spec {
pub fn specs() -> Vec<CommandSpec> {
vec![
- spec!("edit.autoAlignLayers", "Auto-Align Layers…", r##"{"projection":"auto|perspective|collage|reposition","reference":layer id?=bottom selected layer,"interpolation":"bicubic|bilinear|nearest"}"##, auto_align),
+ spec!("edit.autoAlignLayers", "Auto-Align Layers…", r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest"}"##, auto_align),
spec!("edit.autoBlendLayers", "Auto-Blend Layers…", r##"{"method":"panorama|stack","seamlessTones":bool=true}"##, auto_blend),
]
}
@@ -311,7 +288,7 @@ mod tests {
let r = s.execute("edit.autoAlignLayers", json!({})).unwrap();
let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}");
- assert!(s.execute("edit.autoAlignLayers", json!({"projection": "cylindrical"})).is_err());
+ assert!(s.execute("edit.autoAlignLayers", json!({"projection": "sideways"})).is_err());
assert!(s.execute("edit.autoAlignLayers", json!({"reference": 9999})).is_err());
}
diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs
new file mode 100644
index 000000000..56d8ecb9f
--- /dev/null
+++ b/crates/engine/src/analysis_cmds.rs
@@ -0,0 +1,1119 @@
+//! Image › Analysis: measurement scale, data points, Record Measurements and the Measurement
+//! Log, the Ruler tool (with protractor and Straighten Layer), the Count tool and Place Scale
+//! Marker.
+//!
+//! The scale, count groups and ruler line are document data ([`photocraft_doc::Measurement`],
+//! saved in `.pcraft`; the scale also as PSD resource 1074). The Measurement Log and the data
+//! point choices are session-wide, as in Photoshop.
+//!
+//! Selection measurements follow Photoshop's definitions: the selection (coverage ≥ 50 %) is
+//! split into 8-connected features, each recorded with a summary row first. Area is the pixel
+//! count, perimeter the length of the marching-squares contour through the pixel-centre grid
+//! (exact along straight edges, √2 per diagonal step), circularity 4π·area/perimeter², gray
+//! values the luminosity (0.30 R + 0.59 G + 0.11 B) of the composite in the document's value
+//! range (0–255 at 8 bits, 0–32768 at 16 bits, 0–1 at 32 bits), integrated density area × mean.
+//! Lengths and areas are scaled by the measurement scale.
+
+use std::sync::Arc;
+
+use photocraft_color::{Color, SampleType};
+use photocraft_doc::{CountGroup, Document, Layer, MeasurementScale, Ruler};
+use photocraft_geom::Rect;
+use rayon::prelude::*;
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+// ------------------------------------------------------------------ state
+
+/// Data point columns: (key, Photoshop column header).
+pub const COLUMNS: &[(&str, &str)] = &[
+ ("label", "Label"),
+ ("dateTime", "Date and Time"),
+ ("document", "Document"),
+ ("source", "Source"),
+ ("scale", "Scale"),
+ ("scaleUnits", "Scale Units"),
+ ("scaleFactor", "Scale Factor"),
+ ("count", "Count"),
+ ("area", "Area"),
+ ("perimeter", "Perimeter"),
+ ("circularity", "Circularity"),
+ ("height", "Height"),
+ ("width", "Width"),
+ ("grayMin", "Gray Value (Minimum)"),
+ ("grayMax", "Gray Value (Maximum)"),
+ ("grayMean", "Gray Value (Mean)"),
+ ("grayMedian", "Gray Value (Median)"),
+ ("integratedDensity", "Integrated Density"),
+ ("histogram", "Histogram"),
+ ("length", "Length"),
+ ("angle", "Angle"),
+];
+
+const COMMON: &[&str] = &["label", "dateTime", "document", "source", "scale", "scaleUnits", "scaleFactor"];
+const SELECTION_ONLY: &[&str] = &["count", "area", "perimeter", "circularity", "height", "width", "grayMin", "grayMax", "grayMean", "grayMedian", "integratedDensity", "histogram"];
+const RULER_ONLY: &[&str] = &["length", "angle"];
+const COUNT_ONLY: &[&str] = &["count"];
+
+/// Data points a measurement source can record.
+pub fn available(source: &str) -> Vec<&'static str> {
+ let extra = match source {
+ "selection" => SELECTION_ONLY,
+ "ruler" => RULER_ONLY,
+ _ => COUNT_ONLY,
+ };
+ COMMON.iter().chain(extra).copied().collect()
+}
+
+/// Image › Analysis › Select Data Points: what Record Measurements writes per source.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct DataPoints {
+ pub selection: Vec<String>,
+ pub ruler: Vec<String>,
+ pub count: Vec<String>,
+}
+
+impl Default for DataPoints {
+ fn default() -> Self {
+ let all = |s| available(s).into_iter().map(String::from).collect();
+ Self { selection: all("selection"), ruler: all("ruler"), count: all("count") }
+ }
+}
+
+impl DataPoints {
+ fn of(&self, source: &str) -> &[String] {
+ match source {
+ "selection" => &self.selection,
+ "ruler" => &self.ruler,
+ _ => &self.count,
+ }
+ }
+ fn of_mut(&mut self, source: &str) -> &mut Vec<String> {
+ match source {
+ "selection" => &mut self.selection,
+ "ruler" => &mut self.ruler,
+ _ => &mut self.count,
+ }
+ }
+}
+
+/// One Measurement Log row.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct LogRow {
+ pub id: u64,
+ /// Data point values by key (see [`COLUMNS`]).
+ pub values: Map<String, Value>,
+}
+
+/// Session-wide analysis state (`Session::analysis`).
+#[derive(Clone, Debug, Default)]
+pub struct AnalysisState {
+ pub log: Vec<LogRow>,
+ next_row: u64,
+ /// Counter for "Measurement N" labels.
+ next_measurement: u64,
+ pub data_points: DataPoints,
+}
+
+// ------------------------------------------------------------------ helpers
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+fn has_ruler(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ s.active().and_then(|d| d.doc.measurement.ruler).map(|_| ()).ok_or_else(|| "no ruler line".into())
+}
+
+fn has_log(s: &Session) -> std::result::Result<(), String> {
+ if s.analysis.log.is_empty() { Err("the Measurement Log is empty".into()) } else { Ok(()) }
+}
+
+fn point(v: Option<&Value>) -> Option<[f64; 2]> {
+ let a = v?.as_array()?;
+ Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])
+}
+
+fn xy(p: &Value) -> Option<[f64; 2]> {
+ Some([p.get("x")?.as_f64()?, p.get("y")?.as_f64()?])
+}
+
+fn doc(s: &Session) -> Result<Arc<Document>> {
+ Ok(s.active().ok_or(EngineError::NoDocument)?.doc.clone())
+}
+
+/// Change the document without a history step (ruler line: view-like state that is still saved
+/// with the document). A clean document stays clean.
+fn set_quiet(s: &mut Session, f: impl FnOnce(&mut Document)) -> Result<()> {
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ let mut d = (*st.doc).clone();
+ f(&mut d);
+ st.doc = Arc::new(d);
+ let clean = st.saved_revision == st.revision;
+ st.revision += 1;
+ if clean {
+ st.saved_revision = st.revision;
+ }
+ st.last_damage = Some(Rect::EMPTY);
+ Ok(())
+}
+
+/// Run several commands as one history step labelled `label`.
+fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<R>) -> Result<R> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let (before, history) = (st.doc.clone(), st.history.clone());
+ let r = f(s);
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ st.history = history;
+ match r {
+ Ok(v) => {
+ st.history.record(label, before);
+ st.coalesce = None;
+ Ok(v)
+ }
+ Err(e) => {
+ st.doc = before;
+ st.revision += 1;
+ st.last_damage = None;
+ Err(e)
+ }
+ }
+}
+
+/// Current time as ISO 8601 UTC (`2026-10-01T12:34:56Z`); empty on the web (no clock).
+pub fn now_iso() -> String {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
+ let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
+ // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z - era * 146_097;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let y = yoe + era * 400 + i64::from(m <= 2);
+ format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ String::new()
+ }
+}
+
+fn round4(v: f64) -> f64 {
+ (v * 10_000.0).round() / 10_000.0
+}
+
+// ------------------------------------------------------------------ scale
+
+fn set_scale(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.analysis.setMeasurementScale";
+ let cur = doc(s)?.measurement.scale.clone();
+ let preset = p.get("preset").and_then(Value::as_str).unwrap_or(if p.as_object().is_none_or(|o| o.is_empty()) { "query" } else { "custom" });
+ let next = match preset {
+ "query" => return Ok(scale_json(&cur)),
+ "default" => MeasurementScale::default(),
+ "custom" => {
+ let pl = p.get("pixelLength").and_then(Value::as_f64).unwrap_or(cur.pixel_length);
+ let ll = p.get("logicalLength").and_then(Value::as_f64).unwrap_or(cur.logical_length);
+ let units = p.get("units").or_else(|| p.get("logicalUnits")).and_then(Value::as_str).map(str::to_string).unwrap_or(cur.units.clone());
+ if !(pl > 0.0 && pl.is_finite() && ll > 0.0 && ll.is_finite()) {
+ return Err(bad(CMD, "pixelLength and logicalLength must be positive"));
+ }
+ if units.trim().is_empty() {
+ return Err(bad(CMD, "units must not be empty"));
+ }
+ MeasurementScale { pixel_length: pl, logical_length: ll, units }
+ }
+ other => return Err(bad(CMD, format!("unknown preset `{other}` (default|custom)"))),
+ };
+ if next != cur {
+ let n = next.clone();
+ s.edit("Set Measurement Scale", move |d, _| {
+ d.measurement.scale = n;
+ Ok(())
+ })?;
+ }
+ Ok(scale_json(&next))
+}
+
+fn scale_json(sc: &MeasurementScale) -> Value {
+ json!({"pixelLength": sc.pixel_length, "logicalLength": sc.logical_length, "units": sc.units, "factor": sc.factor(), "text": sc.describe(), "default": sc.is_default()})
+}
+
+// ------------------------------------------------------------------ data points
+
+fn select_data_points(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.analysis.selectDataPoints";
+ let mut next = if p.get("reset").and_then(Value::as_bool) == Some(true) { DataPoints::default() } else { s.analysis.data_points.clone() };
+ for source in ["selection", "ruler", "count"] {
+ let avail = available(source);
+ let Some(v) = p.get(source) else { continue };
+ let list = next.of_mut(source);
+ match v {
+ // A full list of keys…
+ Value::Array(a) => {
+ let mut keys = Vec::new();
+ for k in a {
+ let k = k.as_str().ok_or_else(|| bad(CMD, format!("`{source}` entries must be strings")))?;
+ if !avail.contains(&k) {
+ return Err(bad(CMD, format!("`{k}` is not a {source} data point ({})", avail.join("|"))));
+ }
+ keys.push(k.to_string());
+ }
+ *list = keys;
+ }
+ // …or {key: on/off} changes.
+ Value::Object(o) => {
+ for (k, on) in o {
+ if !avail.contains(&k.as_str()) {
+ return Err(bad(CMD, format!("`{k}` is not a {source} data point ({})", avail.join("|"))));
+ }
+ let on = on.as_bool().ok_or_else(|| bad(CMD, format!("`{source}.{k}` must be a bool")))?;
+ list.retain(|x| x != k);
+ if on {
+ list.push(k.clone());
+ }
+ }
+ }
+ _ => return Err(bad(CMD, format!("`{source}` must be a list of keys or an object of bools"))),
+ }
+ // Keep the column order.
+ list.sort_by_key(|k| COLUMNS.iter().position(|c| c.0 == k));
+ }
+ s.analysis.data_points = next;
+ Ok(json!({"dataPoints": s.analysis.data_points, "available": {"selection": available("selection"), "ruler": available("ruler"), "count": available("count")}, "columns": COLUMNS.iter().map(|c| json!({"key": c.0, "name": c.1})).collect::<Vec<_>>()}))
+}
+
+// ------------------------------------------------------------------ selection measurements
+
+/// Measurements of one selection feature (or the summary of all).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Feature {
+ pub area: f64,
+ pub perimeter: f64,
+ pub bounds: Rect,
+ pub gray_min: f64,
+ pub gray_max: f64,
+ pub gray_mean: f64,
+ pub gray_median: f64,
+ pub histogram: Vec<u64>,
+}
+
+impl Feature {
+ pub fn circularity(&self) -> f64 {
+ if self.perimeter > 0.0 { (4.0 * std::f64::consts::PI * self.area / (self.perimeter * self.perimeter)).min(1.0) } else { 0.0 }
+ }
+}
+
+/// Union-find root with path halving.
+fn root(parent: &mut [u32], mut i: u32) -> u32 {
+ while parent[i as usize] != i {
+ parent[i as usize] = parent[parent[i as usize] as usize];
+ i = parent[i as usize];
+ }
+ i
+}
+
+/// Gray value range of a depth: what a "gray value" of 1.0 reads as.
+fn gray_range(depth: SampleType) -> f64 {
+ match depth {
+ SampleType::U8 => 255.0,
+ SampleType::U16 => 32768.0,
+ _ => 1.0,
+ }
+}
+
+/// Split `mask` (w×h, true = selected) into 8-connected features and measure each against the
+/// gray image `gray` (0–1). Returns features in scan order of their first pixel; `origin` offsets
+/// the reported bounds.
+pub fn measure_features(mask: &[bool], gray: &[f32], w: usize, h: usize, origin: (i32, i32), range: f64) -> Vec<Feature> {
+ // Two-pass connected components.
+ let mut label = vec![u32::MAX; w * h];
+ let mut parent: Vec<u32> = Vec::new();
+ for y in 0..h {
+ for x in 0..w {
+ let i = y * w + x;
+ if !mask[i] {
+ continue;
+ }
+ let mut best = u32::MAX;
+ let mut nbrs = [u32::MAX; 4];
+ if x > 0 {
+ nbrs[0] = label[i - 1];
+ }
+ if y > 0 {
+ nbrs[1] = label[i - w];
+ if x > 0 {
+ nbrs[2] = label[i - w - 1];
+ }
+ if x + 1 < w {
+ nbrs[3] = label[i - w + 1];
+ }
+ }
+ for &n in &nbrs {
+ if n != u32::MAX {
+ let r = root(&mut parent, n);
+ best = best.min(r);
+ }
+ }
+ if best == u32::MAX {
+ best = parent.len() as u32;
+ parent.push(best);
+ } else {
+ for &n in &nbrs {
+ if n != u32::MAX {
+ let r = root(&mut parent, n);
+ if r != best {
+ let (a, b) = (r.min(best), r.max(best));
+ parent[b as usize] = a;
+ best = a;
+ }
+ }
+ }
+ }
+ label[i] = best;
+ }
+ }
+ // Compact roots → feature indices in order of first appearance.
+ let mut index = vec![u32::MAX; parent.len()];
+ let mut n = 0u32;
+ for l in label.iter_mut() {
+ if *l == u32::MAX {
+ continue;
+ }
+ let r = root(&mut parent, *l) as usize;
+ if index[r] == u32::MAX {
+ index[r] = n;
+ n += 1;
+ }
+ *l = index[r];
+ }
+ let n = n as usize;
+ // Perimeter: marching squares over the pixel-centre grid (padded with unselected pixels),
+ // per row band in parallel, each cell's length attributed to the feature of a pixel in it.
+ let at = |x: isize, y: isize| -> u32 { if x < 0 || y < 0 || x >= w as isize || y >= h as isize { u32::MAX } else { label[y as usize * w + x as usize] } };
+ const HALF_DIAG: f64 = std::f64::consts::FRAC_1_SQRT_2;
+ let per: Vec<f64> = (-1..h as isize)
+ .into_par_iter()
+ .fold(
+ || vec![0.0f64; n],
+ |mut acc, y| {
+ for x in -1..w as isize {
+ let c = [at(x, y), at(x + 1, y), at(x + 1, y + 1), at(x, y + 1)];
+ let inside = c.iter().filter(|v| **v != u32::MAX).count();
+ let len = match inside {
+ 1 | 3 => HALF_DIAG,
+ 2 if (c[0] != u32::MAX) == (c[2] != u32::MAX) => 2.0 * HALF_DIAG,
+ 2 => 1.0,
+ _ => 0.0,
+ };
+ if len > 0.0
+ && let Some(f) = c.iter().find(|v| **v != u32::MAX)
+ {
+ acc[*f as usize] += len;
+ }
+ }
+ acc
+ },
+ )
+ .reduce(
+ || vec![0.0f64; n],
+ |mut a, b| {
+ a.iter_mut().zip(b).for_each(|(x, y)| *x += y);
+ a
+ },
+ );
+ // Area, bounds and gray values.
+ let mut feats: Vec<Feature> = (0..n).map(|_| Feature { bounds: Rect::EMPTY, gray_min: f64::MAX, gray_max: f64::MIN, histogram: vec![0; 256], ..Default::default() }).collect();
+ let mut sums = vec![0.0f64; n];
+ let mut values: Vec<Vec<u16>> = vec![Vec::new(); n];
+ for y in 0..h {
+ for x in 0..w {
+ let l = label[y * w + x];
+ if l == u32::MAX {
+ continue;
+ }
+ let f = &mut feats[l as usize];
+ f.area += 1.0;
+ let (px, py) = (x as i32 + origin.0, y as i32 + origin.1);
+ let r = Rect::new(px, py, px + 1, py + 1);
+ f.bounds = if f.bounds.is_empty() { r } else { f.bounds.union(&r) };
+ let g = f64::from(gray[y * w + x]);
+ f.gray_min = f.gray_min.min(g);
+ f.gray_max = f.gray_max.max(g);
+ sums[l as usize] += g;
+ f.histogram[(g.clamp(0.0, 1.0) * 255.0).round() as usize] += 1;
+ values[l as usize].push((g.clamp(0.0, 1.0) * 65535.0).round() as u16);
+ }
+ }
+ for (i, f) in feats.iter_mut().enumerate() {
+ f.perimeter = per[i];
+ f.gray_mean = sums[i] / f.area.max(1.0) * range;
+ f.gray_min *= range;
+ f.gray_max *= range;
+ f.gray_median = median(&mut values[i]) * range;
+ }
+ feats
+}
+
+fn median(v: &mut [u16]) -> f64 {
+ if v.is_empty() {
+ return 0.0;
+ }
+ let mid = v.len() / 2;
+ let (_, m, _) = v.select_nth_unstable(mid);
+ let m = f64::from(*m);
+ let m = if v.len().is_multiple_of(2) { (m + f64::from(*v[..mid].iter().max().unwrap_or(&0))) / 2.0 } else { m };
+ m / 65535.0
+}
+
+/// Summary over features (area-weighted mean, pooled median).
+fn summary(feats: &[Feature], all_values_median: f64) -> Feature {
+ let area: f64 = feats.iter().map(|f| f.area).sum();
+ let mut hist = vec![0u64; 256];
+ let mut b = Rect::EMPTY;
+ for f in feats {
+ hist.iter_mut().zip(&f.histogram).for_each(|(a, v)| *a += v);
+ b = if b.is_empty() { f.bounds } else { b.union(&f.bounds) };
+ }
+ Feature {
+ area,
+ perimeter: feats.iter().map(|f| f.perimeter).sum(),
+ bounds: b,
+ gray_min: feats.iter().map(|f| f.gray_min).fold(f64::MAX, f64::min),
+ gray_max: feats.iter().map(|f| f.gray_max).fold(f64::MIN, f64::max),
+ gray_mean: feats.iter().map(|f| f.gray_mean * f.area).sum::<f64>() / area.max(1.0),
+ gray_median: all_values_median,
+ histogram: hist,
+ }
+}
+
+/// Selection mask (coverage ≥ 0.5) over `r`, or every pixel when there is no selection.
+fn selection_mask(d: &Document, r: Rect) -> Vec<bool> {
+ let n = (r.width() * r.height()) as usize;
+ match &d.selection {
+ None => vec![true; n],
+ Some(sel) => {
+ let c = sel.channels().max(1);
+ let v = sel.read_region(r);
+ v.chunks_exact(c).map(|p| p[0] >= 0.5).collect()
+ }
+ }
+}
+
+fn gray_image(d: &Document, r: Rect) -> Vec<f32> {
+ let buf = photocraft_compose::render(d, r);
+ buf.px.par_iter().map(|p| 0.30 * p[0] + 0.59 * p[1] + 0.11 * p[2]).collect()
+}
+
+fn selection_rows(d: &Document) -> Result<(Feature, Vec<Feature>)> {
+ let r = match &d.selection {
+ Some(sel) => sel.content_bounds().intersect(&d.bounds()),
+ None => d.bounds(),
+ };
+ if r.is_empty() {
+ return Err(EngineError::Other("the selection is empty".into()));
+ }
+ let (w, h) = (r.width() as usize, r.height() as usize);
+ let mask = selection_mask(d, r);
+ let gray = gray_image(d, r);
+ let range = gray_range(d.depth);
+ let feats = measure_features(&mask, &gray, w, h, (r.x0, r.y0), range);
+ if feats.is_empty() {
+ return Err(EngineError::Other("the selection is empty".into()));
+ }
+ let mut all: Vec<u16> = mask.iter().zip(&gray).filter(|(m, _)| **m).map(|(_, g)| (g.clamp(0.0, 1.0) * 65535.0).round() as u16).collect();
+ let med = median(&mut all) * range;
+ Ok((summary(&feats, med), feats))
+}
+
+// ------------------------------------------------------------------ ruler
+
+/// Ruler readout: X/Y (start), W/H, angle A and lengths L1/L2, as in the options bar.
+pub fn ruler_info(r: &Ruler, sc: &MeasurementScale) -> Value {
+ let (dx, dy) = (r.end[0] - r.start[0], r.end[1] - r.start[1]);
+ let l1 = dx.hypot(dy);
+ let f = sc.factor();
+ match r.protractor {
+ None => {
+ // Counter-clockwise from the +x axis with y up, −180…180.
+ let a = (-dy).atan2(dx).to_degrees();
+ json!({"x": r.start[0], "y": r.start[1], "w": dx, "h": dy, "angle": round4(a), "l1": round4(l1), "l2": Value::Null, "length": round4(l1 * f), "units": sc.units, "protractor": false})
+ }
+ Some(q) => {
+ let (ex, ey) = (q[0] - r.start[0], q[1] - r.start[1]);
+ let l2 = ex.hypot(ey);
+ let a1 = (-dy).atan2(dx);
+ let a2 = (-ey).atan2(ex);
+ let mut a = (a1 - a2).to_degrees().abs();
+ if a > 180.0 {
+ a = 360.0 - a;
+ }
+ json!({"x": r.start[0], "y": r.start[1], "w": dx, "h": dy, "angle": round4(a), "l1": round4(l1), "l2": round4(l2), "length": round4(l1 * f), "units": sc.units, "protractor": true})
+ }
+ }
+}
+
+fn ruler_tool(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.analysis.rulerTool";
+ let d = doc(s)?;
+ if p.get("clear").and_then(Value::as_bool) == Some(true) {
+ set_quiet(s, |d| d.measurement.ruler = None)?;
+ return Ok(json!({"ruler": Value::Null}));
+ }
+ let start = point(p.get("start"));
+ let end = point(p.get("end"));
+ let mut r = d.measurement.ruler;
+ match (start, end) {
+ (Some(a), Some(b)) => {
+ let prot = match p.get("protractor") {
+ Some(Value::Null) | None => None,
+ Some(v) => Some(point(Some(v)).ok_or_else(|| bad(CMD, "`protractor` must be [x, y] or null"))?),
+ };
+ r = Some(Ruler { start: a, end: b, protractor: prot });
+ }
+ (None, None) => {
+ if let (Some(cur), Some(v)) = (r.as_mut(), p.get("protractor")) {
+ cur.protractor = if v.is_null() { None } else { Some(point(Some(v)).ok_or_else(|| bad(CMD, "`protractor` must be [x, y] or null"))?) };
+ }
+ }
+ _ => return Err(bad(CMD, "pass both `start` and `end`")),
+ }
+ for v in r.iter().flat_map(|r| [Some(r.start), Some(r.end), r.protractor]).flatten() {
+ if !v[0].is_finite() || !v[1].is_finite() {
+ return Err(bad(CMD, "coordinates must be finite"));
+ }
+ }
+ if r != d.measurement.ruler {
+ set_quiet(s, |d| d.measurement.ruler = r)?;
+ }
+ Ok(match r {
+ Some(r) => json!({"ruler": {"start": r.start, "end": r.end, "protractor": r.protractor}, "info": ruler_info(&r, &d.measurement.scale)}),
+ None => json!({"ruler": Value::Null}),
+ })
+}
+
+/// Largest axis-aligned rectangle of a `w`×`h` rectangle rotated by `a` radians.
+fn inscribed(w: f64, h: f64, a: f64) -> (f64, f64) {
+ let (sa, ca) = (a.sin().abs(), a.cos().abs());
+ let long_w = w >= h;
+ let (long, short) = if long_w { (w, h) } else { (h, w) };
+ if short <= 2.0 * sa * ca * long || (sa - ca).abs() < 1e-10 {
+ let x = 0.5 * short;
+ if long_w { (x / sa, x / ca) } else { (x / ca, x / sa) }
+ } else {
+ let c2 = ca * ca - sa * sa;
+ ((w * ca - h * sa) / c2, (h * ca - w * sa) / c2)
+ }
+}
+
+fn straighten(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = doc(s)?;
+ let r = d.measurement.ruler.ok_or_else(|| EngineError::Other("no ruler line".into()))?;
+ let (dx, dy) = (r.end[0] - r.start[0], r.end[1] - r.start[1]);
+ let a = (-dy).atan2(dx).to_degrees();
+ // Straighten to the nearest axis: rotate clockwise by the remaining angle.
+ let rot = a - 90.0 * (a / 90.0).round();
+ if rot.abs() < 1e-9 {
+ return Ok(json!({"angle": 0.0}));
+ }
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let active_bg = st.active_layer.and_then(|id| d.layer(id)).is_some_and(|l| l.name == "Background" && l.locks.position);
+ let crop = p.get("crop").and_then(Value::as_bool).unwrap_or(active_bg || st.active_layer.is_none());
+ let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height));
+ compound(s, "Straighten", |s| {
+ if crop {
+ s.execute("image.rotation.arbitrary", json!({"angle": rot, "direction": "cw"}))?;
+ let nd = doc(s)?;
+ let (cw, ch) = inscribed(w0, h0, rot.to_radians());
+ let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height));
+ let (cw, ch) = (cw.floor().clamp(1.0, nw), ch.floor().clamp(1.0, nh));
+ s.execute("image.crop", json!({"x": ((nw - cw) / 2.0).round(), "y": ((nh - ch) / 2.0).round(), "width": cw, "height": ch}))?;
+ } else {
+ let (cx, cy) = (w0 / 2.0, h0 / 2.0);
+ let (sn, cs) = rot.to_radians().sin_cos();
+ // Clockwise on screen (y down) about the canvas centre.
+ let m = [cs, sn, -sn, cs, cx - (cs * cx - sn * cy), cy - (sn * cx + cs * cy)];
+ s.execute("edit.transform", json!({"matrix": m}))?;
+ }
+ // The ruler is cleared after straightening, as in Photoshop.
+ set_quiet(s, |d| d.measurement.ruler = None)
+ })?;
+ let nd = doc(s)?;
+ Ok(json!({"angle": round4(rot), "cropped": crop, "width": nd.size.width, "height": nd.size.height}))
+}
+
+// ------------------------------------------------------------------ count
+
+fn group_index(d: &Document, p: &Value) -> Option<usize> {
+ let i = p.get("group").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(d.measurement.active_count_group);
+ (i < d.measurement.count_groups.len()).then_some(i)
+}
+
+fn color_of(p: &Value, key: &str) -> Option<Color> {
+ p.get(key)?;
+ let c = crate::commands::color_param(p, key, [1.0, 0.0, 0.0, 1.0]);
+ Some(Color::rgb(c[0], c[1], c[2]))
+}
+
+/// Photoshop's colours for new count groups, in order.
+const GROUP_COLORS: [[f32; 3]; 6] = [[1.0, 0.0, 0.0], [0.0, 0.6, 1.0], [0.0, 0.8, 0.0], [1.0, 0.6, 0.0], [0.8, 0.0, 0.8], [1.0, 1.0, 0.0]];
+
+fn new_group(d: &Document, name: Option<String>, color: Option<Color>) -> CountGroup {
+ let n = d.measurement.count_groups.len();
+ let c = GROUP_COLORS[n % GROUP_COLORS.len()];
+ CountGroup { name: name.unwrap_or_else(|| format!("Count Group {}", n + 1)), color: color.unwrap_or(Color::rgb(c[0], c[1], c[2])), ..Default::default() }
+}
+
+fn count_json(d: &Document) -> Value {
+ let m = &d.measurement;
+ json!({
+ "total": m.count_total(),
+ "activeGroup": m.active_count_group,
+ "groups": m.count_groups.iter().map(|g| json!({"name": g.name, "color": g.color.to_rgb(), "markerSize": g.marker_size, "labelSize": g.label_size, "visible": g.visible, "count": g.points.len(), "points": g.points})).collect::<Vec<_>>(),
+ })
+}
+
+fn count_tool(s: &mut Session, _p: &Value) -> Result<Value> {
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+fn count_add(s: &mut Session, p: &Value) -> Result<Value> {
+ let at = xy(p).or_else(|| point(p.get("point"))).ok_or_else(|| bad("count.add", "pass `x` and `y`"))?;
+ if !at[0].is_finite() || !at[1].is_finite() {
+ return Err(bad("count.add", "coordinates must be finite"));
+ }
+ let gi = p.get("group").and_then(Value::as_u64).map(|v| v as usize);
+ let n = s.edit("Count", |d, _| {
+ if d.measurement.count_groups.is_empty() {
+ let g = new_group(d, None, None);
+ d.measurement.count_groups.push(g);
+ d.measurement.active_count_group = 0;
+ }
+ let i = gi.unwrap_or(d.measurement.active_count_group).min(d.measurement.count_groups.len() - 1);
+ let g = &mut d.measurement.count_groups[i];
+ g.points.push(at);
+ Ok(g.points.len())
+ })?;
+ let mut r = count_json(doc(s)?.as_ref());
+ r["number"] = json!(n);
+ Ok(r)
+}
+
+/// Marker nearest `at` within `radius` px in group `g` (or any visible group).
+fn nearest(d: &Document, at: [f64; 2], radius: f64, g: Option<usize>) -> Option<(usize, usize)> {
+ let mut best: Option<(f64, usize, usize)> = None;
+ for (gi, grp) in d.measurement.count_groups.iter().enumerate() {
+ if g.is_some_and(|x| x != gi) || !grp.visible {
+ continue;
+ }
+ for (pi, q) in grp.points.iter().enumerate() {
+ let dd = (q[0] - at[0]).hypot(q[1] - at[1]);
+ if dd <= radius && best.is_none_or(|b| dd < b.0) {
+ best = Some((dd, gi, pi));
+ }
+ }
+ }
+ best.map(|b| (b.1, b.2))
+}
+
+fn locate(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
+ let d = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ if let Some(i) = p.get("index").and_then(Value::as_u64) {
+ let g = group_index(&d, p).ok_or_else(|| bad(cmd, "no such count group"))?;
+ if (i as usize) < d.measurement.count_groups[g].points.len() {
+ return Ok((g, i as usize));
+ }
+ return Err(bad(cmd, format!("no marker {i}")));
+ }
+ let at = xy(p).ok_or_else(|| bad(cmd, "pass `index` or `x`/`y`"))?;
+ let radius = p.get("radius").and_then(Value::as_f64).unwrap_or(6.0);
+ let g = p.get("group").and_then(Value::as_u64).map(|v| v as usize);
+ nearest(&d, at, radius, g).ok_or_else(|| EngineError::Other("no count marker there".into()))
+}
+
+fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
+ let (g, i) = locate(s, p, "count.remove")?;
+ s.edit("Count", |d, _| {
+ d.measurement.count_groups[g].points.remove(i);
+ Ok(())
+ })?;
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+fn count_move(s: &mut Session, p: &Value) -> Result<Value> {
+ let to = point(p.get("to")).ok_or_else(|| bad("count.move", "pass `to`: [x, y]"))?;
+ let (g, i) = locate(s, p, "count.move")?;
+ s.edit("Count", |d, _| {
+ d.measurement.count_groups[g].points[i] = to;
+ Ok(())
+ })?;
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+fn count_clear(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = doc(s)?;
+ let all = p.get("group").and_then(Value::as_str) == Some("all");
+ let g = if all { None } else { Some(group_index(&d, p).ok_or_else(|| bad("count.clear", "no such count group"))?) };
+ s.edit("Clear Count", |d, _| {
+ for (i, grp) in d.measurement.count_groups.iter_mut().enumerate() {
+ if g.is_none_or(|g| g == i) {
+ grp.points.clear();
+ }
+ }
+ Ok(())
+ })?;
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+fn count_new_group(s: &mut Session, p: &Value) -> Result<Value> {
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string);
+ let color = color_of(p, "color");
+ s.edit("New Count Group", |d, _| {
+ let g = new_group(d, name, color);
+ d.measurement.count_groups.push(g);
+ d.measurement.active_count_group = d.measurement.count_groups.len() - 1;
+ Ok(())
+ })?;
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+fn count_delete_group(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = doc(s)?;
+ let g = group_index(&d, p).ok_or_else(|| bad("count.deleteGroup", "no such count group"))?;
+ s.edit("Delete Count Group", |d, _| {
+ d.measurement.count_groups.remove(g);
+ let n = d.measurement.count_groups.len();
+ d.measurement.active_count_group = d.measurement.active_count_group.min(n.saturating_sub(1));
+ Ok(())
+ })?;
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+fn count_set_group(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "count.setGroup";
+ let d = doc(s)?;
+ let g = group_index(&d, p).ok_or_else(|| bad(CMD, "no such count group"))?;
+ let mut grp = d.measurement.count_groups[g].clone();
+ if let Some(n) = p.get("name").and_then(Value::as_str) {
+ grp.name = n.to_string();
+ }
+ if let Some(c) = color_of(p, "color") {
+ grp.color = c;
+ }
+ if let Some(v) = p.get("markerSize").and_then(Value::as_u64) {
+ grp.marker_size = (v as u32).clamp(1, 10);
+ }
+ if let Some(v) = p.get("labelSize").and_then(Value::as_u64) {
+ grp.label_size = (v as u32).clamp(8, 72);
+ }
+ if let Some(v) = p.get("visible").and_then(Value::as_bool) {
+ grp.visible = v;
+ }
+ let activate = p.get("active").and_then(Value::as_bool) == Some(true) || p.as_object().is_some_and(|o| o.len() == 1 && o.contains_key("group"));
+ let changed = grp != d.measurement.count_groups[g];
+ if changed || (activate && d.measurement.active_count_group != g) {
+ s.edit("Count Group Options", |d, _| {
+ d.measurement.count_groups[g] = grp;
+ if activate {
+ d.measurement.active_count_group = g;
+ }
+ Ok(())
+ })?;
+ }
+ Ok(count_json(doc(s)?.as_ref()))
+}
+
+// ------------------------------------------------------------------ record + log
+
+fn base_row(s: &mut Session, d: &Document, source: &str, label: &str, now: &str) -> Map<String, Value> {
+ let sc = &d.measurement.scale;
+ let mut m = Map::new();
+ m.insert("label".into(), json!(label));
+ m.insert("dateTime".into(), json!(now));
+ m.insert("document".into(), json!(d.name));
+ m.insert("source".into(), json!(match source {
+ "selection" => "Selection",
+ "ruler" => "Ruler Tool",
+ _ => "Count Tool",
+ }));
+ m.insert("scale".into(), json!(sc.describe()));
+ m.insert("scaleUnits".into(), json!(sc.units));
+ m.insert("scaleFactor".into(), json!(sc.factor()));
+ let _ = s;
+ m
+}
+
+fn feature_values(m: &mut Map<String, Value>, f: &Feature, count: usize, factor: f64) {
+ m.insert("count".into(), json!(count));
+ m.insert("area".into(), json!(round4(f.area * factor * factor)));
+ m.insert("perimeter".into(), json!(round4(f.perimeter * factor)));
+ m.insert("circularity".into(), json!(round4(f.circularity())));
+ m.insert("height".into(), json!(round4(f64::from(f.bounds.height()) * factor)));
+ m.insert("width".into(), json!(round4(f64::from(f.bounds.width()) * factor)));
+ m.insert("grayMin".into(), json!(round4(f.gray_min)));
+ m.insert("grayMax".into(), json!(round4(f.gray_max)));
+ m.insert("grayMean".into(), json!(round4(f.gray_mean)));
+ m.insert("grayMedian".into(), json!(round4(f.gray_median)));
+ m.insert("integratedDensity".into(), json!(round4(f.area * f.gray_mean)));
+ m.insert("histogram".into(), json!(f.histogram));
+}
+
+fn record(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.analysis.recordMeasurements";
+ let d = doc(s)?;
+ let source = match p.get("source").and_then(Value::as_str).unwrap_or("auto") {
+ "auto" => {
+ if d.selection.is_some() {
+ "selection"
+ } else if d.measurement.ruler.is_some() {
+ "ruler"
+ } else if d.measurement.count_total() > 0 {
+ "count"
+ } else {
+ "selection"
+ }
+ }
+ x @ ("selection" | "ruler" | "count") => x,
+ other => return Err(bad(CMD, format!("unknown source `{other}` (auto|selection|ruler|count)"))),
+ };
+ s.analysis.next_measurement += 1;
+ let label = format!("Measurement {}", s.analysis.next_measurement);
+ 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();
+ match source {
+ "selection" => {
+ let (sum, feats) = selection_rows(&d)?;
+ let mut m = base_row(s, &d, source, &label, &now);
+ feature_values(&mut m, &sum, feats.len(), factor);
+ rows.push(m);
+ if feats.len() > 1 {
+ for (i, f) in feats.iter().enumerate() {
+ let mut m = base_row(s, &d, source, &format!("Feature {}", i + 1), &now);
+ feature_values(&mut m, f, 1, factor);
+ rows.push(m);
+ }
+ }
+ }
+ "ruler" => {
+ let r = d.measurement.ruler.ok_or_else(|| EngineError::Other("no ruler line to measure".into()))?;
+ let info = ruler_info(&r, &d.measurement.scale);
+ let mut m = base_row(s, &d, source, &label, &now);
+ m.insert("length".into(), info["length"].clone());
+ m.insert("angle".into(), info["angle"].clone());
+ rows.push(m);
+ }
+ _ => {
+ let mut m = base_row(s, &d, source, &label, &now);
+ m.insert("count".into(), json!(d.measurement.count_total()));
+ rows.push(m);
+ }
+ }
+ let keep = s.analysis.data_points.of(source).to_vec();
+ let mut ids = Vec::new();
+ for mut m in rows {
+ m.retain(|k, _| keep.iter().any(|x| x == k));
+ s.analysis.next_row += 1;
+ ids.push(s.analysis.next_row);
+ s.analysis.log.push(LogRow { id: s.analysis.next_row, values: m });
+ }
+ let new: Vec<&LogRow> = s.analysis.log.iter().filter(|r| ids.contains(&r.id)).collect();
+ Ok(json!({"source": source, "rows": new}))
+}
+
+fn log_list(s: &mut Session, _p: &Value) -> Result<Value> {
+ Ok(json!({"rows": s.analysis.log, "columns": log_columns(&s.analysis.log)}))
+}
+
+/// Columns any row has, in Photoshop's order.
+pub fn log_columns(rows: &[LogRow]) -> Vec<&'static str> {
+ COLUMNS.iter().map(|c| c.0).filter(|k| rows.iter().any(|r| r.values.contains_key(*k))).collect()
+}
+
+fn ids_param(p: &Value) -> Option<Vec<u64>> {
+ p.get("rows").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect())
+}
+
+fn log_delete(s: &mut Session, p: &Value) -> Result<Value> {
+ let before = s.analysis.log.len();
+ match ids_param(p) {
+ Some(ids) => s.analysis.log.retain(|r| !ids.contains(&r.id)),
+ None if p.get("all").and_then(Value::as_bool) == Some(true) => s.analysis.log.clear(),
+ None => return Err(bad("measurementLog.delete", "pass `rows`: [ids] or `all`: true")),
+ }
+ Ok(json!({"deleted": before - s.analysis.log.len(), "remaining": s.analysis.log.len()}))
+}
+
+fn csv_field(v: &Value) -> String {
+ let s = match v {
+ Value::String(s) => s.clone(),
+ Value::Array(a) => a.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" "),
+ Value::Null => String::new(),
+ other => other.to_string(),
+ };
+ if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s }
+}
+
+/// The log (or the given rows) as CSV with Photoshop's column headers.
+pub fn log_csv(rows: &[LogRow]) -> String {
+ let cols = log_columns(rows);
+ let mut out = String::new();
+ out.push_str(&cols.iter().map(|k| COLUMNS.iter().find(|c| c.0 == *k).map_or(*k, |c| c.1)).collect::<Vec<_>>().join(","));
+ out.push('\n');
+ for r in rows {
+ out.push_str(&cols.iter().map(|k| r.values.get(*k).map(csv_field).unwrap_or_default()).collect::<Vec<_>>().join(","));
+ out.push('\n');
+ }
+ out
+}
+
+fn log_export(s: &mut Session, p: &Value) -> Result<Value> {
+ let rows: Vec<LogRow> = match ids_param(p) {
+ Some(ids) => s.analysis.log.iter().filter(|r| ids.contains(&r.id)).cloned().collect(),
+ None => s.analysis.log.clone(),
+ };
+ let csv = log_csv(&rows);
+ match p.get("path").and_then(Value::as_str) {
+ Some(path) => {
+ crate::file_cmds::write_file(path, csv.as_bytes())?;
+ Ok(json!({"path": path, "rows": rows.len()}))
+ }
+ None => Ok(json!({"csv": csv, "rows": rows.len()})),
+ }
+}
+
+// ------------------------------------------------------------------ scale marker
+
+/// A "nice" bar length (1, 2 or 5 × 10ⁿ) near a fifth of the image width, in logical units.
+fn nice_length(d: &Document) -> f64 {
+ let target = f64::from(d.size.width) / 5.0 * d.measurement.scale.factor();
+ let e = 10f64.powf(target.log10().floor());
+ [5.0, 2.0, 1.0].into_iter().map(|m| m * e).find(|v| *v <= target).unwrap_or(e)
+}
+
+fn place_scale_marker(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "image.analysis.placeScaleMarker";
+ let d = doc(s)?;
+ let sc = d.measurement.scale.clone();
+ let length = p.get("length").and_then(Value::as_f64).unwrap_or_else(|| nice_length(&d));
+ if !(length > 0.0 && length.is_finite()) {
+ return Err(bad(CMD, "length must be positive"));
+ }
+ let px = length / sc.factor();
+ let (w, h) = (f64::from(d.size.width), f64::from(d.size.height));
+ if px < 1.0 || px > w {
+ return Err(bad(CMD, format!("a {length} {} bar is {px:.1} px; it must fit the {w} px wide image", sc.units)));
+ }
+ let font_size = p.get("fontSize").and_then(Value::as_f64).unwrap_or(12.0).clamp(1.0, 1000.0);
+ let font = p.get("font").and_then(Value::as_str).map(str::to_string);
+ let show_text = p.get("displayText").and_then(Value::as_bool).unwrap_or(true);
+ let text_top = match p.get("textPosition").and_then(Value::as_str).unwrap_or("bottom") {
+ "top" => true,
+ "bottom" => false,
+ o => return Err(bad(CMD, format!("textPosition `{o}` (top|bottom)"))),
+ };
+ let rgb: [f32; 3] = match p.get("color").and_then(Value::as_str).unwrap_or("black") {
+ "black" => [0.0, 0.0, 0.0],
+ "white" => [1.0, 1.0, 1.0],
+ o => return Err(bad(CMD, format!("color `{o}` (black|white)"))),
+ };
+ // Bottom-left with a margin; the text sits under (or over) the bar.
+ let margin = (w.min(h) * 0.03).round().max(2.0);
+ let bar_h = (font_size / 4.0).round().clamp(2.0, h / 4.0);
+ let text_h = if show_text { font_size * 1.25 } else { 0.0 };
+ let bar_y = if text_top { h - margin - bar_h } else { h - margin - bar_h - text_h };
+ let bar = Rect::new(margin as i32, bar_y.round() as i32, (margin + px).round() as i32, (bar_y + bar_h).round() as i32);
+ let label = format!("{} {}", trim_num(length), sc.units);
+ compound(s, "Place Scale Marker", |s| {
+ let fmt = doc(s)?.pixel_format();
+ let bar_id = s.edit("Place Scale Marker", |doc, active| {
+ let mut l = Layer::raster("Scale Bar", fmt);
+ if let Some(surf) = l.surface_mut() {
+ surf.fill_rect(bar, &photocraft_raster::from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]));
+ }
+ let id = l.id;
+ doc.layers.push(Layer::group("Measurement Scale Marker", vec![l]));
+ *active = Some(id);
+ Ok(id)
+ })?;
+ let mut text_layer = Value::Null;
+ if show_text {
+ let baseline = if text_top { f64::from(bar.y0) - font_size * 0.3 } else { f64::from(bar.y1) + font_size };
+ let mut tp = json!({"x": bar.x0, "y": baseline, "text": label, "size": font_size, "color": [rgb[0], rgb[1], rgb[2], 1.0], "name": label});
+ if let Some(f) = &font {
+ tp["font"] = json!(f);
+ }
+ text_layer = s.execute("type.create", tp)?["layer"].clone();
+ }
+ let group = doc(s)?.layers.last().map(|l| l.id.0);
+ Ok(json!({"group": group, "bar": bar_id.0, "text": text_layer, "barRect": [bar.x0, bar.y0, bar.x1, bar.y1], "pixels": px, "label": label}))
+ })
+}
+
+fn trim_num(v: f64) -> String {
+ if v.fract() == 0.0 { format!("{}", v as i64) } else { format!("{v}") }
+}
+
+// ------------------------------------------------------------------ info
+
+fn analysis_info(s: &mut Session, _p: &Value) -> Result<Value> {
+ let d = doc(s)?;
+ let m = &d.measurement;
+ Ok(json!({
+ "scale": scale_json(&m.scale),
+ "ruler": m.ruler.map(|r| json!({"start": r.start, "end": r.end, "protractor": r.protractor, "info": ruler_info(&r, &m.scale)})),
+ "count": count_json(&d),
+ "notes": d.notes.len(),
+ "logRows": s.analysis.log.len(),
+ }))
+}
+
+macro_rules! spec {
+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr, $journal:expr) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: $journal }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ spec!("image.analysis.setMeasurementScale", "Set Measurement Scale…", ["Image", "Analysis"], r##"{"preset":"default|custom"="custom","pixelLength":px,"logicalLength":number,"units":str (e.g. "mm")} (no params: read the scale)"##, has_doc, set_scale, true),
+ spec!("image.analysis.selectDataPoints", "Select Data Points…", ["Image", "Analysis"], r##"{"selection":[keys]|{key:bool}?,"ruler":[keys]|{key:bool}?,"count":[keys]|{key:bool}?,"reset":bool=false} (keys: label,dateTime,document,source,scale,scaleUnits,scaleFactor,count,area,perimeter,circularity,height,width,grayMin,grayMax,grayMean,grayMedian,integratedDensity,histogram,length,angle)"##, always, select_data_points, true),
+ spec!("image.analysis.recordMeasurements", "Record Measurements", ["Image", "Analysis"], r##"{"source":"auto|selection|ruler|count"="auto"} → appended Measurement Log rows (selection: summary + one row per feature)"##, has_doc, record, true),
+ spec!("image.analysis.rulerTool", "Ruler Tool", ["Image", "Analysis"], r##"{"start":[x,y],"end":[x,y],"protractor":[x,y]|null?,"clear":bool=false} (no params: read) → X/Y/W/H/angle/L1/L2"##, has_doc, ruler_tool, true),
+ spec!("image.analysis.countTool", "Count Tool", ["Image", "Analysis"], r##"{} → count groups and markers (edit with count.*)"##, has_doc, count_tool, false),
+ spec!("image.analysis.placeScaleMarker", "Place Scale Marker…", ["Image", "Analysis"], r##"{"length":logical units=nice ≈ width/5,"font":str?,"fontSize":pt=12,"displayText":bool=true,"textPosition":"top|bottom"="bottom","color":"black|white"="black"}"##, has_doc, place_scale_marker, true),
+ spec!("image.analysis.straightenLayer", "Straighten Layer", [], r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image)"##, has_ruler, straighten, true),
+ spec!("image.analysis.info", "Analysis Info", [], r##"{} → scale, ruler readout, count groups, note and log counts"##, has_doc, analysis_info, false),
+ spec!("count.add", "Add Count", [], r##"{"x":px,"y":px,"group":index?}"##, has_doc, count_add, true),
+ spec!("count.remove", "Remove Count", [], r##"{"index":n,"group":index?} | {"x":px,"y":px,"radius":px=6}"##, has_doc, count_remove, true),
+ spec!("count.move", "Move Count", [], r##"{"index":n,"group":index?,"to":[x,y]} | {"x":px,"y":px,"to":[x,y]}"##, has_doc, count_move, true),
+ spec!("count.clear", "Clear Count", [], r##"{"group":index|"all"=active}"##, has_doc, count_clear, true),
+ spec!("count.newGroup", "New Count Group", [], r##"{"name":str?,"color":"#rrggbb"|[r,g,b]?}"##, has_doc, count_new_group, true),
+ spec!("count.deleteGroup", "Delete Count Group", [], r##"{"group":index=active}"##, has_doc, count_delete_group, true),
+ spec!("count.setGroup", "Count Group Options", [], r##"{"group":index=active,"name":str?,"color":"#rrggbb"|[r,g,b]?,"markerSize":1..10?,"labelSize":8..72?,"visible":bool?,"active":bool?}"##, has_doc, count_set_group, true),
+ spec!("measurementLog.list", "Measurement Log", [], r##"{} → rows and columns"##, always, log_list, false),
+ spec!("measurementLog.delete", "Delete Measurements", [], r##"{"rows":[ids]}|{"all":true}"##, has_log, log_delete, true),
+ spec!("measurementLog.export", "Export Measurements…", [], r##"{"path":str? (CSV file; omitted → returns the CSV text),"rows":[ids]?}"##, always, log_export, true),
+ ]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/analysis_cmds/tests.rs b/crates/engine/src/analysis_cmds/tests.rs
new file mode 100644
index 000000000..8378e8b6b
--- /dev/null
+++ b/crates/engine/src/analysis_cmds/tests.rs
@@ -0,0 +1,297 @@
+use super::*;
+use photocraft_doc::ColorMode;
+
+fn session(w: u32, h: u32, depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "background": "white"})).unwrap();
+ s
+}
+
+fn d(s: &Session) -> Arc<Document> {
+ s.active().unwrap().doc.clone()
+}
+
+#[test]
+fn measurement_scale_set_query_default_and_undo() {
+ let mut s = session(50, 40, 8);
+ let r = s.execute("image.analysis.setMeasurementScale", json!({})).unwrap();
+ assert_eq!(r["default"], true);
+ let r = s.execute("image.analysis.setMeasurementScale", json!({"pixelLength": 100, "logicalLength": 2.5, "units": "cm"})).unwrap();
+ assert_eq!(r["factor"], 0.025);
+ assert_eq!(r["text"], "100 pixels = 2.5000 cm");
+ assert_eq!(d(&s).measurement.scale.units, "cm");
+ assert!(s.execute("image.analysis.setMeasurementScale", json!({"pixelLength": 0})).is_err());
+ assert!(s.execute("image.analysis.setMeasurementScale", json!({"units": " "})).is_err());
+ assert!(s.execute("image.analysis.setMeasurementScale", json!({"preset": "bogus"})).is_err());
+ s.execute("image.analysis.setMeasurementScale", json!({"preset": "default"})).unwrap();
+ assert!(d(&s).measurement.scale.is_default());
+ assert!(s.undo());
+ assert_eq!(d(&s).measurement.scale.units, "cm");
+}
+
+#[test]
+fn features_area_perimeter_circularity() {
+ // A 10×10 square and a 1-pixel diagonal line of 5 pixels (one 8-connected feature).
+ let (w, h) = (30usize, 20usize);
+ let mut mask = vec![false; w * h];
+ for y in 2..12 {
+ for x in 2..12 {
+ mask[y * w + x] = true;
+ }
+ }
+ for i in 0..5 {
+ mask[(5 + i) * w + 20 + i] = true;
+ }
+ let gray: Vec<f32> = (0..w * h).map(|i| if i % 2 == 0 { 0.0 } else { 1.0 }).collect();
+ let f = measure_features(&mask, &gray, w, h, (100, 200), 255.0);
+ assert_eq!(f.len(), 2);
+ assert_eq!(f[0].area, 100.0);
+ assert_eq!(f[0].bounds, Rect::new(102, 202, 112, 212));
+ // Straight edges exact, corners cut by √½: 4·9 + 4·√½.
+ assert!((f[0].perimeter - (36.0 + 4.0 * std::f64::consts::FRAC_1_SQRT_2)).abs() < 1e-9, "{}", f[0].perimeter);
+ assert!(f[0].circularity() > 0.75 && f[0].circularity() < 0.9);
+ assert_eq!(f[0].gray_min, 0.0);
+ assert_eq!(f[0].gray_max, 255.0);
+ assert!((f[0].gray_mean - 127.5).abs() < 3.0);
+ assert_eq!(f[0].histogram.iter().sum::<u64>(), 100);
+ assert_eq!(f[1].area, 5.0);
+ // A disc's circularity approaches 1.
+ let (w, h) = (101usize, 101usize);
+ let mask: Vec<bool> = (0..w * h).map(|i| ((i % w) as f64 - 50.0).hypot((i / w) as f64 - 50.0) <= 40.0).collect();
+ let f = measure_features(&mask, &vec![0.5; w * h], w, h, (0, 0), 1.0);
+ assert_eq!(f.len(), 1);
+ // Digital discs read ≈0.89 (the 8-direction contour is ~5 % long), as in ImageJ.
+ assert!(f[0].circularity() > 0.85, "{}", f[0].circularity());
+ assert!((f[0].perimeter / (2.0 * std::f64::consts::PI * 40.0) - 1.0).abs() < 0.08, "{}", f[0].perimeter);
+ assert!((f[0].gray_median - 0.5).abs() < 1e-4);
+}
+
+#[test]
+fn record_selection_rows_respect_scale_and_data_points() {
+ for depth in [8, 16, 32] {
+ let mut s = session(64, 48, depth);
+ s.execute("select.all", json!({})).unwrap_or_default();
+ s.execute("select.deselect", json!({})).unwrap_or_default();
+ // Two separate rectangles.
+ s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap();
+ s.execute("select.rect", json!({"x": 30, "y": 20, "width": 20, "height": 5, "mode": "add"})).unwrap();
+ s.execute("image.analysis.setMeasurementScale", json!({"pixelLength": 2, "logicalLength": 1, "units": "mm"})).unwrap();
+ let r = s.execute("image.analysis.recordMeasurements", json!({"dateTime": "2026-10-01T00:00:00Z"})).unwrap();
+ assert_eq!(r["source"], "selection");
+ let rows = r["rows"].as_array().unwrap();
+ assert_eq!(rows.len(), 3, "summary + 2 features");
+ let sum = &rows[0]["values"];
+ assert_eq!(sum["count"], 2);
+ assert_eq!(sum["area"], (100.0 + 100.0) * 0.25);
+ assert_eq!(sum["scaleUnits"], "mm");
+ assert_eq!(sum["source"], "Selection");
+ // White background: gray max reads as white in the depth's range.
+ let white = match depth {
+ 8 => 255.0,
+ 16 => 32768.0,
+ _ => 1.0,
+ };
+ assert!((sum["grayMean"].as_f64().unwrap() - white).abs() < white * 0.01, "{depth}: {sum}");
+ assert_eq!(rows[1]["values"]["label"], "Feature 1");
+ assert_eq!(rows[2]["values"]["width"], 10.0);
+ assert_eq!(rows[2]["values"]["height"], 2.5);
+ }
+ // Data points filter the columns.
+ let mut s = session(20, 20, 8);
+ s.execute("image.analysis.selectDataPoints", json!({"selection": ["label", "area"]})).unwrap();
+ let r = s.execute("image.analysis.recordMeasurements", json!({"source": "selection"})).unwrap();
+ let v = r["rows"][0]["values"].as_object().unwrap();
+ assert_eq!(v.keys().collect::<Vec<_>>(), ["area", "label"]);
+ assert_eq!(v["area"], 400.0, "no selection: the whole image");
+ let r = s.execute("image.analysis.selectDataPoints", json!({"selection": {"perimeter": true, "label": false}})).unwrap();
+ assert_eq!(r["dataPoints"]["selection"], json!(["area", "perimeter"]));
+ assert!(s.execute("image.analysis.selectDataPoints", json!({"ruler": ["area"]})).is_err());
+ s.execute("image.analysis.selectDataPoints", json!({"reset": true})).unwrap();
+ assert_eq!(s.analysis.data_points, DataPoints::default());
+}
+
+#[test]
+fn ruler_protractor_and_record() {
+ let mut s = session(100, 100, 8);
+ let r = s.execute("image.analysis.rulerTool", json!({"start": [10, 50], "end": [40, 10]})).unwrap();
+ let i = &r["info"];
+ assert_eq!(i["l1"], 50.0);
+ assert_eq!(i["w"], 30.0);
+ assert_eq!(i["h"], -40.0);
+ assert!((i["angle"].as_f64().unwrap() - 53.1301).abs() < 1e-3);
+ // The ruler doesn't add history and doesn't dirty the document.
+ assert_eq!(s.active().unwrap().history.past_len(), 0);
+ assert!(!s.active().unwrap().is_dirty());
+ // Protractor: a second arm straight down from the vertex.
+ let r = s.execute("image.analysis.rulerTool", json!({"protractor": [10, 90]})).unwrap();
+ assert!((r["info"]["angle"].as_f64().unwrap() - (180.0 - 36.8699)).abs() < 1e-3, "{r}");
+ assert_eq!(r["info"]["l2"], 40.0);
+ s.execute("image.analysis.setMeasurementScale", json!({"pixelLength": 10, "logicalLength": 1, "units": "cm"})).unwrap();
+ let r = s.execute("image.analysis.recordMeasurements", json!({})).unwrap();
+ assert_eq!(r["source"], "ruler");
+ assert_eq!(r["rows"][0]["values"]["length"], 5.0);
+ assert!(s.execute("image.analysis.rulerTool", json!({"start": [1, 1]})).is_err());
+ s.execute("image.analysis.rulerTool", json!({"clear": true})).unwrap();
+ assert!(d(&s).measurement.ruler.is_none());
+ assert!(!s.is_enabled("image.analysis.straightenLayer"));
+}
+
+#[test]
+fn straighten_layer_and_image() {
+ // A layer: rotated about the canvas centre, canvas unchanged.
+ let mut s = session(80, 60, 8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 28, "width": 60, "height": 4})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap_or_default();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
+ let before = s.active().unwrap().history.past_len();
+ let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
+ assert_eq!(r["cropped"], false);
+ assert!((r["angle"].as_f64().unwrap() - 4.7636).abs() < 1e-3, "{r}");
+ assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one history step");
+ assert_eq!(d(&s).size.width, 80);
+ assert!(d(&s).measurement.ruler.is_none());
+ // The Background: rotate the canvas and crop to the image.
+ let mut s = session(80, 60, 16);
+ s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [40, 40]})).unwrap();
+ let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
+ assert_eq!(r["cropped"], true);
+ assert_eq!(r["angle"].as_f64().unwrap().abs(), 45.0);
+ let nd = d(&s);
+ assert!(nd.size.width < 80 && nd.size.height < 60);
+ assert!(s.undo());
+ assert_eq!(d(&s).size.width, 80);
+}
+
+#[test]
+fn inscribed_rect() {
+ let (w, h) = inscribed(100.0, 50.0, 0.0);
+ assert!((w - 100.0).abs() < 1e-9 && (h - 50.0).abs() < 1e-9);
+ let (w, h) = inscribed(100.0, 100.0, std::f64::consts::FRAC_PI_4);
+ assert!((w - 70.710678).abs() < 1e-4 && (h - 70.710678).abs() < 1e-4);
+}
+
+#[test]
+fn count_groups_markers_and_undo() {
+ let mut s = session(100, 100, 8);
+ let r = s.execute("image.analysis.countTool", json!({})).unwrap();
+ assert_eq!(r["total"], 0);
+ let r = s.execute("count.add", json!({"x": 10, "y": 10})).unwrap();
+ assert_eq!(r["number"], 1);
+ assert_eq!(r["groups"][0]["name"], "Count Group 1");
+ s.execute("count.add", json!({"x": 20, "y": 20})).unwrap();
+ s.execute("count.newGroup", json!({"name": "Cells", "color": "#00ff00"})).unwrap();
+ let r = s.execute("count.add", json!({"x": 50, "y": 50})).unwrap();
+ assert_eq!(r["activeGroup"], 1);
+ assert_eq!(r["groups"][1]["count"], 1);
+ assert_eq!(r["total"], 3);
+ // Remove by position, move by index.
+ s.execute("count.remove", json!({"x": 21, "y": 19})).unwrap();
+ assert_eq!(d(&s).measurement.count_groups[0].points, vec![[10.0, 10.0]]);
+ s.execute("count.move", json!({"group": 0, "index": 0, "to": [12, 13]})).unwrap();
+ assert_eq!(d(&s).measurement.count_groups[0].points[0], [12.0, 13.0]);
+ assert!(s.execute("count.remove", json!({"x": 90, "y": 90})).is_err());
+ s.execute("count.setGroup", json!({"group": 0, "markerSize": 50, "labelSize": 20, "visible": false, "name": "Spots"})).unwrap();
+ let g = &d(&s).measurement.count_groups[0];
+ assert_eq!((g.marker_size, g.label_size, g.visible, g.name.as_str()), (10, 20, false, "Spots"));
+ // Record counts.
+ let r = s.execute("image.analysis.recordMeasurements", json!({"source": "count"})).unwrap();
+ assert_eq!(r["rows"][0]["values"]["count"], 2);
+ s.execute("count.clear", json!({})).unwrap();
+ assert_eq!(d(&s).measurement.count_total(), 1, "clears the active group only");
+ s.execute("count.clear", json!({"group": "all"})).unwrap();
+ assert_eq!(d(&s).measurement.count_total(), 0);
+ assert!(s.undo());
+ assert_eq!(d(&s).measurement.count_total(), 1);
+ s.execute("count.deleteGroup", json!({"group": 1})).unwrap();
+ assert_eq!(d(&s).measurement.count_groups.len(), 1);
+ assert_eq!(d(&s).measurement.active_count_group, 0);
+ s.execute("count.setGroup", json!({"group": 0})).unwrap();
+ assert!(s.execute("count.setGroup", json!({"group": 7})).is_err());
+ assert!(s.execute("count.add", json!({"x": 1})).is_err());
+}
+
+#[test]
+fn log_delete_and_csv_export() {
+ let mut s = session(10, 10, 8);
+ assert!(!s.is_enabled("measurementLog.delete"));
+ s.execute("image.analysis.recordMeasurements", json!({"dateTime": "t"})).unwrap();
+ s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [3, 4]})).unwrap();
+ s.execute("image.analysis.recordMeasurements", json!({"source": "ruler", "dateTime": "t"})).unwrap();
+ let r = s.execute("measurementLog.list", json!({})).unwrap();
+ assert_eq!(r["rows"].as_array().unwrap().len(), 2);
+ let r = s.execute("measurementLog.export", json!({})).unwrap();
+ let csv = r["csv"].as_str().unwrap();
+ let mut lines = csv.lines();
+ let header = lines.next().unwrap();
+ assert!(header.starts_with("Label,Date and Time,Document,Source,Scale"));
+ assert!(header.contains("Length") && header.contains("Gray Value (Mean)"));
+ assert!(lines.next().unwrap().starts_with("Measurement 1,t,"));
+ assert!(lines.next().unwrap().contains(",5.0,"), "{csv}");
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let path = std::env::temp_dir().join(format!("pc-log-{}.csv", std::process::id()));
+ let r = s.execute("measurementLog.export", json!({"path": path.to_str().unwrap(), "rows": [2]})).unwrap();
+ assert_eq!(r["rows"], 1);
+ let text = std::fs::read_to_string(&path).unwrap();
+ assert_eq!(text.lines().count(), 2);
+ let _ = std::fs::remove_file(path);
+ }
+ s.execute("measurementLog.delete", json!({"rows": [1]})).unwrap();
+ assert_eq!(s.analysis.log.len(), 1);
+ assert!(s.execute("measurementLog.delete", json!({})).is_err());
+ s.execute("measurementLog.delete", json!({"all": true})).unwrap();
+ assert!(s.analysis.log.is_empty());
+ assert_eq!(csv_field(&json!("a,\"b\"")), "\"a,\"\"b\"\"\"");
+}
+
+#[test]
+fn place_scale_marker_builds_one_group_in_one_step() {
+ let mut s = session(400, 300, 8);
+ s.execute("image.analysis.setMeasurementScale", json!({"pixelLength": 50, "logicalLength": 1, "units": "cm"})).unwrap();
+ let before = s.active().unwrap().history.past_len();
+ let r = s.execute("image.analysis.placeScaleMarker", json!({"color": "black"})).unwrap();
+ assert_eq!(s.active().unwrap().history.past_len(), before + 1);
+ // Nice length near width/5 = 80 px = 1.6 cm → 1 cm = 50 px.
+ assert_eq!(r["label"], "1 cm");
+ assert_eq!(r["pixels"], 50.0);
+ let doc = d(&s);
+ let g = doc.layers.last().unwrap();
+ assert_eq!(g.name, "Measurement Scale Marker");
+ let kids = g.children().unwrap();
+ assert_eq!(kids.len(), 2, "bar + text");
+ let bar = kids.iter().find(|l| l.name == "Scale Bar").unwrap();
+ let b = bar.surface().unwrap().content_bounds();
+ assert_eq!(b.width(), 50);
+ assert!(b.y1 < 300);
+ // Without text, white, on top.
+ let r = s.execute("image.analysis.placeScaleMarker", json!({"length": 2, "displayText": false, "color": "white", "textPosition": "top"})).unwrap();
+ assert_eq!(r["pixels"], 100.0);
+ assert!(r["text"].is_null());
+ assert!(s.execute("image.analysis.placeScaleMarker", json!({"length": 100})).is_err(), "wider than the image");
+ assert!(s.execute("image.analysis.placeScaleMarker", json!({"color": "red"})).is_err());
+ assert!(s.undo());
+ assert!(s.undo());
+ assert!(d(&s).layers.iter().all(|l| l.name != "Measurement Scale Marker"));
+}
+
+#[test]
+fn analysis_info_and_cmyk_document() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 30, "height": 20, "mode": "cmyk", "background": "white"})).unwrap();
+ assert_eq!(d(&s).mode, ColorMode::Cmyk);
+ s.execute("count.add", json!({"x": 3, "y": 4})).unwrap();
+ let r = s.execute("image.analysis.recordMeasurements", json!({"source": "selection"})).unwrap();
+ assert_eq!(r["rows"][0]["values"]["area"], 600.0);
+ let r = s.execute("image.analysis.info", json!({})).unwrap();
+ assert_eq!(r["count"]["total"], 1);
+ assert_eq!(r["logRows"], 1);
+}
+
+#[test]
+fn now_iso_shape() {
+ let t = now_iso();
+ assert_eq!(t.len(), 20, "{t}");
+ assert!(t.ends_with('Z') && &t[4..5] == "-");
+}
diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rs
new file mode 100644
index 000000000..7fe62fda4
--- /dev/null
+++ b/crates/engine/src/automate_cmds.rs
@@ -0,0 +1,512 @@
+//! File › Automate › Contact Sheet II and Create Droplet, File › Scripts › Statistics, Browse
+//! and Script Events Manager, plus the session state the File-menu commands share
+//! ([`FileMenuState`]).
+//!
+//! "Scripts" are PhotoCraft action scripts: JSON (`[[id, params], …]`, `{"steps": …}` or a
+//! droplet) or a plain-text list with one `command.id {json params}` per line (`#` comments).
+//! Droplets are JSON files (`.pcdroplet`) holding an action plus batch options; `photocraft-cli
+//! droplet <file> <inputs…>` runs one, and on macOS/Linux a `.command` shim makes it
+//! double-clickable / drop-target-able from the shell.
+//!
+//! Script events (Start Application, New / Open / Save / Close Document, Print, Export) are
+//! bound in Preferences (`scriptEvents`) and fired by [`fire_event`]: the engine fires New,
+//! Close, Print and Export itself; the app shell fires Start, Open and Save.
+
+use photocraft_doc::{DocId, Layer, LayerContent};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::file_cmds::{file_name, import, join, list_images, read_file, stem, write_file};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+/// Session state of the File-menu commands (not saved, not history).
+#[derive(Clone, Debug, Default)]
+pub struct FileMenuState {
+ /// View › Lock Slices.
+ pub slices_locked: bool,
+ /// Documents with File › Generate › Image Assets on.
+ pub image_assets: Vec<DocId>,
+ /// File › Print settings used last (Print One Copy repeats them).
+ pub last_print: Option<Value>,
+ /// Save for Web settings used last.
+ pub last_web: Option<Value>,
+ /// Results of the most recent script event (for inspection), newest last, capped.
+ pub event_log: Vec<Value>,
+ /// Set while event scripts run, so their commands don't fire events recursively.
+ pub firing: bool,
+}
+
+// ---------- scripts ----------
+
+/// Parses an action script: JSON (array of steps, `{"steps"|"action": …}`, a droplet) or one
+/// `command.id {json}` per line.
+pub fn parse_script(text: &str) -> Result<Vec<(String, Value)>> {
+ let cmd = "file.scripts.browse";
+ let t = text.trim_start_matches('\u{feff}').trim();
+ if t.starts_with('[') || t.starts_with('{') {
+ let v: Value = serde_json::from_str(t).map_err(|e| bad(cmd, format!("script JSON: {e}")))?;
+ let steps = match &v {
+ Value::Array(_) => &v,
+ Value::Object(o) => o
+ .get("steps")
+ .or_else(|| o.get("action").and_then(|a| a.get("steps").or(Some(a))))
+ .ok_or_else(|| bad(cmd, "script object needs \"steps\""))?,
+ _ => unreachable!(),
+ };
+ return parse_steps(steps, cmd);
+ }
+ let mut out = Vec::new();
+ for (n, line) in t.lines().enumerate() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
+ continue;
+ }
+ let (id, rest) = line.split_once(char::is_whitespace).map_or((line, ""), |(a, b)| (a, b.trim()));
+ let params = if rest.is_empty() { json!({}) } else { serde_json::from_str(rest).map_err(|e| bad(cmd, format!("line {}: {e}", n + 1)))? };
+ out.push((id.to_string(), params));
+ }
+ Ok(out)
+}
+
+fn parse_steps(v: &Value, cmd: &str) -> Result<Vec<(String, Value)>> {
+ let arr = v.as_array().ok_or_else(|| bad(cmd, "steps must be an array"))?;
+ arr.iter()
+ .map(|st| match st {
+ Value::Array(a) if !a.is_empty() => Ok((a[0].as_str().ok_or_else(|| bad(cmd, "step id must be a string"))?.to_string(), a.get(1).cloned().unwrap_or(json!({})))),
+ Value::Object(o) => {
+ let id = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).ok_or_else(|| bad(cmd, "step needs \"command\""))?;
+ Ok((id.to_string(), o.get("params").cloned().unwrap_or(json!({}))))
+ }
+ Value::String(id) => Ok((id.clone(), json!({}))),
+ _ => Err(bad(cmd, "each step is [id, params], {\"command\", \"params\"} or an id")),
+ })
+ .collect()
+}
+
+fn check_known(steps: &[(String, Value)], cmd: &str) -> Result<()> {
+ match steps.iter().find(|(id, _)| crate::commands::find(id).is_none()) {
+ Some((id, _)) => Err(bad(cmd, format!("unknown command `{id}` in the script"))),
+ None => Ok(()),
+ }
+}
+
+fn run_steps(s: &mut Session, steps: &[(String, Value)]) -> Vec<Value> {
+ let mut results = Vec::new();
+ for (id, params) in steps {
+ match s.execute(id, params.clone()) {
+ Ok(r) => results.push(json!({"command": id, "result": r})),
+ Err(e) => {
+ results.push(json!({"command": id, "error": e.to_string()}));
+ break;
+ }
+ }
+ }
+ results
+}
+
+/// File › Scripts › Browse…: run a script file on the session.
+fn browse(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.scripts.browse";
+ let steps = match (p.get("path").and_then(Value::as_str), p.get("script").and_then(Value::as_str), p.get("steps")) {
+ (Some(path), _, _) => parse_script(&String::from_utf8_lossy(&read_file(path)?))?,
+ (_, Some(text), _) => parse_script(text)?,
+ (_, _, Some(v)) => parse_steps(v, cmd)?,
+ _ => return Err(bad(cmd, "give \"path\" (a script file), \"script\" (its text) or \"steps\"")),
+ };
+ check_known(&steps, cmd)?;
+ let results = run_steps(s, &steps);
+ let ok = results.iter().all(|r| r.get("error").is_none());
+ Ok(json!({"steps": steps.len(), "ok": ok, "results": results}))
+}
+
+// ---------- Script Events Manager ----------
+
+/// Events a script can be bound to (Photoshop's Script Events Manager list).
+pub const EVENTS: [(&str, &str); 8] = [
+ ("startApplication", "Start Application"),
+ ("newDocument", "New Document"),
+ ("openDocument", "Open Document"),
+ ("saveDocument", "Save Document"),
+ ("closeDocument", "Close Document"),
+ ("print", "Print Document"),
+ ("export", "Export Document"),
+ ("everything", "Everything"),
+];
+
+/// One event → script binding.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ScriptBinding {
+ pub event: String,
+ /// A script file (see [`parse_script`]).
+ pub script: Option<String>,
+ /// Or inline steps (an action).
+ pub steps: Option<Value>,
+ /// Display name (the action's name).
+ pub name: String,
+}
+
+/// Preferences › Script Events Manager.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ScriptEvents {
+ /// "Enable Events to Run Scripts/Actions".
+ pub enabled: bool,
+ pub bindings: Vec<ScriptBinding>,
+}
+
+fn script_events(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.scripts.scriptEventsManager";
+ let mut ev = s.prefs().script_events.clone();
+ if let Some(b) = p.get("enabled").and_then(Value::as_bool) {
+ ev.enabled = b;
+ }
+ if p.get("removeAll").and_then(Value::as_bool) == Some(true) {
+ ev.bindings.clear();
+ }
+ if let Some(i) = p.get("remove").and_then(Value::as_u64) {
+ if (i as usize) >= ev.bindings.len() {
+ return Err(bad(cmd, format!("no binding {i}")));
+ }
+ ev.bindings.remove(i as usize);
+ }
+ // The dialog's flat form: "event" + "script" at the top level means add.
+ let flat = p.get("event").and_then(Value::as_str).filter(|_| p.get("script").and_then(Value::as_str).is_some_and(|v| !v.is_empty())).map(|e| json!({"event": e, "script": p["script"], "name": p.get("name").cloned().unwrap_or(Value::Null)}));
+ if let Some(a) = p.get("add").cloned().or(flat).as_ref() {
+ let event = a.get("event").and_then(Value::as_str).ok_or_else(|| bad(cmd, "add needs \"event\""))?;
+ if !EVENTS.iter().any(|(id, _)| *id == event) {
+ return Err(bad(cmd, format!("unknown event `{event}` ({})", EVENTS.map(|e| e.0).join("|"))));
+ }
+ let script = a.get("script").and_then(Value::as_str).map(str::to_string);
+ let steps = a.get("steps").cloned();
+ if script.is_none() && steps.is_none() {
+ return Err(bad(cmd, "add needs \"script\" (a file) or \"steps\" (an action)"));
+ }
+ if let Some(st) = &steps {
+ check_known(&parse_steps(st, cmd)?, cmd)?;
+ }
+ let name = a.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| script.as_deref().map(file_name).unwrap_or_else(|| "Action".into()));
+ ev.bindings.push(ScriptBinding { event: event.into(), script, steps, name });
+ if a.get("enable").and_then(Value::as_bool).unwrap_or(true) {
+ ev.enabled = true;
+ }
+ }
+ let changed = ev != s.prefs().script_events;
+ if changed {
+ s.edit_prefs(|pr| pr.script_events = ev.clone());
+ }
+ let events: Vec<Value> = EVENTS.iter().map(|(id, label)| json!({"id": id, "label": label})).collect();
+ Ok(json!({"enabled": ev.enabled, "bindings": ev.bindings, "events": events}))
+}
+
+/// Runs the scripts bound to `event` (when Script Events are enabled). Returns how many ran.
+pub fn fire_event(s: &mut Session, event: &str) -> usize {
+ if s.file_menu.firing {
+ return 0;
+ }
+ let ev = &s.prefs().script_events;
+ if !ev.enabled {
+ return 0;
+ }
+ let jobs: Vec<ScriptBinding> = ev.bindings.iter().filter(|b| b.event == event || b.event == "everything").cloned().collect();
+ if jobs.is_empty() {
+ return 0;
+ }
+ s.file_menu.firing = true;
+ for b in &jobs {
+ let steps = match (&b.steps, &b.script) {
+ (Some(st), _) => parse_steps(st, "scriptEvent"),
+ (None, Some(path)) => read_file(path).and_then(|bytes| parse_script(&String::from_utf8_lossy(&bytes))),
+ _ => Ok(Vec::new()),
+ };
+ let entry = match steps {
+ Ok(steps) => json!({"event": event, "binding": b.name, "results": run_steps(s, &steps)}),
+ Err(e) => json!({"event": event, "binding": b.name, "error": e.to_string()}),
+ };
+ s.file_menu.event_log.push(entry);
+ }
+ let n = s.file_menu.event_log.len();
+ if n > 32 {
+ s.file_menu.event_log.drain(..n - 32);
+ }
+ s.file_menu.firing = false;
+ jobs.len()
+}
+
+/// Called by `Session::execute` after every successful command: keeps layer-based slices on
+/// their layers and fires the engine-side script events.
+pub(crate) fn after_command(s: &mut Session, id: &str) {
+ crate::slice_cmds::refresh(s);
+ let event = match id {
+ "file.new" => "newDocument",
+ "file.close" | "file.closeAll" | "file.closeOthers" => "closeDocument",
+ _ => return,
+ };
+ fire_event(s, event);
+}
+
+/// App shell hooks for the events only it sees.
+pub fn document_opened(s: &mut Session) {
+ fire_event(s, "openDocument");
+}
+
+/// After the shell saved document `index`: Save Document scripts and Image Assets.
+pub fn document_saved(s: &mut Session, index: usize) -> Option<Value> {
+ fire_event(s, "saveDocument");
+ crate::web_cmds::on_saved(s, index)
+}
+
+// ---------- Create Droplet ----------
+
+fn create_droplet(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.createDroplet";
+ let path = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| bad(cmd, "missing \"path\" (where to save the droplet)"))?;
+ let steps_v = p.get("steps").or_else(|| p.get("action")).ok_or_else(|| bad(cmd, "missing \"steps\" (the action to run)"))?;
+ let steps = parse_steps(steps_v, cmd)?;
+ check_known(&steps, cmd)?;
+ let path = if path.ends_with(".pcdroplet") || path.ends_with(".json") { path.to_string() } else { format!("{path}.pcdroplet") };
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&path));
+ let steps_json: Vec<Value> = steps.iter().map(|(id, pr)| json!([id, pr])).collect();
+ let mut options = serde_json::Map::new();
+ for k in ["output", "format", "quality", "suffix", "overrideOpen"] {
+ if let Some(v) = p.get(k) {
+ options.insert(k.into(), v.clone());
+ }
+ }
+ let droplet = json!({"photocraftDroplet": 1, "name": name, "action": {"name": name, "steps": steps_json}, "options": options});
+ let text = serde_json::to_string_pretty(&droplet).unwrap_or_default();
+ write_file(&path, text.as_bytes())?;
+ let shim = p.get("shim").and_then(Value::as_bool).unwrap_or(cfg!(any(target_os = "macos", target_os = "linux")));
+ let shim_path = if shim { Some(write_shim(&path)?) } else { None };
+ let _ = s;
+ Ok(json!({"path": path, "shim": shim_path, "steps": steps.len()}))
+}
+
+/// A tiny shell script next to the droplet: drop files on it (or pass them) to run the droplet.
+#[cfg(not(target_arch = "wasm32"))]
+fn write_shim(droplet: &str) -> Result<String> {
+ let abs = std::fs::canonicalize(droplet).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| droplet.to_string());
+ let base = abs.trim_end_matches(".pcdroplet").trim_end_matches(".json");
+ let shim = format!("{base}.command");
+ let body = format!("#!/bin/sh\n# PhotoCraft droplet: runs the action on the files given (or dropped).\nexec \"${{PHOTOCRAFT_CLI:-photocraft-cli}}\" droplet \"{}\" \"$@\"\n", abs.replace('"', "\\\""));
+ std::fs::write(&shim, body).map_err(|e| EngineError::Other(format!("{shim}: {e}")))?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755));
+ }
+ Ok(shim)
+}
+#[cfg(target_arch = "wasm32")]
+fn write_shim(_: &str) -> Result<String> {
+ Err(EngineError::Other("no file system on the web".into()))
+}
+
+/// Runs a droplet file on inputs (files and/or folders).
+fn run_droplet(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.runDroplet";
+ let path = p.get("droplet").or_else(|| p.get("path")).and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing \"droplet\""))?;
+ let v: Value = serde_json::from_slice(&read_file(path)?).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
+ if v.get("photocraftDroplet").is_none() {
+ return Err(bad(cmd, format!("{path} is not a PhotoCraft droplet")));
+ }
+ let steps = v.get("action").and_then(|a| a.get("steps")).cloned().ok_or_else(|| bad(cmd, "droplet has no action"))?;
+ let opts = v.get("options").cloned().unwrap_or(json!({}));
+ let mut inputs: Vec<String> = Vec::new();
+ let raw: Vec<String> = match p.get("input").or_else(|| p.get("files")) {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ Some(Value::String(one)) => vec![one.clone()],
+ _ => return Err(bad(cmd, "missing \"input\" (files or folders)")),
+ };
+ for i in raw {
+ if std::path::Path::new(&i).is_dir() { inputs.extend(list_images(&i)?) } else { inputs.push(i) }
+ }
+ if inputs.is_empty() {
+ return Err(bad(cmd, "no input images"));
+ }
+ let output = p.get("output").or_else(|| opts.get("output")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| {
+ let first = std::path::Path::new(&inputs[0]);
+ join(&first.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(), "droplet-output")
+ });
+ let mut bp = json!({"steps": steps, "input": inputs, "output": output, "format": opts.get("format").cloned().unwrap_or(json!("same"))});
+ if let Some(q) = opts.get("quality") {
+ bp["quality"] = q.clone();
+ }
+ let r = s.execute("file.automate.batch", bp)?;
+ Ok(json!({"droplet": path, "output": output, "files": r["files"], "errors": r["errors"]}))
+}
+
+// ---------- Statistics ----------
+
+fn statistics(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.scripts.statistics";
+ let mode = p.get("mode").or_else(|| p.get("stackMode")).and_then(Value::as_str).unwrap_or("median");
+ let sm = photocraft_doc::StackMode::ALL.into_iter().find(|m| m.id().eq_ignore_ascii_case(mode)).ok_or_else(|| bad(cmd, format!("unknown stack mode `{mode}`")))?;
+ let input = p.get("input").or_else(|| p.get("paths")).cloned().ok_or_else(|| bad(cmd, "missing \"input\" (files or a folder)"))?;
+ let align = p.get("align").and_then(Value::as_bool).unwrap_or(false);
+ let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": input, "createSmartObject": !align}))?;
+ let n = r["layers"].as_u64().unwrap_or(0);
+ if align && n > 1 {
+ s.execute("select.allLayers", json!({}))?;
+ s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?;
+ let name = s.active().map(|d| d.doc.name.clone()).unwrap_or_default();
+ s.edit("Convert to Smart Object", |doc, active| {
+ let children = std::mem::take(&mut doc.layers);
+ let group = Layer::new(name.clone(), LayerContent::Group(photocraft_doc::Group { children, expanded: true, artboard: None }));
+ let smart = crate::smart_cmds::layer_to_smart(doc, &group)?;
+ *active = Some(smart.id);
+ doc.layers = vec![smart];
+ Ok(())
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.selected_layers = st.active_layer.into_iter().collect();
+ }
+ }
+ let id = s.active().and_then(|d| d.doc.layers.first().map(|l| l.id)).ok_or(EngineError::NoDocument)?;
+ s.select_layer(id)?;
+ s.execute(&format!("layer.smartObjects.stackMode.{}", sm.id()), json!({"layer": id.0}))?;
+ Ok(json!({"document": s.active_index(), "layer": id.0, "images": n, "mode": sm.id()}))
+}
+
+// ---------- Contact Sheet II ----------
+
+fn units_px(v: f64, unit: &str, res: f64) -> f64 {
+ match unit {
+ "cm" => v * res / 2.54,
+ "mm" => v * res / 25.4,
+ "px" | "pixels" => v,
+ _ => v * res,
+ }
+}
+
+fn contact_sheet(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.contactSheetII";
+ let files: Vec<String> = match p.get("input").or_else(|| p.get("files")) {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ Some(Value::String(dir)) => list_images(dir)?,
+ _ => return Err(bad(cmd, "missing \"input\" (a folder or an array of files)")),
+ };
+ if files.is_empty() {
+ return Err(bad(cmd, "no images to place"));
+ }
+ let f = |k: &str, d: f64| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(d);
+ let unit = p.get("units").and_then(Value::as_str).unwrap_or("inches");
+ let res = f("resolution", 300.0).clamp(1.0, 10_000.0);
+ let pw = units_px(f("width", 8.0), unit, res).round().clamp(16.0, 30_000.0) as u32;
+ let ph = units_px(f("height", 10.0), unit, res).round().clamp(16.0, 30_000.0) as u32;
+ let cols = f("columns", 5.0).round().clamp(1.0, 100.0) as u32;
+ let rows = f("rows", 6.0).round().clamp(1.0, 100.0) as u32;
+ let auto = p.get("autoSpacing").and_then(Value::as_bool).unwrap_or(true);
+ let gap = (f64::from(pw.min(ph)) * 0.014).max(2.0);
+ let hs = if auto { gap } else { p.get("horizontal").and_then(Value::as_f64).map_or(gap, |v| units_px(v, unit, res)) };
+ let vs = if auto { gap } else { p.get("vertical").and_then(Value::as_f64).map_or(gap, |v| units_px(v, unit, res)) };
+ let across = p.get("placeAcrossFirst").and_then(Value::as_bool).unwrap_or(true);
+ let rotate = p.get("rotateForBestFit").and_then(Value::as_bool).unwrap_or(false);
+ let caption = p.get("caption").and_then(Value::as_bool).unwrap_or(true);
+ let font = p.get("font").and_then(Value::as_str).unwrap_or(photocraft_text::fonts::DEFAULT_FAMILY).to_string();
+ let font_pt = f("fontSize", 12.0);
+ let flatten = p.get("flatten").and_then(Value::as_bool).unwrap_or(false);
+ let mode = p.get("mode").and_then(Value::as_str).unwrap_or("rgb").to_string();
+ let depth = p.get("depth").and_then(Value::as_u64).unwrap_or(8);
+ let caption_px = if caption { font_pt * res / 72.0 * 1.5 } else { 0.0 };
+ let cell_w = ((f64::from(pw) - f64::from(cols + 1) * hs) / f64::from(cols)).max(1.0);
+ let cell_h = ((f64::from(ph) - f64::from(rows + 1) * vs) / f64::from(rows)).max(1.0);
+ let box_h = (cell_h - caption_px).max(1.0);
+ let per_page = (cols * rows) as usize;
+ let mut docs = Vec::new();
+ let mut placed = 0usize;
+ let mut errors = Vec::new();
+ for (page, chunk) in files.chunks(per_page).enumerate() {
+ let name = if files.len() > per_page { format!("ContactSheet-{:03}", page + 1) } else { "ContactSheet-001".into() };
+ s.execute("file.new", json!({"width": pw, "height": ph, "mode": mode, "depth": depth, "background": "white", "name": name}))?;
+ let idx = s.active_index().ok_or(EngineError::NoDocument)?;
+ if let Some(st) = s.active_mut() {
+ std::sync::Arc::make_mut(&mut st.doc).resolution_dpi = res as f32;
+ }
+ let fmt = s.active().ok_or(EngineError::NoDocument)?.doc.pixel_format();
+ for (k, path) in chunk.iter().enumerate() {
+ let k = k as u32;
+ let (c, r) = if across { (k % cols, k / cols) } else { (k / rows, k % rows) };
+ let x0 = hs + f64::from(c) * (cell_w + hs);
+ let y0 = vs + f64::from(r) * (cell_h + vs);
+ let thumb = (|| -> Result<photocraft_doc::Surface> {
+ let bytes = read_file(path)?;
+ let src = import(&file_name(path), &bytes)?;
+ let mut t = Session::new();
+ t.add_document(src, None);
+ let (w, h) = t.active().map(|d| (f64::from(d.doc.size.width), f64::from(d.doc.size.height))).unwrap_or((1.0, 1.0));
+ let fit = |w: f64, h: f64| (cell_w / w).min(box_h / h);
+ if rotate && fit(h, w) > fit(w, h) * 1.001 {
+ t.execute("image.imageRotation.90cw", json!({}))?;
+ }
+ let (w, h) = t.active().map(|d| (f64::from(d.doc.size.width), f64::from(d.doc.size.height))).unwrap_or((1.0, 1.0));
+ let k = fit(w, h);
+ let (tw, th) = ((w * k).round().max(1.0), (h * k).round().max(1.0));
+ t.execute("image.imageSize", json!({"width": tw, "height": th, "resample": "bicubic"}))?;
+ let d = &t.active().ok_or(EngineError::NoDocument)?.doc;
+ let buf = photocraft_compose::flatten(d);
+ let ox = (x0 + (cell_w - tw) / 2.0).round() as i32;
+ let oy = (y0 + (box_h - th) / 2.0).round() as i32;
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; buf.px.len() * n];
+ for (px, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) {
+ photocraft_raster::from_rgba_into(&fmt, *px, out);
+ }
+ let mut surf = photocraft_doc::Surface::new(fmt);
+ surf.write_region(photocraft_geom::Rect::new(ox, oy, ox + tw as i32, oy + th as i32), &data);
+ Ok(surf)
+ })();
+ let surf = match thumb {
+ Ok(s) => s,
+ Err(e) => {
+ errors.push(json!({"file": path, "error": e.to_string()}));
+ continue;
+ }
+ };
+ let label = stem(path);
+ s.edit("Contact Sheet", |doc, active| {
+ let l = Layer::new(label.clone(), LayerContent::Raster(surf));
+ *active = Some(l.id);
+ doc.layers.push(l);
+ Ok(())
+ })?;
+ placed += 1;
+ if caption {
+ let size_pt = font_pt;
+ let baseline = y0 + box_h + caption_px * 0.72;
+ s.execute("type.create", json!({"x": x0 + cell_w / 2.0, "y": baseline, "text": label, "font": font, "size": size_pt, "align": "center", "color": [0.0, 0.0, 0.0], "name": label}))?;
+ }
+ }
+ if flatten {
+ s.execute("layer.flattenImage", json!({}))?;
+ }
+ docs.push(idx);
+ }
+ Ok(json!({"documents": docs, "pages": docs.len(), "images": placed, "errors": errors, "width": pw, "height": ph}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ let native = crate::file_cmds::native;
+ vec![
+ spec!("file.automate.contactSheetII", "Contact Sheet II…", &["File", "Automate"], r##"{"input":folder|[paths],"units":"inches|cm|mm|pixels"="inches","width":8,"height":10,"resolution":ppi=300,"mode":"rgb|gray|cmyk|lab"="rgb","depth":8|16=8,"columns":5,"rows":6,"placeAcrossFirst":bool=true,"autoSpacing":bool=true,"horizontal":units?,"vertical":units?,"rotateForBestFit":bool=false,"caption":bool=true (file name as caption),"font":family?,"fontSize":pt=12,"flatten":bool=false} → {documents, pages, images}"##, native, contact_sheet),
+ spec!("file.automate.createDroplet", "Create Droplet…", &["File", "Automate"], r##"{"path":str (.pcdroplet),"steps":[[id,params]…] (the action),"name":str?,"output":folder?,"format":"same|png|jpg|…"?,"quality":0..12?,"shim":bool=true on macOS/Linux (writes <name>.command calling `photocraft-cli droplet`)} → {path, shim}"##, native, create_droplet),
+ spec!("file.automate.runDroplet", "Run Droplet", &[], r##"{"droplet":path,"input":[files or folders],"output":folder? (default: droplet's, else <input folder>/droplet-output)} → {files, errors}"##, native, run_droplet),
+ spec!("file.scripts.statistics", "Statistics…", &["File", "Scripts"], r##"{"mode":"mean|median|maximum|minimum|range|summation|variance|standardDeviation|skewness|kurtosis|entropy"="median","input":folder|[paths],"align":bool=false (Auto-Align first)} → new document with one stack-mode smart object"##, native, statistics),
+ spec!("file.scripts.browse", "Browse…", &["File", "Scripts"], r##"{"path":script file | "script":text | "steps":[[id,params]…]} (JSON action, or one `command.id {json}` per line) → {steps, ok, results}"##, |_| Ok(()), browse),
+ spec!("file.scripts.scriptEventsManager", "Script Events Manager…", &["File", "Scripts"], r##"{"enabled":bool?,"add":{"event":"startApplication|newDocument|openDocument|saveDocument|closeDocument|print|export|everything","script":path?|"steps":[…]?,"name":str?}?,"remove":index?,"removeAll":bool?} → {enabled, bindings, events}"##, |_| Ok(()), script_events),
+ ]
+}
+
+#[cfg(test)]
+#[path = "automate_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/automate_cmds/tests.rs
new file mode 100644
index 000000000..2f862bda9
--- /dev/null
+++ b/crates/engine/src/automate_cmds/tests.rs
@@ -0,0 +1,148 @@
+use super::*;
+
+fn tmp(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("photocraft-automate-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d.to_string_lossy().into_owned()
+}
+
+/// Writes `n` small PNGs (w×h, grey level i·40) into `dir`.
+fn images(dir: &str, n: usize, w: u32, h: u32) -> Vec<String> {
+ (0..n)
+ .map(|i| {
+ let mut s = Session::new();
+ let v = (i as f32 * 40.0 + 20.0) / 255.0;
+ s.execute("file.new", json!({"width": w, "height": h, "background": format!("#{:02x}{:02x}{:02x}", (v * 255.0) as u8, (v * 255.0) as u8, (v * 255.0) as u8)})).unwrap();
+ let path = format!("{dir}/img{i}.png");
+ crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap();
+ path
+ })
+ .collect()
+}
+
+#[test]
+fn scripts_parse_json_and_lines() {
+ let a = parse_script(r#"[["file.new", {"width": 10}], {"command": "layer.flattenImage"}, "edit.undo"]"#).unwrap();
+ assert_eq!(a.len(), 3);
+ assert_eq!(a[0].1["width"], 10);
+ let b = parse_script("# make a doc\nfile.new {\"width\": 12, \"height\": 8}\n\nimage.imageRotation.90cw\n").unwrap();
+ assert_eq!(b.len(), 2);
+ assert_eq!(b[1].0, "image.imageRotation.90cw");
+ let c = parse_script(r#"{"photocraftDroplet":1,"action":{"steps":[["file.new",{}]]}}"#).unwrap();
+ assert_eq!(c.len(), 1);
+ assert!(parse_script("file.new {bad json").is_err());
+}
+
+#[test]
+fn browse_runs_a_script_file() {
+ let dir = tmp("browse");
+ let path = format!("{dir}/make.txt");
+ std::fs::write(&path, "file.new {\"width\": 30, \"height\": 20}\nimage.imageRotation.90cw\n").unwrap();
+ let mut s = Session::new();
+ let r = s.execute("file.scripts.browse", json!({"path": path})).unwrap();
+ assert_eq!(r["ok"], true);
+ let d = &s.active().unwrap().doc;
+ assert_eq!((d.size.width, d.size.height), (20, 30));
+ assert!(s.execute("file.scripts.browse", json!({"script": "no.such.command"})).is_err());
+ // A failing step stops the script and is reported.
+ let r = s.execute("file.scripts.browse", json!({"steps": [["layer.delete", {"layer": 999_999}], ["image.imageRotation.90cw", {}]]})).unwrap();
+ assert_eq!(r["results"].as_array().unwrap().len(), 1);
+}
+
+#[test]
+fn script_events_fire_on_new_and_close() {
+ let mut s = Session::new();
+ let r = s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "newDocument", "steps": [["image.imageRotation.90cw", {}]], "name": "Rotate"}})).unwrap();
+ assert_eq!(r["enabled"], true);
+ assert_eq!(r["bindings"].as_array().unwrap().len(), 1);
+ assert!(s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "nope", "steps": []}})).is_err());
+ assert!(s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "print", "steps": [["no.such", {}]]}})).is_err());
+ s.execute("file.new", json!({"width": 40, "height": 10})).unwrap();
+ let d = &s.active().unwrap().doc;
+ assert_eq!((d.size.width, d.size.height), (10, 40), "the New Document action rotated it");
+ assert_eq!(s.file_menu.event_log.len(), 1);
+ // Events don't re-enter: the script's own commands fire nothing.
+ s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "closeDocument", "steps": [["file.new", {"width": 5, "height": 5}]]}})).unwrap();
+ s.execute("file.close", json!({})).unwrap();
+ assert_eq!(s.documents().len(), 1, "closing ran the script, which made a new document");
+ assert_eq!(s.documents()[0].doc.size.width, 5, "…without the New Document rotation");
+ // Disabled: nothing fires.
+ s.execute("file.scripts.scriptEventsManager", json!({"enabled": false})).unwrap();
+ s.execute("file.new", json!({"width": 40, "height": 10})).unwrap();
+ assert_eq!(s.active().unwrap().doc.size.width, 40);
+ let r = s.execute("file.scripts.scriptEventsManager", json!({"removeAll": true})).unwrap();
+ assert!(r["bindings"].as_array().unwrap().is_empty());
+ assert_eq!(r["events"].as_array().unwrap().len(), EVENTS.len());
+}
+
+#[test]
+fn droplets_are_written_and_run() {
+ let dir = tmp("droplet");
+ let inputs = images(&dir, 2, 40, 20);
+ let mut s = Session::new();
+ let path = format!("{dir}/Rotate");
+ let r = s.execute("file.automate.createDroplet", json!({"path": path, "steps": [["image.imageRotation.90cw", {}]], "format": "png", "output": format!("{dir}/out")})).unwrap();
+ let dp = r["path"].as_str().unwrap().to_string();
+ assert!(dp.ends_with("Rotate.pcdroplet"));
+ let v: Value = serde_json::from_slice(&std::fs::read(&dp).unwrap()).unwrap();
+ assert_eq!(v["photocraftDroplet"], 1);
+ #[cfg(unix)]
+ {
+ let shim = r["shim"].as_str().unwrap();
+ let text = std::fs::read_to_string(shim).unwrap();
+ assert!(text.starts_with("#!/bin/sh") && text.contains("droplet"));
+ use std::os::unix::fs::PermissionsExt;
+ assert_ne!(std::fs::metadata(shim).unwrap().permissions().mode() & 0o111, 0, "executable");
+ }
+ let r = s.execute("file.automate.runDroplet", json!({"droplet": dp, "input": [dir.clone()]})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}");
+ let out = photocraft_codecs::decode(&std::fs::read(format!("{dir}/out/img0.png")).unwrap()).unwrap();
+ assert_eq!(out.dimensions(), (20, 40));
+ assert!(s.execute("file.automate.createDroplet", json!({"path": path, "steps": [["bogus", {}]]})).is_err());
+}
+
+#[test]
+fn statistics_makes_a_stack_mode_smart_object() {
+ let dir = tmp("stats");
+ let files = images(&dir, 3, 16, 12);
+ let mut s = Session::new();
+ let r = s.execute("file.scripts.statistics", json!({"mode": "mean", "input": files})).unwrap();
+ assert_eq!(r["images"], 3);
+ let d = &s.active().unwrap().doc;
+ assert_eq!(d.layers.len(), 1);
+ let LayerContent::Smart(so) = &d.layers[0].content else { panic!("not a smart object") };
+ assert_eq!(so.stack_mode, Some(photocraft_doc::StackMode::Mean));
+ // Mean of 20, 60, 100 = 60.
+ let px = photocraft_compose::flatten(d).px[0];
+ assert!((px[0] * 255.0 - 60.0).abs() < 1.5, "{px:?}");
+ assert!(s.execute("file.scripts.statistics", json!({"mode": "average", "input": dir})).is_err());
+}
+
+#[test]
+fn contact_sheet_places_thumbnails_with_captions() {
+ let dir = tmp("contact");
+ images(&dir, 5, 60, 30);
+ for depth in [8, 16] {
+ let mut s = Session::new();
+ let r = s
+ .execute("file.automate.contactSheetII", json!({"input": dir, "units": "pixels", "width": 400, "height": 300, "resolution": 72, "columns": 2, "rows": 2, "depth": depth, "fontSize": 10, "rotateForBestFit": true}))
+ .unwrap();
+ assert_eq!(r["pages"], 2, "5 images on 2×2 sheets");
+ assert_eq!(r["images"], 5);
+ let first = r["documents"][0].as_u64().unwrap() as usize;
+ let d = &s.documents()[first].doc;
+ assert_eq!((d.size.width, d.size.height), (400, 300));
+ let names: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect();
+ assert!(names.contains(&"img0") && names.contains(&"img3"), "{names:?}");
+ let texts = d.layers.iter().filter(|l| matches!(l.content, LayerContent::Text(_))).count();
+ assert_eq!(texts, 4, "a caption per image");
+ let thumb = d.layers.iter().find(|l| l.name == "img0" && matches!(l.content, LayerContent::Raster(_))).unwrap();
+ let b = thumb.surface().unwrap().content_bounds();
+ assert!(b.width() <= 200 && b.height() < 150, "fits its cell: {b:?}");
+ // Flattened variant.
+ let r = s.execute("file.automate.contactSheetII", json!({"input": dir, "units": "pixels", "width": 200, "height": 200, "columns": 3, "rows": 2, "caption": false, "flatten": true})).unwrap();
+ let d = &s.documents()[r["documents"][0].as_u64().unwrap() as usize].doc;
+ assert_eq!(d.layers.len(), 1);
+ }
+}
diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs
index 3108bb094..464ac26e1 100644
--- a/crates/engine/src/color_cmds.rs
+++ b/crates/engine/src/color_cmds.rs
@@ -35,6 +35,9 @@ pub struct ProofSetup {
pub bpc: bool,
/// Simulate paper colour (absolute colorimetric proof → display, black ink simulated).
pub simulate_paper: bool,
+ /// What is simulated: the profile itself, one or more of its plates, an RGB display or a
+ /// colour vision deficiency (see `proof_sim`).
+ pub kind: crate::proof_sim::ProofKind,
}
impl Default for ProofSetup {
@@ -45,6 +48,7 @@ impl Default for ProofSetup {
intent: Intent::RelativeColorimetric,
bpc: true,
simulate_paper: false,
+ kind: crate::proof_sim::ProofKind::Profile,
}
}
}
@@ -183,6 +187,8 @@ pub struct ColorState {
/// Monitor profile bytes supplied by the platform (`None` = sRGB display).
pub monitor_profile: Option<Arc<Vec<u8>>>,
display_cache: Mutex<HashMap<DisplayKey, Arc<Transform>>>,
+ /// View › 32-bit Preview Options per document.
+ pub hdr: HashMap<DocId, crate::proof_sim::HdrPreview>,
}
impl ColorState {
@@ -256,7 +262,7 @@ impl ColorState {
self.proofs.get(&doc).cloned().unwrap_or_else(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
}
- fn proof_mut(&mut self, doc: DocId) -> &mut ProofView {
+ pub(crate) fn proof_mut(&mut self, doc: DocId) -> &mut ProofView {
self.proofs.entry(doc).or_insert_with(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
}
@@ -299,6 +305,9 @@ impl ColorState {
/// The display transform as an `size³` RGBA 3D LUT (upload with
/// [`Lut3d::to_rgba16f_bytes`] and apply in the canvas shader).
pub fn display_lut(&self, doc: &Document, size: usize) -> Result<Lut3d> {
+ if let Some(lut) = crate::proof_sim::display_lut(self, doc, size)? {
+ return Ok(lut);
+ }
let t = self.display_transform(doc)?;
Ok(Lut3d::from_transform(&t, size))
}
@@ -308,7 +317,7 @@ impl ColorState {
/// out of the proof gamut (only with Gamut Warning on).
pub fn canvas_lut(&self, doc: &Document, size: usize) -> Result<Option<Vec<u8>>> {
let pv = self.proof(doc.id);
- if !pv.enabled && !pv.gamut_warning {
+ if !pv.enabled && !pv.gamut_warning && !crate::proof_sim::hdr_active(self, doc) {
return Ok(None);
}
let lut = self.display_lut(doc, size)?;
@@ -595,6 +604,9 @@ pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc:
/// default the mode's working profile), `intent` (default relative), `bpc` (default true).
pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value> {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ if doc.mode == ColorMode::Multichannel && mode != ColorMode::Multichannel {
+ return crate::multichannel_cmds::convert_from(s, mode, p);
+ }
if doc.mode == mode && p.get("profile").is_none() {
return Ok(Value::Null);
}
@@ -708,7 +720,7 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
let name = p.get("profile").and_then(Value::as_str).unwrap_or("working-cmyk").to_string();
let profile = s.color.resolve(&name, Some(&doc), Some(ColorMode::Cmyk))?;
let intent = intent_param(p)?;
- let setup = ProofSetup { name, profile, intent, bpc: bool_param(p, "bpc", true), simulate_paper: bool_param(p, "simulatePaper", false) };
+ let setup = ProofSetup { name, profile, intent, bpc: bool_param(p, "bpc", true), simulate_paper: bool_param(p, "simulatePaper", false), kind: crate::proof_sim::ProofKind::Profile };
let pv = s.color.proof_mut(id);
pv.setup = setup.clone();
Ok(json!({ "profile": setup.profile.description, "intent": setup.intent.id(), "bpc": setup.bpc, "simulatePaper": setup.simulate_paper, "proofColors": pv.enabled }))
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index a1116a569..617742849 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -252,7 +252,7 @@ pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment {
fn build() -> Vec<CommandSpec> {
let mut v = vec![
// File
- cmd!("file.new", "New…", ["File"], Some("Cmd+N"), r##"{"width":u32=1920,"height":u32=1080,"mode":"rgb|gray|cmyk|lab"="rgb","depth":8|16|32=8,"background":"white|black|transparent|#rrggbb"="white","name":str}"##, always, |s, p| {
+ cmd!("file.new", "New…", ["File"], Some("Cmd+N"), r##"{"width":u32=1920,"height":u32=1080,"mode":"rgb|gray|cmyk|lab"="rgb","depth":8|16|32=8,"background":"white|black|backgroundColor|transparent|#rrggbb"="white","resolution":ppi=72,"name":str}"##, always, |s, p| {
let w = p.get("width").and_then(Value::as_u64).unwrap_or(1920).clamp(1, 300_000) as u32;
let h = p.get("height").and_then(Value::as_u64).unwrap_or(1080).clamp(1, 300_000) as u32;
let mode = match p.get("mode").and_then(Value::as_str).unwrap_or("rgb") {
@@ -267,7 +267,10 @@ fn build() -> Vec<CommandSpec> {
_ => SampleType::U8,
};
let name = p.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_string();
- let doc = match p.get("background").and_then(Value::as_str).unwrap_or("white") {
+ let res = p.get("resolution").and_then(Value::as_f64).unwrap_or(72.0).clamp(1.0, 30_000.0) as f32;
+ let bgc = s.tools.background;
+ let mut doc = match p.get("background").and_then(Value::as_str).unwrap_or("white") {
+ "backgroundColor" => Document::with_background(name, Size::new(w, h), mode, depth, Color::rgba(bgc[0], bgc[1], bgc[2], 1.0)),
"transparent" => {
let mut d = Document::new(name, Size::new(w, h), mode, depth);
d.layers.push(Layer::raster("Layer 1", d.pixel_format()));
@@ -279,6 +282,7 @@ fn build() -> Vec<CommandSpec> {
Document::with_background(name, Size::new(w, h), mode, depth, Color::rgba(c[0], c[1], c[2], c[3]))
}
};
+ doc.resolution_dpi = res;
let i = s.add_document(doc, None);
Ok(json!({ "document": i }))
}),
@@ -346,22 +350,37 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(Value::Null)
}),
- cmd!("select.rect", "Rectangular Selection", [], None, r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false}"##, has_doc, |s, p| {
+ cmd!("select.rect", "Rectangular Selection", [], None, r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false,"antiAlias":bool=true,"feather":px=0}"##, has_doc, |s, p| {
let get = |k: &str| int(p, k).ok_or_else(|| bad("select.rect", format!("missing `{k}`")));
let r = Rect::from_xywh(get("x")? as i32, get("y")? as i32, get("width")?.max(0) as u32, get("height")?.max(0) as u32);
let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string();
let ellipse = p.get("ellipse").and_then(Value::as_bool).unwrap_or(false);
+ // Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only).
+ let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
+ let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32;
s.edit("Rectangular Marquee", |doc, _| {
let mut shape = Surface::new(photocraft_color::PixelFormat::GRAY8);
if ellipse {
let (cx, cy) = ((r.x0 + r.x1) as f32 / 2.0, (r.y0 + r.y1) as f32 / 2.0);
let (rx, ry) = (r.width() as f32 / 2.0, r.height() as f32 / 2.0);
+ let inside = |x: f32, y: f32| {
+ let (dx, dy) = ((x - cx) / rx, (y - cy) / ry);
+ dx * dx + dy * dy <= 1.0
+ };
for y in r.y0..r.y1 {
for x in r.x0..r.x1 {
- let dx = (x as f32 + 0.5 - cx) / rx;
- let dy = (y as f32 + 0.5 - cy) / ry;
- if dx * dx + dy * dy <= 1.0 {
- shape.write_pixel(x, y, &[1.0]);
+ let (fx, fy) = (x as f32, y as f32);
+ let corners = [(fx, fy), (fx + 1.0, fy), (fx, fy + 1.0), (fx + 1.0, fy + 1.0)].iter().filter(|(a, b)| inside(*a, *b)).count();
+ let cov = if !aa {
+ if inside(fx + 0.5, fy + 0.5) { 1.0 } else { 0.0 }
+ } else if corners == 4 {
+ 1.0
+ } else {
+ let n = (0..16).filter(|i| inside(fx + ((i % 4) as f32 + 0.5) / 4.0, fy + ((i / 4) as f32 + 0.5) / 4.0)).count();
+ n as f32 / 16.0
+ };
+ if cov > 0.0 {
+ shape.write_pixel(x, y, &[cov]);
}
}
}
@@ -369,6 +388,12 @@ fn build() -> Vec<CommandSpec> {
shape.fill_rect(r, &[1.0]);
}
let area = doc.bounds();
+ if feather > 0.0 {
+ use photocraft_algo::selection as sel;
+ let m = sel::feather(&sel::mask_from_surface(Some(&shape), area), area.width() as usize, area.height() as usize, feather);
+ doc.selection = sel::combine(doc.selection.as_ref(), &m, area, sel::SelectionMode::parse(&mode));
+ return Ok(());
+ }
let old = doc.selection.take();
let combined = match (mode.as_str(), old) {
("add", Some(o)) => combine(&o, &shape, area, |a, b| a.max(b)),
@@ -407,8 +432,14 @@ fn build() -> Vec<CommandSpec> {
}
let id = layer_param(s, p)?;
let nid = s.edit("Duplicate Layer", |doc, active| {
- let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();
+ let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ // A copy of the Background layer is an ordinary, unlocked layer (Photoshop).
+ let from_background = src.name == "Background" && src.locks.transparency && doc.layers.first().is_some_and(|b| b.id == id);
+ let mut dup = src.duplicate();
dup.name = format!("{} copy", dup.name);
+ if from_background {
+ dup.locks = Default::default();
+ }
let nid = doc.insert_above(Some(id), dup);
*active = Some(nid);
Ok(nid)
@@ -755,6 +786,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::layer_style::specs());
v.extend(crate::filters::specs());
v.extend(crate::filters_ext::specs());
+ v.extend(crate::gallery_cmds::specs());
v.extend(crate::type_cmds::specs());
v.extend(crate::transform_cmds::specs());
v.extend(crate::vector_cmds::specs());
@@ -765,24 +797,41 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::retouch_cmds::specs());
v.extend(crate::image_cmds::specs());
v.extend(crate::selection_cmds::specs());
+ v.extend(crate::select_extra_cmds::specs());
v.extend(crate::paint_cmds::specs());
v.extend(crate::extra_cmds::specs());
v.extend(crate::file_cmds::specs());
v.extend(crate::type_extra_cmds::specs());
+ v.extend(crate::type_styles_cmds::specs());
+ v.extend(crate::type_spell_cmds::specs());
v.extend(crate::smart_cmds::specs());
v.extend(crate::layer_multi_cmds::specs());
v.extend(crate::prefs::specs());
v.extend(crate::edit_menu_cmds::specs());
v.extend(crate::align_cmds::specs());
+ v.extend(crate::photo_cmds::specs());
+ v.extend(crate::lens_cmds::specs());
+ v.extend(crate::vp_cmds::specs());
v.extend(crate::channel_cmds::specs());
v.extend(crate::adjust_cmds::specs());
v.extend(crate::layer_menu_cmds::specs());
v.extend(crate::mode_cmds::specs());
+ v.extend(crate::multichannel_cmds::specs());
v.extend(crate::pattern_cmds::specs());
v.extend(crate::warp_cmds::specs());
v.extend(crate::comps_cmds::specs());
v.extend(crate::artboard_cmds::specs());
v.extend(crate::distort_cmds::specs());
+ v.extend(crate::analysis_cmds::specs());
+ v.extend(crate::notes_cmds::specs());
+ v.extend(crate::proof_sim::specs());
+ v.extend(crate::presets::specs());
+ v.extend(crate::render_cmds::specs());
+ v.extend(crate::slice_cmds::specs());
+ v.extend(crate::web_cmds::specs());
+ v.extend(crate::automate_cmds::specs());
+ v.extend(crate::print_cmds::specs());
+ v.extend(crate::pick_cmds::specs());
v
}
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
index e97e3c280..6230ef678 100644
--- a/crates/engine/src/edit_menu_cmds.rs
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -496,7 +496,7 @@ fn define_brush_preset(s: &mut Session, p: &Value) -> Result<Value> {
/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the
/// active shape layer, the active layer's vector mask, or the last saved path.
-fn current_path(doc: &Document, active: Option<LayerId>, spec: Option<&str>) -> Option<Path> {
+pub(crate) fn current_path(doc: &Document, active: Option<LayerId>, spec: Option<&str>) -> Option<Path> {
let ok = |p: &Path| !p.subpaths.is_empty();
match spec {
Some("work") => return doc.work_path.clone().filter(ok),
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index af806bfdd..5a001cb24 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -75,11 +75,11 @@ fn is_file(_path: &str) -> bool {
}
#[cfg(not(target_arch = "wasm32"))]
-fn read_file(path: &str) -> Result<Vec<u8>> {
+pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
#[cfg(target_arch = "wasm32")]
-fn read_file(path: &str) -> Result<Vec<u8>> {
+pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
Err(EngineError::Other(format!("cannot read {path}: no file system on the web")))
}
@@ -97,7 +97,7 @@ pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
/// Files of a folder that look like images we can open, sorted by name.
#[cfg(not(target_arch = "wasm32"))]
-fn list_images(dir: &str) -> Result<Vec<String>> {
+pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {
let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?;
let mut out: Vec<String> = rd
.filter_map(|e| e.ok())
@@ -109,14 +109,14 @@ fn list_images(dir: &str) -> Result<Vec<String>> {
Ok(out)
}
#[cfg(target_arch = "wasm32")]
-fn list_images(dir: &str) -> Result<Vec<String>> {
+pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {
Err(EngineError::Other(format!("cannot list {dir}: no file system on the web")))
}
/// Extensions the batch commands pick up from a folder.
const OPENABLE: &[&str] = &["psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm"];
-fn file_name(path: &str) -> String {
+pub(crate) fn file_name(path: &str) -> String {
path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
}
@@ -145,7 +145,7 @@ pub(crate) fn sanitize(name: &str) -> String {
if s.is_empty() { "layer".into() } else { s }
}
-fn import(name: &str, bytes: &[u8]) -> Result<Document> {
+pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
photocraft_io::import(name, bytes).map(|r| r.document).map_err(|e| EngineError::Other(format!("{name}: {e}")))
}
@@ -180,7 +180,7 @@ fn size_param(p: &Value, key: &str) -> Option<f64> {
// ---------- pixels ----------
/// A composite buffer as a surface in `fmt` (straight RGBA → the format's model and depth).
-fn buffer_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface {
+pub(crate) fn buffer_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface {
let n = fmt.channels();
let mut data = vec![0.0f32; buf.px.len() * n];
for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) {
@@ -195,7 +195,7 @@ fn buffer_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface
}
/// The flattened image of `doc` as a surface in `fmt`, placed at the origin.
-fn flattened(doc: &Document, fmt: PixelFormat) -> Surface {
+pub(crate) fn flattened(doc: &Document, fmt: PixelFormat) -> Surface {
buffer_surface(&photocraft_compose::flatten(doc), fmt)
}
@@ -566,7 +566,7 @@ fn parse_steps(v: &Value) -> Result<Vec<(String, Value)>> {
}
/// Inputs of a batch command: `"input"` is a folder or an array of files.
-fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
+pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
match p.get("input").or_else(|| p.get("files")) {
Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()),
Some(Value::String(dir)) => list_images(dir),
@@ -576,7 +576,7 @@ fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format`
/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal.
-fn process_files(inputs: &[String], output: &str, format: &str, quality: Option<f64>, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
+pub(crate) fn process_files(inputs: &[String], output: &str, format: &str, quality: Option<f64>, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
let mut files = Vec::new();
let mut errors = Vec::new();
for path in inputs {
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs
index d5d95119c..34f2c9812 100644
--- a/crates/engine/src/filters.rs
+++ b/crates/engine/src/filters.rs
@@ -134,6 +134,10 @@ pub fn apply_filter_to_surface(
if let Some(out) = crate::distort_cmds::apply_to_surface(id, params, surf, canvas) {
return Some(out);
}
+ // Lens Correction / Adaptive Wide Angle / Camera Raw smart filters (lens_cmds).
+ if let Some(out) = crate::lens_cmds::apply_to_surface(id, params, surf, canvas) {
+ return Some(out);
+ }
let fp = params_for(id, params)?;
let sel_bounds = selection.map(photocraft_raster::Surface::content_bounds);
let content = surf.content_bounds();
diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs
index 244a9b5a9..0eab06b22 100644
--- a/crates/engine/src/filters_ext.rs
+++ b/crates/engine/src/filters_ext.rs
@@ -357,13 +357,13 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
// ---- Video ----
"filter.video.deInterlace" => FilterParams::DeInterlace { eliminate_even: s(p, "eliminate", "oddFields") == "evenFields", interpolate: s(p, "createBy", "interpolation") != "duplication" },
"filter.video.ntscColors" => FilterParams::NtscColors,
- _ => return None,
+ _ => return crate::gallery_cmds::params_for(id, p),
})
}
/// Ids whose rendering uses the foreground/background colours.
fn uses_colours(id: &str) -> bool {
- matches!(id, "filter.render.fibers" | "filter.stylize.tiles" | "filter.pixelate.pointillize")
+ matches!(id, "filter.render.fibers" | "filter.stylize.tiles" | "filter.pixelate.pointillize") || crate::gallery_cmds::uses_colours(id)
}
/// Fills in session state a filter reads (the current colours) as explicit params, so the
diff --git a/crates/engine/src/gallery_cmds.rs b/crates/engine/src/gallery_cmds.rs
new file mode 100644
index 000000000..4622f78a0
--- /dev/null
+++ b/crates/engine/src/gallery_cmds.rs
@@ -0,0 +1,157 @@
+//! Filter › Filter Gallery… (`filter.filterGallery`) and one command per gallery filter
+//! (`filter.gallery.<key>`, not in menus).
+//!
+//! `filter.filterGallery {effects:[{filter, params, visible}]}` applies a stack of effect layers
+//! in order (the gallery dialog's effect list, bottom to top). Like every filter it goes through
+//! [`crate::filters::run_filter`]: selection, smart objects (recorded as a smart filter),
+//! history, channels and `filter.lastFilter` all work. The foreground/background colours the
+//! Sketch filters read are recorded as explicit params, so smart filters re-render identically.
+
+use photocraft_algo::{FilterParams, GalleryEffect, GalleryFilter, GalleryParamKind};
+use serde_json::{Map, Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// Straight RGBA colour from `[r, g, b(, a)]` (0–1) or `#rrggbb`.
+fn colour(v: Option<&Value>) -> Option<[f32; 4]> {
+ match v? {
+ Value::Array(a) if a.len() >= 3 => {
+ let c = |j: usize, d: f32| a.get(j).and_then(Value::as_f64).map_or(d, |v| v as f32);
+ Some([c(0, 0.0), c(1, 0.0), c(2, 0.0), c(3, 1.0)])
+ }
+ Value::String(h) if h.len() == 7 && h.starts_with('#') => {
+ let ch = |j: usize| u8::from_str_radix(&h[j..j + 2], 16).map_or(0.0, |v| v as f32 / 255.0);
+ Some([ch(1), ch(3), ch(5), 1.0])
+ }
+ _ => None,
+ }
+}
+
+/// One effect from its params object (`fallback` supplies colours not given per effect).
+pub fn effect_from_json(filter: GalleryFilter, p: &Value, fallback: &Value) -> GalleryEffect {
+ let mut e = GalleryEffect::new(filter);
+ for prm in filter.params() {
+ let Some(v) = p.get(prm.key) else { continue };
+ match (&prm.kind, v) {
+ (GalleryParamKind::Choice(_), Value::String(name)) => {
+ e.set_choice(prm.key, name);
+ }
+ (_, Value::Bool(b)) => e.set(prm.key, *b as u8 as f32),
+ (_, v) => {
+ if let Some(n) = v.as_f64() {
+ e.set(prm.key, n as f32);
+ }
+ }
+ }
+ }
+ let pick = |k: &str| colour(p.get(k)).or_else(|| colour(fallback.get(k)));
+ if let Some(c) = pick("foreground") {
+ e.foreground = c;
+ }
+ if let Some(c) = pick("background") {
+ e.background = c;
+ }
+ if let Some(c) = pick("glowColor") {
+ e.color = c;
+ }
+ e
+}
+
+/// The effect stack of a `filter.filterGallery` params object. Entries are
+/// `{"filter": "<key>", "params": {...}, "visible": bool}` (params may also sit beside
+/// `filter`); hidden entries are skipped.
+pub fn effects_from_json(p: &Value) -> std::result::Result<Vec<GalleryEffect>, String> {
+ let Some(list) = p.get("effects").and_then(Value::as_array) else { return Ok(Vec::new()) };
+ let mut out = Vec::new();
+ for (k, item) in list.iter().enumerate() {
+ if item.get("visible").and_then(Value::as_bool) == Some(false) {
+ continue;
+ }
+ let key = item.get("filter").and_then(Value::as_str).ok_or_else(|| format!("effect {k}: missing `filter`"))?;
+ let f = GalleryFilter::from_key(key).ok_or_else(|| format!("effect {k}: unknown gallery filter `{key}`"))?;
+ let params = item.get("params").filter(|v| v.is_object()).unwrap_or(item);
+ out.push(effect_from_json(f, params, p));
+ }
+ Ok(out)
+}
+
+/// Algorithm parameters for the ids this module owns.
+pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
+ if id == "filter.filterGallery" {
+ return Some(FilterParams::FilterGallery { effects: effects_from_json(p).unwrap_or_default() });
+ }
+ let f = id.strip_prefix("filter.gallery.").and_then(GalleryFilter::from_key)?;
+ Some(FilterParams::FilterGallery { effects: vec![effect_from_json(f, p, &Value::Null)] })
+}
+
+/// Whether the command reads the foreground/background colours.
+pub(crate) fn uses_colours(id: &str) -> bool {
+ id == "filter.filterGallery" || id.strip_prefix("filter.gallery.").and_then(GalleryFilter::from_key).is_some_and(GalleryFilter::uses_colours)
+}
+
+/// The gallery catalogue for dialogs and agents: categories, filters and parameter notation.
+pub fn catalogue() -> Value {
+ let filters: Vec<Value> = GalleryFilter::ALL
+ .iter()
+ .map(|f| json!({"key": f.key(), "name": f.name(), "category": f.category(), "command": f.command_id(), "params": f.params_doc()}))
+ .collect();
+ json!({"categories": photocraft_algo::GALLERY_CATEGORIES, "filters": filters})
+}
+
+fn run_gallery(s: &mut Session, p: &Value) -> Result<Value> {
+ if p.get("list").and_then(Value::as_bool) == Some(true) {
+ return Ok(catalogue());
+ }
+ let effects = effects_from_json(p).map_err(EngineError::Other)?;
+ if effects.is_empty() {
+ return Err(EngineError::Other("filter.filterGallery needs `effects`: [{\"filter\": \"<key>\", \"params\": {...}}] (pass {\"list\": true} for the catalogue)".into()));
+ }
+ // Normalize the recorded params (journal / smart filter) to the canonical form.
+ let mut q: Map<String, Value> = p.as_object().cloned().unwrap_or_default();
+ q.remove("list");
+ crate::filters::run_filter(s, "filter.filterGallery", &Value::Object(q))
+}
+
+macro_rules! gallery_specs {
+ ($($v:ident),* $(,)?) => {
+ vec![$(
+ CommandSpec {
+ id: GalleryFilter::$v.command_id(),
+ label: GalleryFilter::$v.name(),
+ menu: &[],
+ shortcut: None,
+ params: GalleryFilter::$v.params_doc(),
+ enabled: crate::filters::has_filterable_layer,
+ run: |s, p| crate::filters::run_filter(s, GalleryFilter::$v.command_id(), p),
+ journal: true,
+ }
+ ),*]
+ };
+}
+
+/// The command specs.
+pub fn specs() -> Vec<CommandSpec> {
+ let mut v = vec![CommandSpec {
+ id: "filter.filterGallery",
+ label: "Filter Gallery…",
+ menu: &["Filter"],
+ shortcut: None,
+ params: r##"{"effects":json,"foreground":json,"background":json,"list":bool}"##,
+ enabled: crate::filters::has_filterable_layer,
+ run: run_gallery,
+ journal: true,
+ }];
+ v.extend(gallery_specs![
+ ColoredPencil, Cutout, DryBrush, FilmGrain, Fresco, NeonGlow, PaintDaubs, PaletteKnife, PlasticWrap, PosterEdges, RoughPastels, SmudgeStick, Sponge, Underpainting, Watercolor,
+ AccentedEdges, AngledStrokes, Crosshatch, DarkStrokes, InkOutlines, Spatter, SprayedStrokes, SumiE,
+ DiffuseGlow, Glass, OceanRipple,
+ BasRelief, ChalkCharcoal, Charcoal, Chrome, ConteCrayon, GraphicPen, HalftonePattern, NotePaper, Photocopy, Plaster, Reticulation, Stamp, TornEdges, WaterPaper,
+ GlowingEdges,
+ Craquelure, Grain, MosaicTiles, Patchwork, StainedGlass, Texturizer,
+ ]);
+ v
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/gallery_cmds/tests.rs b/crates/engine/src/gallery_cmds/tests.rs
new file mode 100644
index 000000000..21e6b2973
--- /dev/null
+++ b/crates/engine/src/gallery_cmds/tests.rs
@@ -0,0 +1,139 @@
+use photocraft_geom::Rect;
+use serde_json::json;
+
+use super::*;
+
+const W: i32 = 40;
+const H: i32 = 32;
+
+fn session(depth: u32, mode: &str) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "mode": mode})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("pattern", |doc, active| {
+ let l = doc.layer_mut(active.unwrap()).unwrap();
+ let surf = l.surface_mut().unwrap();
+ let n = surf.channels();
+ for y in 0..H {
+ for x in 0..W {
+ let v = ((x * 7 + y * 3) % 23) as f32 / 22.0;
+ let mut px = vec![1.0; n];
+ for (c, p) in px.iter_mut().enumerate().take(n - 1) {
+ *p = if (x / 10 + y / 8) % 2 == 0 { v } else { 1.0 - v * (c as f32 + 1.0) / 4.0 };
+ }
+ surf.write_pixel(x, y, &px);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+fn pixels(s: &Session) -> Vec<f32> {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, W, H))
+}
+
+#[test]
+fn every_gallery_filter_runs_at_every_depth_and_undoes() {
+ for depth in [8, 16, 32] {
+ for f in GalleryFilter::ALL {
+ let mut s = session(depth, "rgb");
+ let before = pixels(&s);
+ let r = s.execute(f.command_id(), json!({})).unwrap_or_else(|e| panic!("{}: {e}", f.key()));
+ assert!(r.get("filter").is_some());
+ let after = pixels(&s);
+ assert_ne!(after, before, "{} @{depth} changed nothing", f.key());
+ assert!(after.iter().all(|v| v.is_finite() && (-1e-4..=1.0001).contains(v)), "{} @{depth} out of range", f.key());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(pixels(&s), before, "{} undo", f.key());
+ }
+ }
+}
+
+#[test]
+fn gallery_filters_run_in_other_colour_models() {
+ for mode in ["gray", "cmyk", "lab"] {
+ for f in [GalleryFilter::Cutout, GalleryFilter::GraphicPen, GalleryFilter::Texturizer, GalleryFilter::StainedGlass] {
+ let mut s = session(16, mode);
+ let before = pixels(&s);
+ s.execute(f.command_id(), json!({})).unwrap_or_else(|e| panic!("{} {mode}: {e}", f.key()));
+ assert_ne!(pixels(&s), before, "{} {mode}", f.key());
+ }
+ }
+}
+
+#[test]
+fn results_do_not_depend_on_tiling() {
+ let s = session(32, "rgb");
+ let d = s.active().unwrap();
+ let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().clone();
+ let b = Rect::new(0, 0, W, H);
+ for f in GalleryFilter::ALL {
+ let fp = params_for(f.command_id(), &json!({})).unwrap();
+ let big = photocraft_algo::apply_tiled(&surf, &fp, b, b, None, 256, Some(b));
+ let small = photocraft_algo::apply_tiled(&surf, &fp, b, b, None, 16, Some(b));
+ let (a, c) = (big.read_region(b), small.read_region(b));
+ let worst = a.iter().zip(&c).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
+ assert!(worst < 1e-3, "{} differs across tilings by {worst}", f.key());
+ }
+}
+
+#[test]
+fn stack_applies_in_order_and_skips_hidden_layers() {
+ let run = |effects: Value| {
+ let mut s = session(8, "rgb");
+ s.execute("filter.filterGallery", json!({ "effects": effects })).unwrap();
+ pixels(&s)
+ };
+ let one = run(json!([{"filter": "cutout", "params": {"numberOfLevels": 3}}]));
+ let mut single = session(8, "rgb");
+ single.execute("filter.gallery.cutout", json!({"numberOfLevels": 3})).unwrap();
+ assert_eq!(one, pixels(&single), "one-layer gallery = the filter's own command");
+ let ab = run(json!([{"filter": "cutout"}, {"filter": "glowingEdges"}]));
+ let ba = run(json!([{"filter": "glowingEdges"}, {"filter": "cutout"}]));
+ assert_ne!(ab, ba, "order matters");
+ let hidden = run(json!([{"filter": "cutout"}, {"filter": "glowingEdges", "visible": false}]));
+ assert_eq!(hidden, run(json!([{"filter": "cutout"}])));
+}
+
+#[test]
+fn gallery_validates_and_lists() {
+ let mut s = session(8, "rgb");
+ assert!(s.execute("filter.filterGallery", json!({})).is_err());
+ assert!(s.execute("filter.filterGallery", json!({"effects": [{"filter": "nope"}]})).is_err());
+ let list = s.execute("filter.filterGallery", json!({"list": true})).unwrap();
+ assert_eq!(list["filters"].as_array().unwrap().len(), 47);
+ assert_eq!(list["categories"].as_array().unwrap().len(), 6);
+ // Param values clamp to Photoshop's ranges; choices accept names.
+ let e = effect_from_json(GalleryFilter::GraphicPen, &json!({"strokeLength": 99, "strokeDirection": "vertical"}), &Value::Null);
+ assert_eq!(e.get("strokeLength"), 15.0);
+ assert_eq!(e.choice("strokeDirection"), "vertical");
+}
+
+#[test]
+fn sketch_filters_record_and_use_the_current_colours() {
+ let mut s = session(8, "rgb");
+ s.tools.foreground = [1.0, 0.0, 0.0, 1.0];
+ s.tools.background = [0.0, 0.0, 1.0, 1.0];
+ let r = s.execute("filter.gallery.stamp", json!({})).unwrap();
+ assert_eq!(r["filter"]["effects"][0]["foreground"], json!([1.0, 0.0, 0.0, 1.0]));
+ // Stamp is two-tone: every pixel is (close to) red or blue.
+ let px = pixels(&s);
+ assert!(px.chunks(4).all(|c| c[1] < 0.05), "no green in a red/blue stamp");
+ assert!(px.chunks(4).any(|c| c[0] > 0.9) && px.chunks(4).any(|c| c[2] > 0.9));
+}
+
+#[test]
+fn gallery_is_a_smart_filter_on_smart_objects() {
+ let mut s = session(8, "rgb");
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ let r = s.execute("filter.filterGallery", json!({"effects": [{"filter": "texturizer", "params": {"relief": 20}}]}));
+ r.unwrap();
+ let d = s.active().unwrap();
+ let photocraft_doc::LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not smart") };
+ assert_eq!(sm.smart_filters.len(), 1);
+ assert_eq!(sm.smart_filters[0].command, "filter.filterGallery");
+ assert_eq!(sm.smart_filters[0].params["effects"][0]["filter"], json!("texturizer"));
+}
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index 5e32d78c2..77f477eda 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -34,6 +34,7 @@ pub fn document(d: &DocState) -> Value {
"resolution": doc.resolution_dpi,
"activeLayer": d.active_layer.map(|l| l.0),
"selectedLayers": selected.iter().map(|l| l.0).collect::<Vec<_>>(),
+ "isolatedLayers": d.isolated_layers.iter().map(|l| l.0).collect::<Vec<_>>(),
"hasSelection": doc.selection.is_some(),
"selectionBounds": doc.selection.as_ref().map(|s| { let r = s.content_bounds(); [r.x0, r.y0, r.width() as i32, r.height() as i32] }),
"layers": doc.layers.iter().rev().map(|l| layer_sel(l, &selected)).collect::<Vec<_>>(),
@@ -45,6 +46,8 @@ pub fn document(d: &DocState) -> Value {
"quickMask": doc.quick_mask.is_some(),
"layerComps": doc.layer_comps.iter().map(|c| json!({"id": c.id, "name": c.name})).collect::<Vec<_>>(),
"lastAppliedComp": doc.last_applied_comp,
+ "measurement": {"scale": doc.measurement.scale.describe(), "ruler": doc.measurement.ruler.map(|r| json!({"start": r.start, "end": r.end, "protractor": r.protractor})), "count": doc.measurement.count_total(), "countGroups": doc.measurement.count_groups.len()},
+ "notes": doc.notes.iter().map(|n| json!({"author": n.author, "text": n.text, "position": n.position})).collect::<Vec<_>>(),
})
}
diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs
new file mode 100644
index 000000000..cbace72cb
--- /dev/null
+++ b/crates/engine/src/lens_cmds.rs
@@ -0,0 +1,539 @@
+//! Filter › Lens Correction, Filter › Adaptive Wide Angle, Filter › Camera Raw Filter and
+//! File › Automate › Lens Correction (the batch twin).
+//!
+//! The three filters act on the active pixel layer (inside the selection) or, on a smart
+//! object, record a smart filter whose params are fully resolved (EXIF-derived values are
+//! written into them), so re-rendering is deterministic. Algorithms: [`photocraft_algo::lens`],
+//! [`photocraft_algo::wideangle`], [`photocraft_algo::camera_raw`].
+
+use photocraft_algo::camera_raw::{self, CameraRaw};
+use photocraft_algo::exif;
+use photocraft_algo::lens::{self, EdgeMode, LensCorrection};
+use photocraft_algo::transform::Interp;
+use photocraft_algo::wideangle::{self, WideAngle};
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_doc::{Document, LayerContent, LayerId, SmartFilter};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, from_rgba_into};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+pub const LENS: &str = "filter.lensCorrection";
+pub const WIDE: &str = "filter.adaptiveWideAngle";
+pub const RAW: &str = "filter.cameraRaw";
+pub const LENS_BATCH: &str = "file.automate.lensCorrection";
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn num(p: &Value, k: &str, d: f64) -> f64 {
+ p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(d)
+}
+
+fn flag(p: &Value, k: &str, d: bool) -> bool {
+ p.get(k).and_then(Value::as_bool).unwrap_or(d)
+}
+
+// ---------- params ----------
+
+/// Lens Correction settings from params; `exif` resolves `"profile":"auto"`.
+pub fn lens_params(cmd: &str, p: &Value, frame: Rect, info: Option<&exif::CameraInfo>) -> Result<LensCorrection> {
+ let mut lc = LensCorrection {
+ correct_distortion: flag(p, "correctDistortion", true),
+ correct_vignette: flag(p, "correctVignette", true),
+ correct_ca: flag(p, "correctCA", true),
+ distortion: num(p, "distortion", 0.0).clamp(-100.0, 100.0),
+ red_cyan: num(p, "redCyan", 0.0).clamp(-100.0, 100.0),
+ blue_yellow: num(p, "blueYellow", 0.0).clamp(-100.0, 100.0),
+ vignette_amount: num(p, "vignetteAmount", 0.0).clamp(-100.0, 100.0),
+ vignette_midpoint: num(p, "vignetteMidpoint", 50.0).clamp(0.0, 100.0),
+ vertical: num(p, "vertical", 0.0).clamp(-100.0, 100.0),
+ horizontal: num(p, "horizontal", 0.0).clamp(-100.0, 100.0),
+ angle: num(p, "angle", 0.0),
+ scale: num(p, "scale", 100.0).clamp(50.0, 150.0),
+ ..Default::default()
+ };
+ lc.edge = match p.get("edge").and_then(Value::as_str).unwrap_or("transparency") {
+ "transparency" => EdgeMode::Transparency,
+ "edgeExtension" | "extension" => EdgeMode::Extension,
+ "black" => EdgeMode::Color([0.0, 0.0, 0.0, 1.0]),
+ "white" => EdgeMode::Color([1.0, 1.0, 1.0, 1.0]),
+ "background" | "color" => EdgeMode::Color(crate::commands::color_param(p, "edgeColor", [0.0, 0.0, 0.0, 1.0])),
+ other => return Err(bad(cmd, format!("unknown edge `{other}` (transparency|edgeExtension|black|white|color)"))),
+ };
+ let focal = num(p, "focalLength", 0.0);
+ lc.profile = match p.get("profile").and_then(Value::as_str).unwrap_or("none") {
+ "none" | "" => None,
+ "generic" => Some(lens::generic_profile(if focal > 0.0 { focal } else { 50.0 })),
+ "auto" => info.and_then(|i| i.focal_length_35mm.or(i.focal_length)).or((focal > 0.0).then_some(focal)).map(lens::generic_profile),
+ other => return Err(bad(cmd, format!("unknown profile `{other}` (none|auto|generic)"))),
+ };
+ if let Some(Value::Array(line)) = p.get("straighten") {
+ let pt = |v: &Value| -> Option<[f64; 2]> { Some([v.get(0)?.as_f64()?, v.get(1)?.as_f64()?]) };
+ let (Some(a), Some(b)) = (line.first().and_then(pt), line.get(1).and_then(pt)) else {
+ return Err(bad(cmd, "`straighten` is [[x0,y0],[x1,y1]]"));
+ };
+ lc.angle += lens::straighten_angle(a, b);
+ }
+ if flag(p, "autoScale", false) {
+ lc.scale = lens::auto_scale(&lc, frame);
+ }
+ Ok(lc)
+}
+
+/// Writes the resolved profile / angle / scale back into the params (for smart filters).
+fn resolved_lens_params(p: &Value, lc: &LensCorrection) -> Value {
+ let mut q = p.clone();
+ if let Value::Object(m) = &mut q {
+ m.remove("straighten");
+ m.remove("autoScale");
+ m.remove("layer");
+ m.insert("angle".into(), json!(lc.angle));
+ m.insert("scale".into(), json!(lc.scale));
+ match &lc.profile {
+ Some(pr) => {
+ m.insert("profile".into(), json!("generic"));
+ let f = pr.name.trim_start_matches("Generic Lens (").split(' ').next().and_then(|v| v.parse::<f64>().ok()).unwrap_or(50.0);
+ m.insert("focalLength".into(), json!(f));
+ }
+ None => {
+ m.insert("profile".into(), json!("none"));
+ }
+ }
+ }
+ q
+}
+
+/// Adaptive Wide Angle settings; a zero focal length is taken from EXIF when present.
+pub fn wide_params(cmd: &str, p: &Value, info: Option<&exif::CameraInfo>) -> Result<WideAngle> {
+ let mut wa: WideAngle = serde_json::from_value(p.clone()).map_err(|e| bad(cmd, format!("bad params: {e} (constraints: [{{\"a\":[x,y],\"b\":[x,y],\"orientation\":\"free|horizontal|vertical\"}}])")))?;
+ if wa.constraints.iter().any(|c| c.a.iter().chain(&c.b).any(|v| !v.is_finite())) {
+ return Err(bad(cmd, "constraint points must be finite"));
+ }
+ wa.scale = wa.scale.clamp(50.0, 150.0);
+ wa.crop_factor = wa.crop_factor.clamp(0.1, 10.0);
+ if wa.focal_length <= 0.0
+ && let Some(i) = info
+ {
+ if let Some(f) = i.focal_length {
+ wa.focal_length = f;
+ if let Some(f35) = i.focal_length_35mm {
+ wa.crop_factor = (f35 / f).clamp(0.1, 10.0);
+ }
+ } else if let Some(f35) = i.focal_length_35mm {
+ wa.focal_length = f35;
+ wa.crop_factor = 1.0;
+ }
+ }
+ Ok(wa)
+}
+
+/// Camera Raw settings (ACR names in camelCase).
+pub fn raw_params(cmd: &str, p: &Value) -> Result<CameraRaw> {
+ let mut q = p.clone();
+ if let Value::Object(m) = &mut q {
+ m.remove("layer");
+ }
+ serde_json::from_value(q).map_err(|e| bad(cmd, format!("bad params: {e}")))
+}
+
+// ---------- pixels ----------
+
+fn rgba_region(surf: &Surface, area: Rect) -> Vec<[f32; 4]> {
+ let mut v = vec![[0.0f32; 4]; (area.width() * area.height()) as usize];
+ surf.read_rgba_into(area, &mut v);
+ v
+}
+
+/// Camera Raw on a surface over `area` (RGB / Gray via RGBA, at the surface's depth).
+pub fn camera_raw_surface(surf: &Surface, area: Rect, p: &CameraRaw) -> Surface {
+ let area = area.intersect(&surf.content_bounds().union(&area));
+ if area.is_empty() || p.is_identity() {
+ return surf.clone();
+ }
+ let fmt = surf.format();
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let mut px = rgba_region(surf, area);
+ camera_raw::develop(&mut px, w, h, p, fmt.sample == SampleType::F32);
+ let n = fmt.channels();
+ let orig = surf.read_region(area);
+ let mut data = vec![0.0f32; w * h * n];
+ for (i, (q, o)) in px.iter().zip(data.chunks_exact_mut(n)).enumerate() {
+ from_rgba_into(&fmt, *q, o);
+ if fmt.alpha {
+ // Alpha is untouched.
+ o[n - 1] = orig[i * n + n - 1];
+ }
+ }
+ let mut out = surf.clone();
+ out.write_region(area, &data);
+ out.prune();
+ out
+}
+
+/// Mixes `new` over `old` by the selection's coverage.
+fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Surface {
+ let area = old.content_bounds().union(&new.content_bounds());
+ let fmt = new.format();
+ let old = if old.format() == fmt { old.clone() } else { old.convert(fmt) };
+ let mut out = new.clone();
+ if area.is_empty() {
+ return out;
+ }
+ let n = fmt.channels();
+ let (o, w) = (old.read_region(area), new.read_region(area));
+ let aw = area.width() as usize;
+ let mut r = vec![0.0f32; o.len()];
+ for (i, ((op, np), rp)) in o.chunks_exact(n).zip(w.chunks_exact(n)).zip(r.chunks_exact_mut(n)).enumerate() {
+ let k = sel.sample_channel(area.x0 + (i % aw) as i32, area.y0 + (i / aw) as i32, 0).clamp(0.0, 1.0);
+ if !fmt.alpha {
+ for c in 0..n {
+ rp[c] = op[c] + (np[c] - op[c]) * k;
+ }
+ continue;
+ }
+ let a = n - 1;
+ let oa = op[a] + (np[a] - op[a]) * k;
+ rp[a] = oa;
+ for c in 0..a {
+ let pm = op[c] * op[a] + (np[c] * np[a] - op[c] * op[a]) * k;
+ rp[c] = if oa > 0.0 { pm / oa } else { 0.0 };
+ }
+ }
+ out.write_region(area, &r);
+ out.prune();
+ out
+}
+
+/// Smart-filter hook: re-applies a stored filter of this module (`None` for other ids).
+pub fn apply_to_surface(id: &str, params: &Value, surf: &Surface, canvas: Rect) -> Option<Surface> {
+ match id {
+ LENS => Some(lens::correct(surf, canvas, &lens_params(id, params, canvas, None).ok()?)),
+ WIDE => Some(wideangle::apply(surf, canvas, &wide_params(id, params, None).ok()?, Interp::Bicubic)),
+ RAW => Some(camera_raw_surface(surf, canvas, &raw_params(id, params).ok()?)),
+ _ => None,
+ }
+}
+
+// ---------- commands ----------
+
+fn target(s: &Session, p: &Value) -> Result<LayerId> {
+ match p.get("layer").and_then(Value::as_u64) {
+ Some(v) => Ok(LayerId(v)),
+ None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())),
+ }
+}
+
+fn camera_info(doc: &Document) -> Option<exif::CameraInfo> {
+ doc.metadata.exif.as_ref().map(|e| exif::read(e))
+}
+
+fn filterable(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ match &d.doc.layer(id).ok_or("no active layer")?.content {
+ LayerContent::Raster(_) => Ok(()),
+ LayerContent::Smart(sm) if sm.cache.is_some() => Ok(()),
+ other => Err(format!("filters need a pixel layer (active layer is a {} layer)", other.kind_name())),
+ }
+}
+
+fn raw_enabled(s: &Session) -> std::result::Result<(), String> {
+ filterable(s)?;
+ 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:?})")),
+ }
+}
+
+/// Runs `f` on the target layer (pixel layer edited in place inside the selection; smart object
+/// gets a smart filter with `stored` params).
+fn run_filter(s: &mut Session, cmd: &str, label: &str, stored: Value, float_bg: bool, f: &dyn Fn(&Surface, Rect) -> Surface) -> Result<LayerId> {
+ let id = target(s, &stored)?;
+ let mut stored = stored;
+ if let Value::Object(m) = &mut stored {
+ m.remove("layer");
+ }
+ s.edit(label, |doc: &mut Document, _| {
+ let canvas = doc.bounds();
+ let selection = doc.selection.clone();
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if let LayerContent::Smart(_) = l.content {
+ let sf = SmartFilter { command: cmd.to_string(), params: stored.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true };
+ return crate::smart_cmds::add_smart_filter(doc, id, sf, selection.as_ref());
+ }
+ if l.locks.all || l.locks.pixels {
+ return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));
+ }
+ // A Background layer gains transparency when the edge mode exposes it (as in Photoshop).
+ if float_bg && l.locks.position && l.name == "Background" {
+ l.locks.position = false;
+ l.locks.transparency = false;
+ l.name = "Layer 0".into();
+ }
+ let LayerContent::Raster(surf) = &mut l.content else {
+ return Err(EngineError::Other(format!("{label} needs a pixel layer")));
+ };
+ let out = f(surf, canvas);
+ *surf = match &selection {
+ Some(sel) => mix_by_selection(surf, &out, sel),
+ None => out,
+ };
+ Ok(())
+ })?;
+ Ok(id)
+}
+
+fn lens_correction(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let frame = st.doc.bounds();
+ let info = camera_info(&st.doc);
+ let lc = lens_params(LENS, p, frame, info.as_ref())?;
+ let stored = resolved_lens_params(p, &lc);
+ let t0 = std::time::Instant::now();
+ let id = run_filter(s, LENS, "Lens Correction", stored.clone(), matches!(lc.edge, EdgeMode::Transparency), &|surf, canvas| lens::correct(surf, canvas, &lc))?;
+ Ok(json!({"layer": id.0, "profile": lc.profile.as_ref().map(|p| p.name.clone()), "angle": lc.angle, "scale": lc.scale, "params": stored, "ms": t0.elapsed().as_secs_f64() * 1000.0}))
+}
+
+fn adaptive_wide_angle(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let frame = st.doc.bounds();
+ let info = camera_info(&st.doc);
+ let wa = wide_params(WIDE, p, info.as_ref())?;
+ let t0 = std::time::Instant::now();
+ let mesh = wideangle::solve(&wa, frame);
+ let cam = wideangle::Camera::new(&wa, frame);
+ let mut stored = serde_json::to_value(&wa).unwrap_or(Value::Null);
+ if let Some(l) = p.get("layer") {
+ stored["layer"] = l.clone();
+ }
+ let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));
+ let id = run_filter(s, WIDE, "Adaptive Wide Angle", stored.clone(), true, &|surf, canvas| {
+ let tris = mesh.triangles();
+ if canvas == frame { photocraft_algo::warp::warp_triangles(surf, canvas, &mesh.verts, &tris, interp) } else { wideangle::apply(surf, canvas, &wa, interp) }
+ })?;
+ let model = match cam.model {
+ wideangle::WideModel::Fisheye => "fisheye",
+ wideangle::WideModel::Perspective => "perspective",
+ wideangle::WideModel::FullSpherical => "fullSpherical",
+ wideangle::WideModel::Auto => "auto",
+ };
+ if let Some(m) = stored.as_object_mut() {
+ m.remove("layer");
+ }
+ Ok(json!({
+ "layer": id.0,
+ "model": model,
+ "focalPx": cam.f,
+ "constraints": wa.constraints.len(),
+ "curves": mesh.curves,
+ "residual": mesh.residual,
+ "params": stored,
+ "ms": t0.elapsed().as_secs_f64() * 1000.0,
+ }))
+}
+
+fn camera_raw_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ let cr = raw_params(RAW, p)?;
+ let t0 = std::time::Instant::now();
+ let id = run_filter(s, RAW, "Camera Raw Filter", 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.elapsed().as_secs_f64() * 1000.0}))
+}
+
+fn lens_batch(_s: &mut Session, p: &Value) -> Result<Value> {
+ let inputs = crate::file_cmds::batch_inputs(p, LENS_BATCH)?;
+ let output = crate::file_cmds::str_param(p, "output", LENS_BATCH)?.to_string();
+ let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
+ let mut params = p.clone();
+ if let Value::Object(m) = &mut params {
+ for k in ["input", "files", "output", "format", "quality"] {
+ m.remove(k);
+ }
+ // Batch default: the EXIF-driven profile, as Photoshop's dialog suggests.
+ m.entry("profile").or_insert(json!("auto"));
+ }
+ let r = crate::file_cmds::process_files(&inputs, &output, &format, crate::file_cmds::f64_param(p, "quality"), "", &|scratch| {
+ if scratch.active().is_some_and(|d| d.doc.layers.len() > 1) {
+ scratch.execute("layer.flattenImage", json!({}))?;
+ }
+ scratch.execute(LENS, params.clone())?;
+ Ok(())
+ });
+ Ok(r)
+}
+
+const LENS_DOC: &str = r##"{"profile":"none|auto|generic","focalLength":mm=0,"correctDistortion":bool=true,"correctVignette":bool=true,"correctCA":bool=true,"autoScale":bool=false,"distortion":-100..100=0,"redCyan":-100..100=0,"blueYellow":-100..100=0,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vertical":-100..100=0,"horizontal":-100..100=0,"angle":-180..180=0,"scale":50..150=100,"edge":"transparency|edgeExtension|black|white","straighten":[[x,y],[x,y]]?}"##;
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: LENS, label: "Lens Correction…", menu: &["Filter"], shortcut: Some("Cmd+Shift+R"), params: LENS_DOC, enabled: filterable, run: lens_correction, journal: true },
+ CommandSpec {
+ id: WIDE,
+ label: "Adaptive Wide Angle…",
+ menu: &["Filter"],
+ shortcut: Some("Cmd+Alt+Shift+A"),
+ params: r##"{"model":"auto|fisheye|perspective|fullSpherical","focalLength":0..200=0,"cropFactor":0.1..10=1,"scale":50..150=100,"constraints":[{"a":[x,y],"b":[x,y],"orientation":"free|horizontal|vertical"}]}"##,
+ enabled: filterable,
+ run: adaptive_wide_angle,
+ journal: true,
+ },
+ CommandSpec {
+ id: RAW,
+ label: "Camera Raw Filter…",
+ menu: &["Filter"],
+ shortcut: None,
+ 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,"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}"##,
+ enabled: raw_enabled,
+ run: camera_raw_cmd,
+ journal: true,
+ },
+ CommandSpec {
+ id: LENS_BATCH,
+ label: "Lens Correction…",
+ menu: &["File", "Automate"],
+ shortcut: None,
+ params: r##"{"input":folder|[files],"output":folder,"format":"same|jpg|png|tif|psd","quality":0..12?, …Filter › Lens Correction params ("profile" defaults to "auto")}"##,
+ enabled: crate::file_cmds::native,
+ run: lens_batch,
+ journal: true,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 120, "height": 80, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "grid"})).unwrap();
+ s.edit("grid", |doc, active| {
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ let fmt = surf.format();
+ for y in 0..80 {
+ for x in 0..120 {
+ let v = if x % 12 < 2 || y % 12 < 2 { 0.9 } else { 0.35 };
+ surf.write_pixel(x, y, &photocraft_raster::from_rgba(&fmt, [v, v * 0.9, v * 0.7, 1.0]));
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+ }
+
+ fn active_px(s: &Session, x: i32, y: i32) -> [f32; 4] {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
+ }
+
+ #[test]
+ fn lens_correction_runs_undoes_and_resolves_profiles() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ assert!(s.is_enabled(LENS));
+ let before = active_px(&s, 1, 1);
+ let r = s.execute(LENS, json!({"distortion": -40, "vignetteAmount": -50})).unwrap();
+ assert!(r["ms"].as_f64().is_some());
+ let after = active_px(&s, 1, 1);
+ assert!(after[3] < 0.5, "depth {depth}: corner cleared by transparency edge: {after:?}");
+ s.undo();
+ assert_eq!(active_px(&s, 1, 1), before);
+ }
+ // EXIF-driven auto profile.
+ let mut s = session(8);
+ s.edit("exif", |doc, _| {
+ doc.metadata.exif = Some(std::sync::Arc::new(exif::build(&exif::CameraInfo { focal_length: Some(16.0), focal_length_35mm: Some(24.0), ..Default::default() })));
+ Ok(())
+ })
+ .unwrap();
+ let r = s.execute(LENS, json!({"profile": "auto", "autoScale": true, "edge": "edgeExtension"})).unwrap();
+ assert_eq!(r["params"]["profile"], "generic");
+ assert_eq!(r["params"]["focalLength"], 24.0);
+ assert!(r["scale"].as_f64().unwrap() >= 100.0);
+ let r = s.execute(LENS, json!({"straighten": [[0, 0], [100, 5]]})).unwrap();
+ assert!((r["angle"].as_f64().unwrap() + 2.862).abs() < 0.01, "{r}");
+ assert!(s.execute(LENS, json!({"edge": "rainbow"})).is_err());
+ assert!(s.execute(LENS, json!({"profile": "zeiss"})).is_err());
+ }
+
+ #[test]
+ fn lens_correction_as_smart_filter() {
+ let mut s = session(8);
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ let r = s.execute(LENS, json!({"vignetteAmount": 80, "edge": "edgeExtension"})).unwrap();
+ let d = s.active().unwrap();
+ let l = d.doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap();
+ let LayerContent::Smart(sm) = &l.content else { panic!("smart") };
+ assert_eq!(sm.smart_filters.len(), 1);
+ assert_eq!(sm.smart_filters[0].command, LENS);
+ let corner = active_px(&s, 3, 3);
+ assert!(corner[0] > 0.4, "{corner:?}");
+ }
+
+ #[test]
+ fn adaptive_wide_angle_straightens() {
+ let mut s = session(8);
+ let r = s.execute(WIDE, json!({"model": "fisheye", "focalLength": 10, "constraints": [{"a": [10, 15], "b": [110, 15], "orientation": "horizontal"}]})).unwrap();
+ assert_eq!(r["model"], "fisheye");
+ assert!(r["residual"].as_f64().unwrap() < 2.0, "{r}");
+ assert!(s.execute(WIDE, json!({"constraints": [{"a": [0, 0]}]})).is_err());
+ // Smart filter re-render.
+ let mut s = session(16);
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ s.execute(WIDE, json!({"model": "perspective", "scale": 90})).unwrap();
+ assert!(active_px(&s, 1, 1)[3] < 0.5);
+ }
+
+ #[test]
+ fn camera_raw_filter_on_layers_selection_and_smart_objects() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ assert!(s.is_enabled(RAW));
+ let before = active_px(&s, 60, 40);
+ s.execute(RAW, json!({"exposure": 1.0, "vibrance": 30, "clarity": 20})).unwrap();
+ let after = active_px(&s, 60, 40);
+ assert!(after[1] > before[1] + 0.05, "depth {depth}: {before:?} → {after:?}");
+ s.undo();
+ }
+ // Selection limits it.
+ let mut s = session(8);
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 60, "height": 80})).unwrap();
+ let inside_before = active_px(&s, 10, 40);
+ let outside_before = active_px(&s, 100, 40);
+ s.execute(RAW, json!({"exposure": -1.0})).unwrap();
+ assert!(active_px(&s, 10, 40)[1] < inside_before[1]);
+ assert_eq!(active_px(&s, 100, 40), outside_before);
+ assert!(s.execute(RAW, json!({"exposure": "bright"})).is_err());
+ // Smart filter.
+ let mut s = session(8);
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ s.execute(RAW, json!({"saturation": -100})).unwrap();
+ let p = active_px(&s, 60, 40);
+ assert!((p[0] - p[2]).abs() < 0.01, "{p:?}");
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn lens_correction_batch_over_files() {
+ let dir = std::env::temp_dir().join(format!("pc-lens-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("in")).unwrap();
+ let mut s = session(8);
+ s.execute("layer.flattenImage", json!({})).unwrap();
+ for k in 0..2 {
+ let path = dir.join("in").join(format!("shot{k}.png"));
+ crate::file_cmds::save_doc(&s.active().unwrap().doc, path.to_str().unwrap(), None).unwrap();
+ }
+ let r = s.execute(LENS_BATCH, json!({"input": dir.join("in").to_str().unwrap(), "output": dir.join("out").to_str().unwrap(), "vignetteAmount": 60, "edge": "edgeExtension"})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), 2, "{r}");
+ assert!(r["errors"].as_array().unwrap().is_empty());
+ assert!(dir.join("out").join("shot0.png").is_file());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f0073473d..5c688233c 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -7,15 +7,20 @@
#![forbid(unsafe_code)]
pub mod adjust_cmds;
+pub mod analysis_cmds;
+pub mod notes_cmds;
+pub mod proof_sim;
pub mod build_info;
pub mod layer_menu_cmds;
pub mod mode_cmds;
+pub mod multichannel_cmds;
pub mod channel_cmds;
pub mod commands;
pub mod inspect;
pub mod layer_style;
pub mod filters;
pub mod filters_ext;
+pub mod gallery_cmds;
pub mod type_cmds;
pub mod transform_cmds;
pub mod vector_cmds;
@@ -27,7 +32,9 @@ pub mod paint_cmds;
pub mod pattern_cmds;
pub mod warp_cmds;
pub mod distort_cmds;
+pub mod render_cmds;
pub mod selection_cmds;
+pub mod select_extra_cmds;
pub mod brush_cmds;
pub mod extra_cmds;
pub mod color_cmds;
@@ -35,13 +42,24 @@ pub mod layer_multi_cmds;
pub mod smart_cmds;
pub mod file_cmds;
pub mod type_extra_cmds;
+pub mod type_spell_cmds;
+pub mod type_styles_cmds;
mod pixels;
pub mod prefs;
pub mod snap;
pub mod edit_menu_cmds;
pub mod align_cmds;
+pub mod photo_cmds;
+pub mod lens_cmds;
+pub mod vp_cmds;
pub mod artboard_cmds;
pub mod comps_cmds;
+pub mod automate_cmds;
+pub mod pick_cmds;
+pub mod print_cmds;
+pub mod slice_cmds;
+pub mod web_cmds;
+pub mod presets;
use std::sync::Arc;
@@ -95,6 +113,8 @@ pub struct DocState {
pub coalesce: Option<String>,
/// Channels panel: targeted channel and eye toggles (view state, not history).
pub channel_view: channel_cmds::ChannelView,
+ /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state).
+ pub isolated_layers: Vec<LayerId>,
}
impl DocState {
@@ -112,6 +132,7 @@ impl DocState {
last_damage: None,
coalesce: None,
channel_view: Default::default(),
+ isolated_layers: Vec::new(),
}
}
/// The selected layers in bottom-to-top document order, always including the active layer.
@@ -183,6 +204,13 @@ pub struct Session {
pub edit_state: edit_menu_cmds::EditState,
/// The pattern library (Window › Patterns; see `pattern.*`).
pub patterns: pattern_cmds::PatternLibrary,
+ /// Image › Analysis: Measurement Log and Select Data Points (see `analysis_cmds`).
+ pub analysis: analysis_cmds::AnalysisState,
+ /// Window › Gradients, Patterns (groups), Styles, Shapes, Tool Presets and Clone Source.
+ pub presets: presets::PresetState,
+ /// File menu state: Lock Slices, Image Assets, last Print / Save for Web settings, script
+ /// event log (see `automate_cmds`).
+ pub file_menu: automate_cmds::FileMenuState,
}
impl Session {
@@ -250,6 +278,7 @@ impl Session {
self.color_restrict = None;
let r = r?;
edit_menu_cmds::after_command(self, id);
+ automate_cmds::after_command(self, id);
if spec.journal {
self.journal.push((id.to_string(), params));
}
diff --git a/crates/engine/src/multichannel_cmds.rs b/crates/engine/src/multichannel_cmds.rs
new file mode 100644
index 000000000..c8e191108
--- /dev/null
+++ b/crates/engine/src/multichannel_cmds.rs
@@ -0,0 +1,205 @@
+//! Image › Mode › Multichannel, and conversions out of it.
+//!
+//! A Multichannel document has no layers: its image is a set of ink channels, kept as spot
+//! channels in [`Document::channels`] (value = ink density, 1 = solid; the compositor prints them
+//! over white, see `photocraft_compose::multichannel`). Like Photoshop the conversion flattens and
+//! turns each colour channel into an ink:
+//!
+//! * RGB → Cyan, Magenta, Yellow (the red, green and blue data read as ink: density = 1 − value);
+//! * CMYK → Cyan, Magenta, Yellow, Black (the plates as they are);
+//! * Lab → Alpha 1, Alpha 2, Alpha 3 (lightness, a, b data, printed in black);
+//! * Grayscale → Black; Duotone → one channel per ink (its curve applied).
+//!
+//! Existing alpha channels stay alpha channels. Converting back reinterprets the channel data when
+//! the count matches the target (3 → RGB / Lab, 4 → CMYK, 1 → Grayscale), the inverse of the
+//! above; otherwise the printed look is converted.
+
+use photocraft_color::{Color, ColorMode, PixelFormat};
+use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent};
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// Display colours of the process inks (sRGB).
+const CYAN: Color = Color::rgb(0.0, 0.682, 0.937);
+const MAGENTA: Color = Color::rgb(0.925, 0.0, 0.549);
+const YELLOW: Color = Color::rgb(1.0, 0.949, 0.0);
+const BLACK: Color = Color::rgb(0.137, 0.122, 0.125);
+
+/// Modes Photoshop converts to Multichannel.
+const SOURCES: [ColorMode; 5] = [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale, ColorMode::Duotone];
+
+fn enabled(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if SOURCES.contains(&d.doc.mode) { Ok(()) } else { Err(format!("Multichannel needs an RGB, CMYK, Lab, Grayscale or Duotone image (the document is {:?})", d.doc.mode)) }
+}
+
+/// Native colour planes of the flattened image (opaque over white): one `Vec` per colour
+/// channel of the document's pixel format. A lone plain layer is read exactly; anything else
+/// goes through the compositor.
+fn flattened_planes(doc: &Document) -> Vec<Vec<f32>> {
+ let fmt = doc.pixel_format();
+ let cc = fmt.mode.color_channels();
+ let canvas = doc.bounds();
+ let n = canvas.width() as usize * canvas.height() as usize;
+ let white = photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0]);
+ let mut planes = vec![Vec::with_capacity(n); cc];
+ let plain = match doc.layers.as_slice() {
+ [l] if l.visible
+ && l.opacity >= 1.0
+ && l.fill_opacity >= 1.0
+ && l.mask.is_none()
+ && l.vector_mask.is_none()
+ && !photocraft_compose::effects::has_effects(l) =>
+ {
+ match &l.content {
+ LayerContent::Raster(s) if s.format().mode == fmt.mode => Some(s),
+ _ => None,
+ }
+ }
+ _ => None,
+ };
+ if let Some(s) = plain {
+ let ch = s.channels();
+ let alpha = s.format().alpha;
+ for px in s.read_region(canvas).chunks_exact(ch) {
+ let a = if alpha { px[ch - 1] } else { 1.0 };
+ for (c, plane) in planes.iter_mut().enumerate() {
+ plane.push(px[c] * a + white[c] * (1.0 - a));
+ }
+ }
+ } else {
+ let buf = photocraft_compose::flatten(doc).over_background([1.0, 1.0, 1.0]);
+ for p in &buf.px {
+ let v = photocraft_raster::from_rgba(&fmt, *p);
+ for (c, plane) in planes.iter_mut().enumerate() {
+ plane.push(v[c]);
+ }
+ }
+ }
+ planes
+}
+
+fn channel_surface(doc: &Document, vals: &[f32]) -> Surface {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, doc.depth, false));
+ let clamped: Vec<f32> = vals.iter().map(|v| v.clamp(0.0, 1.0)).collect();
+ s.write_region(doc.bounds(), &clamped);
+ s.prune();
+ s
+}
+
+/// The ink channels (name, display colour, densities) of the flattened document.
+fn inks_of(doc: &Document) -> Vec<(String, Color, Vec<f32>)> {
+ let planes = flattened_planes(doc);
+ let inv = |p: &Vec<f32>| p.iter().map(|v| 1.0 - v).collect::<Vec<f32>>();
+ match doc.mode {
+ ColorMode::Rgb => [("Cyan", CYAN), ("Magenta", MAGENTA), ("Yellow", YELLOW)].into_iter().zip(&planes).map(|((n, c), p)| (n.to_string(), c, inv(p))).collect(),
+ ColorMode::Cmyk => [("Cyan", CYAN), ("Magenta", MAGENTA), ("Yellow", YELLOW), ("Black", BLACK)].into_iter().zip(planes).map(|((n, c), p)| (n.to_string(), c, p)).collect(),
+ ColorMode::Lab => planes.iter().enumerate().map(|(k, p)| (format!("Alpha {}", k + 1), Color::BLACK, inv(p))).collect(),
+ ColorMode::Duotone if doc.duotone.as_ref().is_some_and(|d| !d.inks.is_empty()) => {
+ let d = doc.duotone.as_ref().expect("checked");
+ d.inks.iter().map(|ink| (ink.name.clone(), Color::rgb(ink.color[0], ink.color[1], ink.color[2]), planes[0].iter().map(|g| ink.density(1.0 - g)).collect())).collect()
+ }
+ _ => vec![("Black".to_string(), Color::BLACK, inv(&planes[0]))],
+ }
+}
+
+fn to_multichannel(s: &mut Session, _p: &Value) -> Result<Value> {
+ let names = s.edit("Multichannel", |doc, active| {
+ let inks = inks_of(doc);
+ let mut channels: Vec<AlphaChannel> = inks.iter().map(|(name, ink, vals)| AlphaChannel { spot: Some((*ink, 0.0)), ..AlphaChannel::new(name.clone(), channel_surface(doc, vals)) }).collect();
+ // Existing alpha / spot channels follow the inks, converted to the document depth.
+ let fmt = PixelFormat::new(ColorMode::Grayscale, doc.depth, false);
+ for mut ch in std::mem::take(&mut doc.channels) {
+ if ch.surface.format() != fmt {
+ ch.surface = ch.surface.convert(fmt);
+ }
+ channels.push(ch);
+ }
+ doc.channels = channels;
+ doc.layers.clear();
+ *active = None;
+ doc.mode = ColorMode::Multichannel;
+ doc.quick_mask = None;
+ doc.color_table = None;
+ doc.duotone = None;
+ doc.icc_profile = None;
+ Ok(inks.into_iter().map(|(n, _, _)| n).collect::<Vec<_>>())
+ })?;
+ Ok(json!({ "mode": "multichannel", "channels": names }))
+}
+
+/// Image › Mode › RGB / CMYK / Lab / Grayscale from a Multichannel document (called by
+/// `color_cmds::convert_mode`). Profiles are not involved: Multichannel has none.
+pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Result<Value> {
+ if !matches!(mode, ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab | ColorMode::Grayscale) {
+ return Err(EngineError::Other(format!("a Multichannel document can't be converted to {mode:?}")));
+ }
+ let how = s.edit("Mode Change", |doc, active| {
+ let (inks, others): (Vec<AlphaChannel>, Vec<AlphaChannel>) = std::mem::take(&mut doc.channels).into_iter().partition(|c| c.spot.is_some());
+ let canvas = doc.bounds();
+ let n = canvas.width() as usize * canvas.height() as usize;
+ let reinterpret = matches!((mode, inks.len()), (ColorMode::Rgb | ColorMode::Lab, 3) | (ColorMode::Cmyk, 4) | (ColorMode::Grayscale, 1));
+ // The printed look, rendered before the inks leave the document.
+ let shown = (!reinterpret).then(|| {
+ let mut d = doc.clone();
+ d.channels = inks.clone();
+ photocraft_compose::flatten(&d)
+ });
+ doc.mode = mode;
+ let fmt = doc.pixel_format();
+ let cc = fmt.mode.color_channels();
+ let mut data = vec![0.0f32; n * (cc + 1)];
+ if let Some(buf) = &shown {
+ for (px, p) in data.chunks_exact_mut(cc + 1).zip(&buf.px) {
+ px.copy_from_slice(&photocraft_raster::from_rgba(&fmt, [p[0], p[1], p[2], 1.0])[..cc + 1]);
+ }
+ } else {
+ for (k, ch) in inks.iter().enumerate() {
+ let vals = ch.surface.read_region(canvas);
+ let step = ch.surface.channels();
+ for (i, v) in vals.chunks_exact(step).enumerate() {
+ // CMYK plates are ink amounts already; other modes store light.
+ data[i * (cc + 1) + k] = if mode == ColorMode::Cmyk { v[0] } else { 1.0 - v[0] };
+ }
+ }
+ for i in 0..n {
+ data[i * (cc + 1) + cc] = 1.0;
+ }
+ }
+ let mut surf = Surface::new(fmt);
+ surf.write_region(canvas, &data);
+ surf.prune();
+ let mut bg = Layer::new("Background", LayerContent::Raster(surf));
+ bg.locks.transparency = true;
+ bg.locks.position = true;
+ *active = Some(bg.id);
+ doc.layers = vec![bg];
+ doc.channels = others;
+ Ok(if reinterpret { "channels" } else { "appearance" })
+ })?;
+ Ok(json!({ "mode": format!("{mode:?}").to_lowercase(), "from": "multichannel", "converted": how }))
+}
+
+/// Names of the ink (spot) channels that make up a Multichannel image.
+pub fn ink_names(doc: &Document) -> Vec<String> {
+ doc.channels.iter().filter(|c| c.spot.is_some()).map(|c| c.name.clone()).collect()
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: "image.mode.multichannel",
+ label: "Multichannel",
+ menu: &["Image", "Mode"],
+ shortcut: None,
+ params: r##"{} (flattens; RGB → Cyan/Magenta/Yellow, CMYK → Cyan/Magenta/Yellow/Black, Lab → Alpha 1–3, Grayscale → Black, Duotone → its inks)"##,
+ enabled,
+ run: to_multichannel,
+ journal: true,
+ }]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/multichannel_cmds/tests.rs b/crates/engine/src/multichannel_cmds/tests.rs
new file mode 100644
index 000000000..e8df57498
--- /dev/null
+++ b/crates/engine/src/multichannel_cmds/tests.rs
@@ -0,0 +1,209 @@
+use super::*;
+use photocraft_color::SampleType;
+
+fn session(mode: &str, depth: u64) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 12, "height": 8, "depth": depth, "mode": mode})).unwrap();
+ s.edit("setup", |doc, active| {
+ let b = doc.bounds();
+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ let ch = surf.channels();
+ let mut data = Vec::new();
+ for y in b.y0..b.y1 {
+ for x in b.x0..b.x1 {
+ for c in 0..ch - 1 {
+ data.push(((x * 3 + y * 5 + c as i32 * 7) % 16) as f32 / 15.0);
+ }
+ data.push(1.0);
+ }
+ }
+ surf.write_region(b, &data);
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn pixels(s: &Session) -> Vec<f32> {
+ let d = doc(s);
+ d.layers[0].surface().unwrap().read_region(d.bounds())
+}
+
+fn tol(depth: u64) -> f32 {
+ if depth == 8 { 0.5 / 255.0 + 1e-6 } else { 1e-4 }
+}
+
+#[test]
+fn rgb_becomes_cmy_inks_and_back_exactly() {
+ for depth in [8, 16, 32] {
+ let mut s = session("rgb", depth);
+ let before = pixels(&s);
+ assert!(s.is_enabled("image.mode.multichannel"));
+ let r = s.execute("image.mode.multichannel", json!({})).unwrap();
+ assert_eq!(r["channels"], json!(["Cyan", "Magenta", "Yellow"]));
+ let d = doc(&s);
+ assert_eq!(d.mode, ColorMode::Multichannel);
+ assert!(d.layers.is_empty());
+ assert_eq!(ink_names(d), ["Cyan", "Magenta", "Yellow"]);
+ // Cyan ink = the red data read as ink.
+ let cyan = d.channels[0].surface.pixel(4, 3)[0];
+ let red = before[(3 * 12 + 4) * 4];
+ assert!((cyan - (1.0 - red)).abs() <= tol(depth), "{depth}: {cyan} vs {red}");
+ assert!(!s.is_enabled("image.mode.multichannel"), "already multichannel");
+ // The display prints the inks: a white RGB pixel shows paper.
+ let shown = photocraft_compose::flatten(doc(&s));
+ assert!(shown.px.iter().all(|p| p[3] == 1.0));
+ let r = s.execute("image.mode.rgb", json!({})).unwrap();
+ assert_eq!(r["converted"], "channels");
+ assert_eq!(doc(&s).mode, ColorMode::Rgb);
+ assert!(doc(&s).channels.is_empty());
+ let after = pixels(&s);
+ assert_eq!(after.len(), before.len());
+ for (a, b) in after.iter().zip(&before) {
+ assert!((a - b).abs() <= 2.0 * tol(depth), "{depth}: {a} vs {b}");
+ }
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(doc(&s).mode, ColorMode::Multichannel);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(doc(&s).mode, ColorMode::Rgb);
+ assert_eq!(pixels(&s), before);
+ }
+}
+
+#[test]
+fn cmyk_lab_and_gray_channel_sets() {
+ for (mode, back, names) in [
+ ("cmyk", "image.mode.cmyk", vec!["Cyan", "Magenta", "Yellow", "Black"]),
+ ("lab", "image.mode.lab", vec!["Alpha 1", "Alpha 2", "Alpha 3"]),
+ ("grayscale", "image.mode.grayscale", vec!["Black"]),
+ ] {
+ for depth in [8, 16] {
+ let mut s = session(mode, depth);
+ let before = pixels(&s);
+ let r = s.execute("image.mode.multichannel", json!({})).unwrap();
+ assert_eq!(r["channels"], json!(names), "{mode}");
+ assert_eq!(doc(&s).depth, if depth == 8 { SampleType::U8 } else { SampleType::U16 });
+ s.execute(back, json!({})).unwrap();
+ for (a, b) in pixels(&s).iter().zip(&before) {
+ assert!((a - b).abs() <= 2.0 * tol(depth), "{mode}/{depth}: {a} vs {b}");
+ }
+ }
+ }
+}
+
+#[test]
+fn flattens_layers_and_keeps_alpha_channels() {
+ let mut s = session("rgb", 8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("select.saveSelection", json!({})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let alpha = doc(&s).channels.len();
+ assert_eq!(alpha, 1);
+ s.execute("image.mode.multichannel", json!({})).unwrap();
+ let d = doc(&s);
+ assert_eq!(d.channels.len(), 4);
+ assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel");
+ // The black fill on the upper layer is solid ink in all three plates.
+ for k in 0..3 {
+ assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99);
+ }
+ // Back to RGB: the alpha channel survives, the inks become colour channels.
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ assert_eq!(doc(&s).channels.len(), 1);
+ assert!(doc(&s).layers[0].surface().unwrap().pixel(1, 1)[0] < 0.01);
+}
+
+#[test]
+fn mismatched_channel_count_converts_the_printed_look() {
+ let mut s = session("rgb", 8);
+ s.execute("image.mode.multichannel", json!({})).unwrap();
+ // Drop the Yellow plate: two inks can't be RGB channels.
+ s.edit("drop", |doc, _| {
+ doc.channels.truncate(2);
+ Ok(())
+ })
+ .unwrap();
+ let shown = photocraft_compose::flatten(doc(&s));
+ let r = s.execute("image.mode.rgb", json!({})).unwrap();
+ assert_eq!(r["converted"], "appearance");
+ let px = doc(&s).layers[0].surface().unwrap().pixel(5, 2);
+ let want = shown.get(5, 2);
+ for c in 0..3 {
+ assert!((px[c] - want[c]).abs() < 1.0 / 255.0 + 1e-4);
+ }
+}
+
+#[test]
+fn duotone_inks_become_channels() {
+ let mut s = session("grayscale", 8);
+ s.execute("image.mode.duotone", json!({"type": "duotone"})).unwrap();
+ let inks = doc(&s).duotone.as_ref().unwrap().inks.len();
+ let r = s.execute("image.mode.multichannel", json!({})).unwrap();
+ assert_eq!(r["channels"].as_array().unwrap().len(), inks);
+}
+
+#[test]
+fn psd_round_trip_keeps_names_inks_and_values() {
+ for depth in [8, 16] {
+ let mut s = session("cmyk", depth);
+ s.execute("image.mode.multichannel", json!({})).unwrap();
+ let d = doc(&s).clone();
+ let out = photocraft_io::export(&d, "x.psd", &photocraft_io::ExportOptions::default()).unwrap();
+ let file = photocraft_io::document_to_psd(&d);
+ assert_eq!(file.header.color_mode.as_u16(), 7);
+ assert_eq!(file.header.channels, 4);
+ // Photoshop stores ink as dark: a solid-ink sample is 0.
+ let back = photocraft_io::import("x.psd", &out.bytes).unwrap().document;
+ assert_eq!(back.mode, ColorMode::Multichannel);
+ assert_eq!(back.depth, d.depth);
+ assert!(back.layers.is_empty());
+ assert_eq!(ink_names(&back), ink_names(&d));
+ for (a, b) in back.channels.iter().zip(&d.channels) {
+ assert_eq!(a.spot.map(|(c, _)| c.to_rgba8()), b.spot.map(|(c, _)| c.to_rgba8()));
+ let (va, vb) = (a.surface.read_region(d.bounds()), b.surface.read_region(d.bounds()));
+ for (x, y) in va.iter().zip(&vb) {
+ assert!((x - y).abs() <= tol(depth), "{depth}");
+ }
+ }
+ }
+}
+
+#[test]
+fn psd_stores_ink_as_dark() {
+ let mut s = session("grayscale", 8);
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("image.mode.multichannel", json!({})).unwrap();
+ let file = photocraft_io::document_to_psd(doc(&s));
+ let merged = file.decode_merged().unwrap();
+ assert!(merged.iter().all(|&b| b == 0), "solid black ink is stored as 0");
+}
+
+#[test]
+fn pcraft_round_trip() {
+ let mut s = session("rgb", 16);
+ s.execute("image.mode.multichannel", json!({})).unwrap();
+ let d = doc(&s).clone();
+ let bytes = photocraft_format::save_to_bytes(&d, &Default::default()).unwrap();
+ let back = photocraft_format::load_from_bytes(&bytes).unwrap();
+ assert_eq!(back.mode, ColorMode::Multichannel);
+ assert_eq!(back.channels, d.channels);
+ assert_eq!(photocraft_compose::flatten(&back), photocraft_compose::flatten(&d));
+}
+
+#[test]
+fn flat_export_prints_the_inks() {
+ let mut s = session("grayscale", 8);
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("image.mode.multichannel", json!({})).unwrap();
+ let out = photocraft_io::export(doc(&s), "x.png", &photocraft_io::ExportOptions::default()).unwrap();
+ let back = photocraft_io::import("x.png", &out.bytes).unwrap().document;
+ let px = photocraft_compose::flatten(&back).get(3, 3);
+ // Solid process black ink, not paper.
+ assert!(px[0] < 0.3 && px[3] > 0.99, "{px:?}");
+}
diff --git a/crates/engine/src/notes_cmds.rs b/crates/engine/src/notes_cmds.rs
new file mode 100644
index 000000000..6995341a4
--- /dev/null
+++ b/crates/engine/src/notes_cmds.rs
@@ -0,0 +1,277 @@
+//! Note tool annotations (Window › Notes, File › Import › Notes…). Notes are document data
+//! ([`photocraft_doc::Note`]), saved in `.pcraft` and as the PSD `Anno` block; each change is
+//! one history step.
+
+use photocraft_color::Color;
+use photocraft_doc::{Document, Note};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn has_notes(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if s.active().is_some_and(|d| !d.doc.notes.is_empty()) { Ok(()) } else { Err("the document has no notes".into()) }
+}
+
+/// PDF-style date (`D:YYYYMMDDhhmmssZ`) as Photoshop stores in notes; empty without a clock.
+fn pdf_date() -> String {
+ let iso = crate::analysis_cmds::now_iso();
+ if iso.len() < 19 {
+ return String::new();
+ }
+ let digits: String = iso[..19].chars().filter(char::is_ascii_digit).collect();
+ format!("D:{digits}Z")
+}
+
+pub fn note_json(i: usize, n: &Note) -> Value {
+ json!({"index": i, "author": n.author, "text": n.text, "color": n.color.to_rgb(), "position": n.position, "open": n.open, "modified": n.modified})
+}
+
+fn list_json(d: &Document) -> Value {
+ json!({"notes": d.notes.iter().enumerate().map(|(i, n)| note_json(i, n)).collect::<Vec<_>>()})
+}
+
+fn color_of(p: &Value) -> Option<Color> {
+ p.get("color")?;
+ let c = crate::commands::color_param(p, "color", [1.0, 1.0, 0.51, 1.0]);
+ Some(Color::rgb(c[0], c[1], c[2]))
+}
+
+fn index_of(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
+ let n = s.active().ok_or(EngineError::NoDocument)?.doc.notes.len();
+ let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "pass `index`"))? as usize;
+ if i < n { Ok(i) } else { Err(bad(cmd, format!("no note {i} (the document has {n})"))) }
+}
+
+fn add(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "notes.add";
+ let x = p.get("x").and_then(Value::as_f64).ok_or_else(|| bad(CMD, "pass `x` and `y`"))?;
+ let y = p.get("y").and_then(Value::as_f64).ok_or_else(|| bad(CMD, "pass `x` and `y`"))?;
+ if !x.is_finite() || !y.is_finite() {
+ return Err(bad(CMD, "coordinates must be finite"));
+ }
+ let mut n = Note {
+ author: p.get("author").and_then(Value::as_str).unwrap_or("").to_string(),
+ text: p.get("text").and_then(Value::as_str).unwrap_or("").to_string(),
+ position: [x, y],
+ popup: [x + 20.0, y + 20.0, x + 260.0, y + 160.0],
+ open: p.get("open").and_then(Value::as_bool).unwrap_or(true),
+ modified: pdf_date(),
+ ..Default::default()
+ };
+ if let Some(c) = color_of(p) {
+ n.color = c;
+ }
+ let i = s.edit("New Note", |d, _| {
+ d.notes.push(n);
+ Ok(d.notes.len() - 1)
+ })?;
+ let d = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ Ok(json!({"index": i, "note": note_json(i, &d.notes[i])}))
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "notes.set";
+ let i = index_of(s, p, CMD)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let mut n = d.notes[i].clone();
+ if let Some(t) = p.get("text").and_then(Value::as_str) {
+ n.text = t.to_string();
+ }
+ if let Some(a) = p.get("author").and_then(Value::as_str) {
+ n.author = a.to_string();
+ }
+ if let Some(c) = color_of(p) {
+ n.color = c;
+ }
+ if let Some(o) = p.get("open").and_then(Value::as_bool) {
+ n.open = o;
+ }
+ let (x, y) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64));
+ if x.is_some() || y.is_some() {
+ let (nx, ny) = (x.unwrap_or(n.position[0]), y.unwrap_or(n.position[1]));
+ if !nx.is_finite() || !ny.is_finite() {
+ return Err(bad(CMD, "coordinates must be finite"));
+ }
+ let (dx, dy) = (nx - n.position[0], ny - n.position[1]);
+ n.position = [nx, ny];
+ // The popup travels with its icon.
+ n.popup = [n.popup[0] + dx, n.popup[1] + dy, n.popup[2] + dx, n.popup[3] + dy];
+ }
+ if n == d.notes[i] {
+ return Ok(json!({"index": i, "note": note_json(i, &n), "changed": false}));
+ }
+ // Content edits update the modification date (opening/closing the popup doesn't).
+ if n.text != d.notes[i].text || n.author != d.notes[i].author {
+ n.modified = pdf_date();
+ }
+ let label = if n.position != d.notes[i].position { "Move Note" } else { "Edit Note" };
+ let out = note_json(i, &n);
+ s.edit(label, |d, _| {
+ d.notes[i] = n;
+ Ok(())
+ })?;
+ Ok(json!({"index": i, "note": out, "changed": true}))
+}
+
+fn delete(s: &mut Session, p: &Value) -> Result<Value> {
+ if p.get("all").and_then(Value::as_bool) == Some(true) {
+ let n = s.active().map_or(0, |d| d.doc.notes.len());
+ s.edit("Delete All Notes", |d, _| {
+ d.notes.clear();
+ Ok(())
+ })?;
+ return Ok(json!({"deleted": n, "remaining": 0}));
+ }
+ let i = index_of(s, p, "notes.delete")?;
+ s.edit("Delete Note", |d, _| {
+ d.notes.remove(i);
+ Ok(())
+ })?;
+ Ok(json!({"deleted": 1, "remaining": s.active().map_or(0, |d| d.doc.notes.len())}))
+}
+
+fn list(s: &mut Session, _p: &Value) -> Result<Value> {
+ Ok(list_json(&s.active().ok_or(EngineError::NoDocument)?.doc))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn read(path: &str) -> Result<Vec<u8>> {
+ std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
+}
+#[cfg(target_arch = "wasm32")]
+fn read(path: &str) -> Result<Vec<u8>> {
+ Err(EngineError::Other(format!("cannot read {path}: no file system on the web")))
+}
+
+/// File › Import › Notes…: append the notes of another PSD or `.pcraft` file. Notes outside the
+/// canvas are pulled inside, as Photoshop does when sizes differ.
+fn import(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "file.import.notes";
+ let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad(CMD, "pass `path` (.psd, .psb or .pcraft)"))?;
+ let bytes = read(path)?;
+ let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
+ import_notes_from(s, &name, &bytes)
+}
+
+/// File › Import › Notes… from file bytes (what a file picker returns).
+pub fn import_notes_from(s: &mut Session, name: &str, bytes: &[u8]) -> Result<Value> {
+ let src = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?.document;
+ if src.notes.is_empty() {
+ return Err(EngineError::Other(format!("{name} has no notes")));
+ }
+ let d = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let (w, h) = (f64::from(d.size.width), f64::from(d.size.height));
+ let mut notes = src.notes;
+ for n in &mut notes {
+ let (nx, ny) = (n.position[0].clamp(0.0, (w - 16.0).max(0.0)), n.position[1].clamp(0.0, (h - 20.0).max(0.0)));
+ let (dx, dy) = (nx - n.position[0], ny - n.position[1]);
+ n.position = [nx, ny];
+ n.popup = [n.popup[0] + dx, n.popup[1] + dy, n.popup[2] + dx, n.popup[3] + dy];
+ }
+ let count = notes.len();
+ s.edit("Import Notes", |d, _| {
+ d.notes.extend(notes);
+ Ok(())
+ })?;
+ let mut r = list_json(&s.active().ok_or(EngineError::NoDocument)?.doc);
+ r["imported"] = json!(count);
+ Ok(r)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: "notes.add", label: "New Note", menu: &[], shortcut: None, params: r##"{"x":px,"y":px,"text":str="","author":str="","color":"#rrggbb"|[r,g,b]=pale yellow,"open":bool=true}"##, enabled: has_doc, run: add, journal: true },
+ CommandSpec { id: "notes.set", label: "Edit Note", menu: &[], shortcut: None, params: r##"{"index":n,"text":str?,"author":str?,"color":"#rrggbb"|[r,g,b]?,"x":px?,"y":px?,"open":bool?}"##, enabled: has_notes, run: set, journal: true },
+ CommandSpec { id: "notes.delete", label: "Delete Note", menu: &[], shortcut: None, params: r##"{"index":n}|{"all":true}"##, enabled: has_notes, run: delete, journal: true },
+ CommandSpec { id: "notes.list", label: "Notes", menu: &[], shortcut: None, params: r##"{} → notes (index, author, text, colour, position, open, modified)"##, enabled: has_doc, run: list, journal: false },
+ CommandSpec { id: "file.import.notes", label: "Notes…", menu: &["File", "Import"], shortcut: None, params: r##"{"path":".psd|.psb|.pcraft with notes"}"##, enabled: has_doc, run: import, journal: true },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 80})).unwrap();
+ s
+ }
+
+ #[test]
+ fn add_edit_move_delete_with_undo() {
+ let mut s = session();
+ assert!(!s.is_enabled("notes.delete"));
+ let r = s.execute("notes.add", json!({"x": 10, "y": 12, "text": "fix this", "author": "QA", "color": "#ff0000"})).unwrap();
+ assert_eq!(r["index"], 0);
+ assert_eq!(r["note"]["color"], json!([1.0, 0.0, 0.0]));
+ s.execute("notes.add", json!({"x": 50, "y": 40})).unwrap();
+ s.execute("notes.set", json!({"index": 0, "text": "fixed", "x": 20})).unwrap();
+ let d = s.active().unwrap().doc.clone();
+ assert_eq!(d.notes[0].text, "fixed");
+ assert_eq!(d.notes[0].position, [20.0, 12.0]);
+ assert_eq!(d.notes[0].popup[0], 40.0);
+ // Unchanged edits don't add history.
+ let before = s.active().unwrap().history.past_len();
+ assert_eq!(s.execute("notes.set", json!({"index": 0, "text": "fixed"})).unwrap()["changed"], false);
+ assert_eq!(s.active().unwrap().history.past_len(), before);
+ s.execute("notes.delete", json!({"index": 1})).unwrap();
+ assert_eq!(s.execute("notes.list", json!({})).unwrap()["notes"].as_array().unwrap().len(), 1);
+ assert!(s.undo());
+ assert_eq!(s.active().unwrap().doc.notes.len(), 2);
+ s.execute("notes.delete", json!({"all": true})).unwrap();
+ assert!(s.active().unwrap().doc.notes.is_empty());
+ assert!(s.execute("notes.set", json!({"index": 0})).is_err());
+ }
+
+ #[test]
+ fn bad_params() {
+ let mut s = session();
+ assert!(s.execute("notes.add", json!({"x": 1})).is_err());
+ s.execute("notes.add", json!({"x": 1, "y": 1})).unwrap();
+ assert!(s.execute("notes.set", json!({"index": 5, "text": "x"})).is_err());
+ assert!(s.execute("notes.set", json!({})).is_err());
+ assert!(s.execute("file.import.notes", json!({})).is_err());
+ assert!(s.execute("file.import.notes", json!({"path": "/nonexistent/x.psd"})).is_err());
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn import_notes_from_pcraft_and_psd() {
+ let dir = std::env::temp_dir().join(format!("pc-notes-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut src = Document::new("src", photocraft_doc::Size::new(400, 400), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
+ src.notes.push(Note { text: "from pcraft".into(), position: [300.0, 300.0], ..Default::default() });
+ let pc = dir.join("a.pcraft");
+ std::fs::write(&pc, photocraft_format::save_to_bytes(&src, &Default::default()).unwrap()).unwrap();
+ let mut s = session();
+ let r = s.execute("file.import.notes", json!({"path": pc.to_str().unwrap()})).unwrap();
+ assert_eq!(r["imported"], 1);
+ // Pulled inside the 100×80 canvas.
+ let n = &s.active().unwrap().doc.notes[0];
+ assert_eq!(n.text, "from pcraft");
+ assert!(n.position[0] <= 84.0 && n.position[1] <= 60.0);
+ // A PSD with notes (corpus sample) appends two more.
+ let psd = concat!(env!("CARGO_MANIFEST_DIR"), "/../../corpus/psd/ag-psd/read-write/annotations/src.psd");
+ if std::path::Path::new(psd).exists() {
+ s.execute("file.import.notes", json!({"path": psd})).unwrap();
+ assert_eq!(s.active().unwrap().doc.notes.len(), 3);
+ }
+ // A file without notes is an error.
+ let empty = dir.join("b.pcraft");
+ src.notes.clear();
+ std::fs::write(&empty, photocraft_format::save_to_bytes(&src, &Default::default()).unwrap()).unwrap();
+ assert!(s.execute("file.import.notes", json!({"path": empty.to_str().unwrap()})).is_err());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rs
index adaadd564..bc3ea3215 100644
--- a/crates/engine/src/paint_cmds.rs
+++ b/crates/engine/src/paint_cmds.rs
@@ -61,12 +61,16 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
_ => GradientShape::Linear,
};
let (fg, bg) = (s.tools.foreground, s.tools.background);
- let colors: Vec<[f32; 4]> = match p.get("colors").and_then(Value::as_array) {
- Some(a) if !a.is_empty() => a.iter().map(|v| color(Some(v), fg)).collect(),
- _ => vec![fg, bg],
+ // A preset (`gradient`), explicit `stops`, or the current gradient (Gradients panel); the
+ // legacy `colors` list spaces its colours evenly.
+ let stops: Vec<(f32, [f32; 4])> = match crate::presets::gradients::tool_stops(s, p)? {
+ Some(st) => st,
+ None => {
+ let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_else(|| vec![fg, bg]);
+ let n = colors.len();
+ colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect()
+ }
};
- let n = colors.len();
- let stops: Vec<(f32, [f32; 4])> = colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect();
let reverse = b(p, "reverse", false);
let opacity = f(p, "opacity", 100.0) / 100.0;
let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal);
@@ -98,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Gradient",
menu: &[],
shortcut: None,
- params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]=[foreground,background],"reverse":bool=false,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,
+ params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"reverse":bool=false,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target}"##,
enabled: crate::commands::has_paintable,
run: gradient,
journal: true,
diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rs
index ccd72891b..bb775a203 100644
--- a/crates/engine/src/pattern_cmds.rs
+++ b/crates/engine/src/pattern_cmds.rs
@@ -114,7 +114,8 @@ fn has_pattern(s: &Session) -> std::result::Result<(), String> {
/// picks the first library pattern (Photoshop's default).
pub fn resolve(s: &Session, key: &str) -> Option<Pattern> {
if key.is_empty() {
- return s.patterns.items.first().cloned();
+ // The Patterns panel's selection, else the first library pattern.
+ return crate::presets::patterns::current(s).or(s.patterns.items.first()).cloned();
}
if let Some(d) = s.active()
&& let Some(p) = photocraft_doc::pattern::find(&d.doc.patterns, key, key)
diff --git a/crates/engine/src/photo_cmds.rs b/crates/engine/src/photo_cmds.rs
new file mode 100644
index 000000000..9cbede6b6
--- /dev/null
+++ b/crates/engine/src/photo_cmds.rs
@@ -0,0 +1,960 @@
+//! Computational-photography automation: File › Automate › Photomerge, Merge to HDR Pro and
+//! Crop and Straighten Photos. The registration and blending code
+//! ([`photocraft_algo::panorama`]) is shared with Edit › Auto-Align / Auto-Blend Layers
+//! (`align_cmds`).
+//!
+//! Inputs are files (`"paths"`: an array or a folder) or, with `"useOpenDocuments": true`, the
+//! open documents (Photoshop's *Add Open Files*). Each command creates new documents; the
+//! sources are untouched.
+
+use photocraft_algo::exif;
+use photocraft_algo::hdr::{self, MergeOptions, ToneMethod};
+use photocraft_algo::panorama::{self, AlignOptions, Alignment, Layout, Placement, RoiImage};
+use photocraft_algo::scancrop;
+use photocraft_algo::tone::HdrToning;
+use photocraft_algo::transform::{Homography, Interp, warp_surface};
+use photocraft_algo::warp::warp_mesh_surface;
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{Document, Layer, LayerContent, LayerMask, Size};
+use photocraft_geom::Rect;
+use photocraft_raster::{Surface, to_rgba};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::file_cmds::{file_name, flattened, import, list_images, read_file};
+use crate::{EngineError, Result, Session};
+
+/// Longest side used for feature registration.
+pub(crate) const REGISTER_SIDE: usize = 1200;
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+// ---------- sources ----------
+
+/// One input image, flattened.
+pub(crate) struct Source {
+ pub name: String,
+ pub surf: Surface,
+ pub w: usize,
+ pub h: usize,
+ pub exif: exif::CameraInfo,
+}
+
+/// Loaded sources, the common pixel format and the first source's ICC profile.
+type Loaded = (Vec<Source>, PixelFormat, Option<std::sync::Arc<Vec<u8>>>);
+
+fn load_sources(s: &Session, p: &Value, cmd: &str) -> Result<Loaded> {
+ let mut docs: Vec<(String, Document)> = Vec::new();
+ if p.get("useOpenDocuments").and_then(Value::as_bool).unwrap_or(false) {
+ for d in s.documents() {
+ docs.push((d.doc.name.clone(), (*d.doc).clone()));
+ }
+ }
+ let paths: Vec<String> = match p.get("paths").or_else(|| p.get("input")) {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ Some(Value::String(dir)) => list_images(dir)?,
+ _ => Vec::new(),
+ };
+ for path in &paths {
+ let bytes = read_file(path)?;
+ docs.push((file_name(path), import(&file_name(path), &bytes)?));
+ }
+ if docs.is_empty() {
+ return Err(bad(cmd, "pass \"paths\" (files or a folder) or \"useOpenDocuments\": true"));
+ }
+ let first = &docs[0].1;
+ let mut fmt = first.pixel_format();
+ if matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab | ColorMode::Multichannel) {
+ // Registration and blending work in RGB; like Photoshop, the result is RGB.
+ fmt = PixelFormat::new(ColorMode::Rgb, fmt.sample, true);
+ }
+ let icc = (first.pixel_format().mode == fmt.mode).then(|| first.icc_profile.clone()).flatten();
+ let out = docs
+ .into_iter()
+ .map(|(name, d)| {
+ let info = d.metadata.exif.as_ref().map(|e| exif::read(e)).unwrap_or_default();
+ Source { name, surf: flattened(&d, fmt), w: d.size.width as usize, h: d.size.height as usize, exif: info }
+ })
+ .collect();
+ Ok((out, fmt, icc))
+}
+
+/// Luminance and coverage of `surf` over `area`, box-downsampled by `k`.
+pub(crate) fn luma_alpha(surf: &Surface, area: Rect, k: usize) -> (usize, usize, Vec<f32>, Vec<f32>) {
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let (sw, sh) = (w.div_ceil(k).max(1), h.div_ceil(k).max(1));
+ let (mut l, mut a, mut cnt) = (vec![0.0f32; sw * sh], vec![0.0f32; sw * sh], vec![0.0f32; sw * sh]);
+ // Row by row keeps memory small for large images.
+ for y in 0..h {
+ let row = surf.read_region(Rect::new(area.x0, area.y0 + y as i32, area.x1, area.y0 + y as i32 + 1));
+ for x in 0..w {
+ let p = to_rgba(&fmt, &row[x * n..(x + 1) * n]);
+ let i = (y / k) * sw + x / k;
+ l[i] += (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) * p[3] + (1.0 - p[3]) * 0.0;
+ a[i] += p[3];
+ cnt[i] += 1.0;
+ }
+ }
+ for i in 0..sw * sh {
+ let c = cnt[i].max(1.0);
+ l[i] = if a[i] > 0.0 { l[i] / a[i] } else { 0.0 };
+ a[i] /= c;
+ }
+ (sw, sh, l, a)
+}
+
+/// Registers `images` (surface, content area) and returns full-resolution placements.
+/// `focal35` is the 35 mm-equivalent focal length when known (EXIF).
+pub(crate) fn register(images: &[(&Surface, Rect)], layout: Layout, reference: Option<usize>, geometric: bool, focal35: Option<f64>) -> Option<Alignment> {
+ let side = images.iter().map(|(_, r)| r.width().max(r.height()) as usize).max().unwrap_or(1);
+ let k = side.div_ceil(REGISTER_SIDE).max(1);
+ let prepared: Vec<panorama::PreparedImage> = images
+ .iter()
+ .map(|(s, r)| {
+ let (w, h, l, a) = luma_alpha(s, *r, k);
+ let valid = a.iter().any(|v| *v < 0.5).then(|| a.iter().map(|v| *v > 0.5).collect());
+ (w, h, l, valid)
+ })
+ .collect();
+ let feats = panorama::detect_many(&prepared, 800);
+ let matches = panorama::match_pairs(&feats);
+ let focal = focal35.map(|f| f / 36.0 * side as f64 / k as f64);
+ let a = panorama::align(&feats, &matches, &AlignOptions { layout, focal, reference, geometric })?;
+ let kf = k as f64;
+ Some(Alignment { placements: a.placements.iter().map(|p| p.as_ref().map(|p| p.scaled(kf))).collect(), focal: a.focal * kf, rms: a.rms * kf, ..a })
+}
+
+/// The 35 mm focal length agreed by the sources' EXIF (median), if any.
+fn exif_focal(srcs: &[Source]) -> Option<f64> {
+ let mut f: Vec<f64> = srcs.iter().filter_map(|s| s.exif.focal_length_35mm).collect();
+ f.sort_by(f64::total_cmp);
+ f.get(f.len() / 2).copied()
+}
+
+/// Warps the content of `surf` inside `rect` by a placement shifted by `offset`; image
+/// coordinates are surface coordinates minus `origin`.
+pub(crate) fn warp_placed(surf: &Surface, rect: Rect, origin: (f64, f64), pl: &Placement, offset: (f64, f64), interp: Interp) -> Surface {
+ let pl = pl.translated(offset.0, offset.1);
+ if let Some(h) = plane_matrix(&pl, origin) {
+ return warp_surface(surf, rect, &h, interp);
+ }
+ warp_mesh_surface(surf, rect, &|x, y| pl.forward(x - origin.0, y - origin.1), interp)
+}
+
+/// The projective matrix of a planar, distortion-free placement (surface px → panorama px).
+pub(crate) fn plane_matrix(pl: &Placement, origin: (f64, f64)) -> Option<Homography> {
+ (pl.projection == panorama::Projection::Plane && pl.k1 == 0.0).then(|| {
+ let t = Homography([1.0, 0.0, -pl.center[0] - origin.0, 0.0, 1.0, -pl.center[1] - origin.1, 0.0, 0.0, 1.0]);
+ pl.h.mul(&t)
+ })
+}
+
+/// Splits a surface region into colour channels and coverage.
+fn roi_of(surf: &Surface, area: Rect) -> RoiImage {
+ let fmt = surf.format();
+ let n = fmt.channels();
+ let cc = fmt.mode.color_channels();
+ let raw = surf.read_region(area);
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let mut px = Vec::with_capacity(w * h * cc);
+ let mut alpha = Vec::with_capacity(w * h);
+ for q in raw.chunks_exact(n) {
+ px.extend_from_slice(&q[..cc]);
+ alpha.push(if fmt.alpha { q[n - 1] } else { 1.0 });
+ }
+ RoiImage { x0: area.x0, y0: area.y0, w, h, ch: cc, px, alpha }
+}
+
+/// Placements, source sizes and the panorama offset (for vignette removal).
+pub(crate) type BlendGeometry<'a> = (&'a [Placement], &'a [(usize, usize)], (f64, f64));
+
+/// Result of [`seam_blend`]: per input, the pixels to keep (blended inside its seam region)
+/// and its mask; plus the blended composite.
+pub(crate) struct Blended {
+ pub layers: Vec<(Surface, Surface)>,
+ pub composite: Surface,
+ pub gains: Vec<Vec<f32>>,
+ pub vignette: [f64; 2],
+}
+
+/// Gain compensation (+ optional vignetting), seams in `order`, multi-band blending. Inputs are
+/// surfaces already in panorama coordinates with alpha. `geometry` enables vignette removal.
+pub(crate) fn seam_blend(warped: &[Surface], canvas: Rect, order: &[usize], seamless: bool, gains: bool, geometry: Option<BlendGeometry>) -> Blended {
+ let n = warped.len();
+ let fmt = warped.first().map_or(PixelFormat::RGBA8, Surface::format);
+ let mut rois: Vec<RoiImage> = warped
+ .iter()
+ .map(|s| {
+ let b = s.content_bounds().intersect(&canvas);
+ if b.is_empty() { RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: fmt.mode.color_channels(), px: Vec::new(), alpha: Vec::new() } } else { roi_of(s, b) }
+ })
+ .collect();
+ // Photometric model in panorama coordinates relative to the canvas origin used by placements.
+ let shifted: Option<Vec<Placement>> = geometry.map(|(pl, _, off)| pl.iter().map(|p| p.translated(off.0, off.1)).collect());
+ let geo = match (&shifted, geometry) {
+ (Some(pl), Some((_, sizes, _))) => Some((pl.as_slice(), sizes)),
+ _ => None,
+ };
+ let photo = panorama::photometric(&rois, geo, seamless && gains, geo.is_some());
+ let vig = photo.vignette != [0.0, 0.0];
+ for (i, roi) in rois.iter_mut().enumerate() {
+ let ch = roi.ch;
+ if photo.gains[i].iter().all(|g| (*g - 1.0).abs() < 1e-6) && !vig {
+ continue;
+ }
+ for y in 0..roi.h {
+ for x in 0..roi.w {
+ let r2 = if vig {
+ let (pl, sizes) = geo.expect("vignette needs geometry");
+ pl[i].inverse((roi.x0 + x as i32) as f64 + 0.5, (roi.y0 + y as i32) as f64 + 0.5).map_or(0.0, |(sx, sy)| {
+ let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64);
+ let (dx, dy) = (sx - w / 2.0, sy - h / 2.0);
+ (dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)
+ })
+ } else {
+ 0.0
+ };
+ let k = y * roi.w + x;
+ for c in 0..ch {
+ let f = photo.factor(i, c, r2);
+ let v = &mut roi.px[k * ch + c];
+ *v = if fmt.mode == ColorMode::Cmyk { 1.0 - (1.0 - *v) * f } else { *v * f };
+ if fmt.sample != SampleType::F32 {
+ *v = v.clamp(0.0, 1.0);
+ }
+ }
+ }
+ }
+ }
+ // Seams on a ≤ 1000 px grid.
+ let (cw, chh) = (canvas.width().max(1) as usize, canvas.height().max(1) as usize);
+ let s = cw.max(chh).div_ceil(1000).max(1);
+ let (gw, gh) = (cw.div_ceil(s), chh.div_ceil(s));
+ let mut luma = vec![vec![0.0f32; gw * gh]; n];
+ let mut cover = vec![vec![false; gw * gh]; n];
+ for (i, roi) in rois.iter().enumerate() {
+ let mut acc = vec![(0.0f32, 0.0f32, 0u32); gw * gh];
+ for y in 0..roi.h {
+ for x in 0..roi.w {
+ let (u, v) = ((roi.x0 - canvas.x0) as usize + x, (roi.y0 - canvas.y0) as usize + y);
+ let g = (v / s).min(gh - 1) * gw + (u / s).min(gw - 1);
+ let k = y * roi.w + x;
+ let l = roi.px[k * roi.ch..(k + 1) * roi.ch].iter().sum::<f32>() / roi.ch as f32;
+ acc[g].0 += l;
+ acc[g].1 += roi.alpha[k];
+ acc[g].2 += 1;
+ }
+ }
+ for g in 0..gw * gh {
+ let (l, a, c) = acc[g];
+ if c > 0 {
+ luma[i][g] = l / c as f32;
+ cover[i][g] = a / (s * s) as f32 > 0.98;
+ }
+ }
+ }
+ let labels = panorama::seam_labels(gw, gh, &luma, &cover, order);
+ // Full-resolution weights: the seam label, falling back to the earliest covering image in
+ // `order` where the label's image doesn't cover the pixel.
+ let rank: Vec<usize> = {
+ let mut r = vec![usize::MAX; n];
+ for (k, &i) in order.iter().enumerate() {
+ r[i] = k;
+ }
+ r
+ };
+ let alpha_at = |j: usize, x: i32, y: i32| -> f32 {
+ let r = &rois[j];
+ let (lx, ly) = (x - r.x0, y - r.y0);
+ if lx < 0 || ly < 0 || lx as usize >= r.w || ly as usize >= r.h { 0.0 } else { r.alpha[ly as usize * r.w + lx as usize] }
+ };
+ let weights: Vec<Vec<f32>> = rois
+ .iter()
+ .enumerate()
+ .map(|(i, roi)| {
+ (0..roi.w * roi.h)
+ .map(|k| {
+ let (x, y) = (roi.x0 + (k % roi.w) as i32, roi.y0 + (k / roi.w) as i32);
+ if roi.alpha[k] < 0.5 {
+ return 0.0;
+ }
+ let (u, v) = ((x - canvas.x0) as usize, (y - canvas.y0) as usize);
+ let lab = labels[(v / s).min(gh - 1) * gw + (u / s).min(gw - 1)];
+ if lab == i as i32 {
+ return 1.0;
+ }
+ if lab >= 0 && alpha_at(lab as usize, x, y) >= 0.5 {
+ return 0.0;
+ }
+ // Fallback: the earliest covering image wins.
+ let first = (0..n).filter(|&j| alpha_at(j, x, y) >= 0.5).min_by_key(|&j| rank[j]);
+ if first == Some(i) { 1.0 } else { 0.0 }
+ })
+ .collect()
+ })
+ .collect();
+ // Shift ROIs to canvas-relative coordinates for the blend.
+ let local: Vec<RoiImage> = rois.iter().map(|r| RoiImage { x0: r.x0 - canvas.x0, y0: r.y0 - canvas.y0, ..r.clone() }).collect();
+ let levels = if seamless { panorama::blend_levels(cw, chh).min(7) } else { 1 };
+ let (blend, cov) = panorama::multiband(cw, chh, &local, &weights, levels);
+ let cc = fmt.mode.color_channels();
+ let nch = fmt.channels();
+ let mut composite = Surface::new(fmt);
+ {
+ let mut data = vec![0.0f32; cw * chh * nch];
+ for i in 0..cw * chh {
+ for c in 0..cc {
+ let v = blend[i * cc + c];
+ data[i * nch + c] = if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) };
+ }
+ data[i * nch + nch - 1] = cov[i];
+ }
+ composite.write_region(canvas, &data);
+ composite.prune();
+ }
+ let layers = rois
+ .iter()
+ .zip(&weights)
+ .map(|(roi, wt)| {
+ let area = Rect::new(roi.x0, roi.y0, roi.x0 + roi.w as i32, roi.y0 + roi.h as i32);
+ let mut px = vec![0.0f32; roi.w * roi.h * nch];
+ let mut mask = vec![0.0f32; roi.w * roi.h];
+ for k in 0..roi.w * roi.h {
+ let (u, v) = ((roi.x0 - canvas.x0) as usize + k % roi.w, (roi.y0 - canvas.y0) as usize + k / roi.w);
+ let g = v * cw + u;
+ let inside = wt[k] > 0.5;
+ for c in 0..cc {
+ px[k * nch + c] = if inside && seamless { data_clamp(blend[g * cc + c], fmt) } else { roi.px[k * cc + c] };
+ }
+ px[k * nch + nch - 1] = roi.alpha[k];
+ mask[k] = wt[k];
+ }
+ let mut ls = Surface::new(fmt);
+ if !area.is_empty() {
+ ls.write_region(area, &px);
+ }
+ ls.prune();
+ let mut ms = Surface::with_default(PixelFormat::GRAY8, &[0.0]);
+ if !area.is_empty() {
+ ms.write_region(area, &mask);
+ }
+ ms.prune();
+ (ls, ms)
+ })
+ .collect();
+ Blended { layers, composite, gains: photo.gains, vignette: photo.vignette }
+}
+
+fn data_clamp(v: f32, fmt: PixelFormat) -> f32 {
+ if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) }
+}
+
+/// Seam order: the reference first, then by distance of each image's centre from it.
+pub(crate) fn seam_order(warped: &[Surface], reference: usize) -> Vec<usize> {
+ let centre = |s: &Surface| {
+ let b = s.content_bounds();
+ ((b.x0 + b.x1) as f64 / 2.0, (b.y0 + b.y1) as f64 / 2.0)
+ };
+ let rc = centre(&warped[reference.min(warped.len() - 1)]);
+ let mut order: Vec<usize> = (0..warped.len()).collect();
+ order.sort_by(|&a, &b| {
+ let (ca, cb) = (centre(&warped[a]), centre(&warped[b]));
+ let (da, db) = ((ca.0 - rc.0).hypot(ca.1 - rc.1), (cb.0 - rc.0).hypot(cb.1 - rc.1));
+ (a != reference).cmp(&(b != reference)).then(da.total_cmp(&db))
+ });
+ order
+}
+
+// ---------- Photomerge ----------
+
+fn photomerge(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.photomerge";
+ let t0 = std::time::Instant::now();
+ let layout_s = p.get("layout").and_then(Value::as_str).unwrap_or("auto");
+ let layout = Layout::parse(layout_s).ok_or_else(|| bad(cmd, format!("unknown layout `{layout_s}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?;
+ let blend = p.get("blend").and_then(Value::as_bool).unwrap_or(true);
+ let vignette = p.get("vignetteRemoval").and_then(Value::as_bool).unwrap_or(false);
+ let geometric = p.get("geometricCorrection").and_then(Value::as_bool).unwrap_or(false);
+ let fill = p.get("contentAwareFill").and_then(Value::as_bool).unwrap_or(false);
+ let (srcs, fmt, icc) = load_sources(s, p, cmd)?;
+ if srcs.len() < 2 {
+ return Err(bad(cmd, "Photomerge needs two or more images"));
+ }
+ let focal35 = p.get("focalLength").and_then(Value::as_f64).filter(|f| *f > 0.0).or_else(|| exif_focal(&srcs));
+ let images: Vec<(&Surface, Rect)> = srcs.iter().map(|s| (&s.surf, Rect::new(0, 0, s.w as i32, s.h as i32))).collect();
+ let al = register(&images, layout, None, geometric, focal35).ok_or_else(|| EngineError::Other("Photomerge couldn't find enough matching detail between the images".into()))?;
+ let t_reg = t0.elapsed().as_secs_f64();
+ let placed: Vec<usize> = (0..srcs.len()).filter(|&i| al.placements[i].is_some()).collect();
+ let failed: Vec<String> = (0..srcs.len()).filter(|&i| al.placements[i].is_none()).map(|i| srcs[i].name.clone()).collect();
+ // Canvas: union of the placed images.
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for &i in &placed {
+ let b = al.placements[i].as_ref().expect("placed").bounds(srcs[i].w as f64, srcs[i].h as f64);
+ x0 = x0.min(b[0]);
+ y0 = y0.min(b[1]);
+ x1 = x1.max(b[2]);
+ y1 = y1.max(b[3]);
+ }
+ let (cw, ch) = ((x1 - x0).ceil(), (y1 - y0).ceil());
+ if !(cw.is_finite() && ch.is_finite()) || cw > 30_000.0 || ch > 30_000.0 || cw * ch > 6.0e8 {
+ return Err(EngineError::Other(format!("the panorama would be {cw}×{ch} px; try another layout")));
+ }
+ let canvas = Rect::new(0, 0, cw as i32, ch as i32);
+ let offset = (-x0.floor(), -y0.floor());
+ let warped: Vec<Surface> = {
+ let jobs: Vec<usize> = placed.clone();
+ jobs.iter().map(|&i| warp_placed(&srcs[i].surf, Rect::new(0, 0, srcs[i].w as i32, srcs[i].h as i32), (0.0, 0.0), al.placements[i].as_ref().expect("placed"), offset, Interp::Bicubic)).collect()
+ };
+ let t_warp = t0.elapsed().as_secs_f64();
+ let mut doc = Document::new(format!("Untitled_Panorama{}", s.documents().len() + 1), Size::new(cw as u32, ch as u32), fmt.mode, fmt.sample);
+ doc.icc_profile = icc;
+ let mut info = json!({});
+ let ref_pos = placed.iter().position(|&i| i == al.reference).unwrap_or(0);
+ if blend {
+ let pls: Vec<Placement> = placed.iter().map(|&i| al.placements[i].clone().expect("placed")).collect();
+ let sizes: Vec<(usize, usize)> = placed.iter().map(|&i| (srcs[i].w, srcs[i].h)).collect();
+ let order = seam_order(&warped, ref_pos);
+ let geo = vignette.then_some((pls.as_slice(), sizes.as_slice(), offset));
+ let b = seam_blend(&warped, canvas, &order, true, true, geo);
+ for (k, (px, mask)) in b.layers.into_iter().enumerate() {
+ let mut l = Layer::new(srcs[placed[k]].name.clone(), LayerContent::Raster(px));
+ let mut m = LayerMask::hide_all();
+ m.surface = mask;
+ l.mask = Some(m);
+ doc.layers.push(l);
+ }
+ info = json!({"gains": b.gains, "vignette": b.vignette});
+ if fill {
+ let filled = content_aware_fill(&b.composite, canvas);
+ doc.layers.push(Layer::new("Content-Aware Fill", LayerContent::Raster(filled)));
+ }
+ } else {
+ for (k, px) in warped.into_iter().enumerate() {
+ doc.layers.push(Layer::new(srcs[placed[k]].name.clone(), LayerContent::Raster(px)));
+ }
+ }
+ let n = doc.layers.len();
+ let idx = s.add_document(doc, None);
+ Ok(json!({
+ "document": idx,
+ "layout": al.layout.name(),
+ "reference": srcs[al.reference].name,
+ "focalLength35": al.focal / (srcs.iter().map(|s| s.w.max(s.h)).max().unwrap_or(1) as f64) * 36.0,
+ "geometricK1": al.k1,
+ "rms": al.rms,
+ "pairs": al.pairs,
+ "placed": placed.iter().map(|&i| srcs[i].name.clone()).collect::<Vec<_>>(),
+ "failed": failed,
+ "width": cw as u32,
+ "height": ch as u32,
+ "layers": n,
+ "photometric": info,
+ "ms": {"register": t_reg * 1000.0, "warp": (t_warp - t_reg) * 1000.0, "total": t0.elapsed().as_secs_f64() * 1000.0},
+ }))
+}
+
+/// Fills the transparent areas of a composite (inside its bounding rectangle) with
+/// content-aware fill, at a reduced scale for large panoramas.
+fn content_aware_fill(comp: &Surface, canvas: Rect) -> Surface {
+ use photocraft_algo::content_aware::{FillOptions, fill};
+ let fmt = comp.format();
+ let n = fmt.channels();
+ let (w, h) = (canvas.width() as usize, canvas.height() as usize);
+ let k = ((w * h) as f64 / 1.5e6).sqrt().ceil().max(1.0) as usize;
+ let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
+ let full = comp.read_region(canvas);
+ let cc = n - 1;
+ let mut small = vec![0.0f32; sw * sh * cc];
+ let mut hole = vec![false; sw * sh];
+ let mut acc_a = vec![0.0f32; sw * sh];
+ let mut cnt = vec![0.0f32; sw * sh];
+ for y in 0..h {
+ for x in 0..w {
+ let i = (y / k) * sw + x / k;
+ let px = &full[(y * w + x) * n..(y * w + x + 1) * n];
+ let a = px[cc];
+ for c in 0..cc {
+ small[i * cc + c] += px[c] * a;
+ }
+ acc_a[i] += a;
+ cnt[i] += 1.0;
+ }
+ }
+ for i in 0..sw * sh {
+ let a = acc_a[i];
+ for c in 0..cc {
+ small[i * cc + c] = if a > 0.0 { small[i * cc + c] / a } else { 0.0 };
+ }
+ hole[i] = a / cnt[i].max(1.0) < 0.99;
+ }
+ let source: Vec<bool> = hole.iter().map(|h| !h).collect();
+ let filled = fill(sw, sh, cc, &small, &hole, &source, &FillOptions::default());
+ let mut out = vec![0.0f32; w * h * n];
+ for y in 0..h {
+ for x in 0..w {
+ let o = (y * w + x) * n;
+ let a = full[o + cc];
+ let i = (y / k) * sw + x / k;
+ for c in 0..cc {
+ // Bilinear upsampling of the fill under partially covered pixels.
+ let fx = ((x as f32 + 0.5) / k as f32 - 0.5).clamp(0.0, (sw - 1) as f32);
+ let fy = ((y as f32 + 0.5) / k as f32 - 0.5).clamp(0.0, (sh - 1) as f32);
+ let (xi, yi) = (fx as usize, fy as usize);
+ let (x2, y2) = ((xi + 1).min(sw - 1), (yi + 1).min(sh - 1));
+ let (tx, ty) = (fx - xi as f32, fy - yi as f32);
+ let at = |xx: usize, yy: usize| filled[(yy * sw + xx) * cc + c];
+ let fv = (at(xi, yi) * (1.0 - tx) + at(x2, yi) * tx) * (1.0 - ty) + (at(xi, y2) * (1.0 - tx) + at(x2, y2) * tx) * ty;
+ let _ = i;
+ out[o + c] = full[o + c] * a + fv * (1.0 - a);
+ }
+ out[o + cc] = 1.0;
+ }
+ }
+ let mut s = Surface::new(fmt);
+ s.write_region(canvas, &out);
+ s.prune();
+ s
+}
+
+// ---------- Merge to HDR Pro ----------
+
+fn shift_rgba(px: &[[f32; 4]], w: usize, h: usize, dx: i32, dy: i32) -> Vec<[f32; 4]> {
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = ((i % w) as i32 - dx, (i / w) as i32 - dy);
+ px[(y.clamp(0, h as i32 - 1) as usize) * w + x.clamp(0, w as i32 - 1) as usize]
+ })
+ .collect()
+}
+
+fn merge_to_hdr(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.automate.mergeToHdrPro";
+ let t0 = std::time::Instant::now();
+ let (srcs, _fmt, icc) = load_sources(s, p, cmd)?;
+ if srcs.len() < 2 {
+ return Err(bad(cmd, "Merge to HDR Pro needs two or more exposures"));
+ }
+ let (w, h) = (srcs[0].w, srcs[0].h);
+ if srcs.iter().any(|s| s.w != w || s.h != h) {
+ return Err(EngineError::Other("the exposures must have the same pixel dimensions".into()));
+ }
+ let area = Rect::new(0, 0, w as i32, h as i32);
+ let mut imgs: Vec<Vec<[f32; 4]>> = srcs
+ .iter()
+ .map(|s| {
+ let mut v = vec![[0.0f32; 4]; w * h];
+ s.surf.read_rgba_into(area, &mut v);
+ v
+ })
+ .collect();
+ // Exposures: explicit EV, EXIF, or estimated.
+ let (exposures, source): (Vec<f64>, &str) = match p.get("exposures").and_then(Value::as_array) {
+ Some(a) if a.len() == srcs.len() => (a.iter().map(|v| 2f64.powf(v.as_f64().unwrap_or(0.0))).collect(), "params"),
+ Some(_) => return Err(bad(cmd, "`exposures` needs one EV value per image")),
+ None => match srcs.iter().map(|s| s.exif.exposure_factor()).collect::<Option<Vec<f64>>>() {
+ Some(e) => (e, "exif"),
+ None => {
+ let refs: Vec<&[[f32; 4]]> = imgs.iter().map(Vec::as_slice).collect();
+ (hdr::estimate_exposures(&refs), "estimated")
+ }
+ },
+ };
+ if exposures.iter().any(|e| !(e.is_finite() && *e > 0.0)) {
+ return Err(bad(cmd, "exposures must be positive"));
+ }
+ // Alignment (Ward's MTB) to the middle exposure, on a downsampled grey copy.
+ let mut order: Vec<usize> = (0..srcs.len()).collect();
+ order.sort_by(|&a, &b| exposures[a].total_cmp(&exposures[b]));
+ let mid = order[order.len() / 2];
+ let mut offsets = vec![(0, 0); srcs.len()];
+ if p.get("align").and_then(Value::as_bool).unwrap_or(true) {
+ let k = w.max(h).div_ceil(1536).max(1);
+ let grey = |im: &[[f32; 4]]| -> (usize, usize, Vec<f32>) {
+ let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
+ let mut g = vec![0.0f32; sw * sh];
+ let mut c = vec![0.0f32; sw * sh];
+ for (i, q) in im.iter().enumerate() {
+ let j = (i / w / k) * sw + (i % w) / k;
+ g[j] += (54.0 * q[0] + 183.0 * q[1] + 19.0 * q[2]) / 256.0;
+ c[j] += 1.0;
+ }
+ (sw, sh, g.iter().zip(&c).map(|(a, b)| a / b.max(1.0)).collect())
+ };
+ let (sw, sh, gref) = grey(&imgs[mid]);
+ for i in 0..srcs.len() {
+ if i == mid {
+ continue;
+ }
+ let (_, _, gi) = grey(&imgs[i]);
+ let (dx, dy) = hdr::mtb_offset(sw, sh, &gref, &gi, 5);
+ offsets[i] = (dx * k as i32, dy * k as i32);
+ if offsets[i] != (0, 0) {
+ imgs[i] = shift_rgba(&imgs[i], w, h, offsets[i].0, offsets[i].1);
+ }
+ }
+ }
+ let ghost_base = p.get("ghostBase").and_then(Value::as_u64).map(|v| v as usize);
+ if ghost_base.is_some_and(|g| g >= srcs.len()) {
+ return Err(bad(cmd, "`ghostBase` is an image index"));
+ }
+ let refs: Vec<&[[f32; 4]]> = imgs.iter().map(Vec::as_slice).collect();
+ let merged = hdr::merge(w, h, &refs, &MergeOptions { exposures: exposures.clone(), remove_ghosts: p.get("removeGhosts").and_then(Value::as_bool).unwrap_or(false), ghost_base, response: None });
+ let mode = p.get("mode").and_then(|v| v.as_str().map(str::to_string).or_else(|| v.as_u64().map(|n| n.to_string()))).unwrap_or_else(|| "32".into());
+ let (depth, mut px) = match mode.as_str() {
+ "32" => (SampleType::F32, merged.px.clone()),
+ "16" | "8" => {
+ let method = p.get("method").and_then(Value::as_str).unwrap_or("localAdaptation");
+ let f = |k: &str, d: f64| p.get(k).and_then(Value::as_f64).unwrap_or(d) as f32;
+ let tm = match method {
+ "localAdaptation" => ToneMethod::LocalAdaptation(HdrToning {
+ radius: f("radius", 7.0).clamp(1.0, 500.0),
+ strength: f("strength", 0.52).clamp(0.1, 4.0),
+ gamma: f("gamma", 1.0).clamp(0.1, 2.0),
+ exposure: f("exposure", 0.0).clamp(-5.0, 5.0),
+ detail: f("detail", 30.0).clamp(-100.0, 300.0),
+ shadow: f("shadow", 0.0).clamp(-100.0, 100.0),
+ highlight: f("highlight", 0.0).clamp(-100.0, 100.0),
+ vibrance: f("vibrance", 0.0).clamp(-100.0, 100.0),
+ saturation: f("saturation", 20.0).clamp(-100.0, 100.0),
+ curve: Vec::new(),
+ }),
+ "exposureGamma" => ToneMethod::ExposureGamma { exposure: f("exposure", 0.0), gamma: f("gamma", 1.0) },
+ "highlightCompression" => ToneMethod::HighlightCompression,
+ "equalizeHistogram" => ToneMethod::EqualizeHistogram,
+ other => return Err(bad(cmd, format!("unknown method `{other}` (localAdaptation|exposureGamma|highlightCompression|equalizeHistogram)"))),
+ };
+ let mut v = merged.px.clone();
+ hdr::tone_map(&mut v, w, h, &tm);
+ (if mode == "16" { SampleType::U16 } else { SampleType::U8 }, v)
+ }
+ other => return Err(bad(cmd, format!("`mode` must be 32|16|8, not {other}"))),
+ };
+ for q in px.iter_mut() {
+ q[3] = 1.0;
+ }
+ let mut doc = Document::new(format!("Untitled_HDR{}", s.documents().len() + 1), Size::new(w as u32, h as u32), ColorMode::Rgb, depth);
+ doc.icc_profile = if depth == SampleType::F32 { Some(photocraft_cms::builtin::Builtin::LinearSrgb.profile().to_bytes()) } else { icc };
+ let fmt = doc.pixel_format();
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; w * h * n];
+ for (q, o) in px.iter().zip(data.chunks_exact_mut(n)) {
+ photocraft_raster::from_rgba_into(&fmt, *q, o);
+ }
+ let mut surf = Surface::new(fmt);
+ surf.write_region(area, &data);
+ doc.layers.push(Layer::new("Background", LayerContent::Raster(surf)));
+ let idx = s.add_document(doc, None);
+ let ev0 = exposures[order[0]];
+ Ok(json!({
+ "document": idx,
+ "mode": mode,
+ "exposureSource": source,
+ "ev": exposures.iter().map(|e| (e / ev0).log2()).collect::<Vec<_>>(),
+ "offsets": offsets,
+ "ghostBase": merged.ghost_base,
+ "ghostFraction": merged.ghost_fraction,
+ "stops": merged.stops,
+ "ms": t0.elapsed().as_secs_f64() * 1000.0,
+ }))
+}
+
+// ---------- Crop and Straighten Photos ----------
+
+fn crop_and_straighten(s: &mut Session, _p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = st.doc.clone();
+ let fmt = doc.pixel_format();
+ let flat = flattened(&doc, fmt);
+ let area = doc.bounds();
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let mut rgba = vec![[0.0f32; 4]; w * h];
+ flat.read_rgba_into(area, &mut rgba);
+ // Transparent pixels count as background.
+ for q in rgba.iter_mut() {
+ if q[3] < 1.0 {
+ let a = q[3];
+ for v in &mut q[..3] {
+ *v = *v * a + (1.0 - a);
+ }
+ }
+ }
+ let found = scancrop::find_photos(w, h, &rgba);
+ if found.is_empty() {
+ return Err(EngineError::Other("no photos found on a uniform background".into()));
+ }
+ let mut out = Vec::new();
+ for (k, f) in found.iter().enumerate() {
+ let (pw, ph) = (f.width.round().max(1.0) as u32, f.height.round().max(1.0) as u32);
+ let corners = f.corners();
+ let hq = Homography::rect_to_quad([0.0, 0.0, pw as f64, ph as f64], corners).and_then(|h| h.inverse());
+ let Some(hm) = hq else { continue };
+ let warped = warp_surface(&flat, area, &hm, Interp::Bicubic);
+ let keep = Rect::new(0, 0, pw as i32, ph as i32);
+ let mut px = Surface::new(fmt);
+ px.write_region(keep, &warped.read_region(keep));
+ // Opaque, like a scanned print.
+ let n = fmt.channels();
+ let mut data = px.read_region(keep);
+ for q in data.chunks_exact_mut(n) {
+ q[n - 1] = 1.0;
+ }
+ px.write_region(keep, &data);
+ let mut nd = Document::new(format!("{} copy {}", doc.name, k + 1), Size::new(pw, ph), doc.mode, doc.depth);
+ nd.icc_profile = doc.icc_profile.clone();
+ nd.resolution_dpi = doc.resolution_dpi;
+ let mut bg = Layer::new("Background", LayerContent::Raster(px));
+ bg.locks.transparency = true;
+ bg.locks.position = true;
+ nd.layers.push(bg);
+ let idx = s.add_document(nd, None);
+ out.push(json!({"document": idx, "width": pw, "height": ph, "angle": f.angle, "center": f.center}));
+ }
+ Ok(json!({"photos": out}))
+}
+
+// ---------- specs ----------
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "file.automate.photomerge",
+ label: "Photomerge…",
+ menu: &["File", "Automate"],
+ shortcut: None,
+ params: r##"{"paths":[str]|folder,"useOpenDocuments":bool=false,"layout":"auto|perspective|cylindrical|spherical|collage|reposition","blend":bool=true,"vignetteRemoval":bool=false,"geometricCorrection":bool=false,"contentAwareFill":bool=false,"focalLength":mm=0 (35 mm equivalent; 0 = EXIF or estimated)} → new document, one masked layer per image"##,
+ enabled: always,
+ run: photomerge,
+ journal: true,
+ },
+ CommandSpec {
+ id: "file.automate.mergeToHdrPro",
+ label: "Merge to HDR Pro…",
+ menu: &["File", "Automate"],
+ shortcut: None,
+ params: r##"{"paths":[str]|folder,"useOpenDocuments":bool=false,"exposures":[ev]? (default EXIF, else estimated),"align":bool=true,"removeGhosts":bool=false,"ghostBase":int?,"mode":"32|16|8","method":"localAdaptation|exposureGamma|highlightCompression|equalizeHistogram","radius":1..500=7,"strength":0.1..4=0.52,"gamma":0.1..2=1,"exposure":-5..5=0,"detail":-100..300=30,"shadow":-100..100=0,"highlight":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=20} → new document (32-bit linear, or tone-mapped 16/8-bit)"##,
+ enabled: always,
+ run: merge_to_hdr,
+ journal: true,
+ },
+ CommandSpec {
+ id: "file.automate.cropAndStraightenPhotos",
+ label: "Crop and Straighten Photos",
+ menu: &["File", "Automate"],
+ shortcut: None,
+ params: "{} → one new document per photo found on the scan",
+ enabled: has_doc,
+ run: crop_and_straighten,
+ journal: true,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A textured RGB scene (deterministic blobs on a gradient).
+ fn scene(w: usize, h: usize, seed: u64) -> Vec<[f32; 4]> {
+ let mut z = seed;
+ let mut rnd = || {
+ z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ (z >> 33) as f64 / (1u64 << 31) as f64
+ };
+ let mut px: Vec<[f32; 4]> = (0..w * h).map(|i| { let x = (i % w) as f32 / w as f32; [0.3 + 0.2 * x, 0.35, 0.4 - 0.1 * x, 1.0] }).collect();
+ for _ in 0..(w * h / 700) {
+ let (cx, cy, r) = (rnd() * w as f64, rnd() * h as f64, 3.0 + rnd() * 9.0);
+ let col = [rnd() as f32, rnd() as f32, rnd() as f32, 1.0];
+ for y in (cy - r).max(0.0) as usize..((cy + r) as usize + 1).min(h) {
+ for x in (cx - r).max(0.0) as usize..((cx + r) as usize + 1).min(w) {
+ if (x as f64 - cx).hypot(y as f64 - cy) < r {
+ px[y * w + x] = col;
+ }
+ }
+ }
+ }
+ px
+ }
+
+ fn doc_from(name: &str, px: &[[f32; 4]], w: usize, h: usize, depth: SampleType) -> Document {
+ let mut d = Document::new(name, Size::new(w as u32, h as u32), ColorMode::Rgb, depth);
+ let fmt = d.pixel_format();
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; w * h * n];
+ for (q, o) in px.iter().zip(data.chunks_exact_mut(n)) {
+ photocraft_raster::from_rgba_into(&fmt, *q, o);
+ }
+ let mut s = Surface::new(fmt);
+ s.write_region(Rect::new(0, 0, w as i32, h as i32), &data);
+ d.layers.push(Layer::new("Background", LayerContent::Raster(s)));
+ d
+ }
+
+ fn crop(px: &[[f32; 4]], sw: usize, x0: usize, y0: usize, w: usize, h: usize, gain: f32) -> Vec<[f32; 4]> {
+ (0..w * h).map(|i| { let q = px[(y0 + i / w) * sw + x0 + i % w]; [q[0] * gain, q[1] * gain, q[2] * gain, 1.0] }).collect()
+ }
+
+ #[test]
+ fn photomerge_open_documents_reposition_and_perspective() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let (sw, sh) = (520, 220);
+ let sc = scene(sw, sh, 5);
+ let mut s = Session::new();
+ // Three overlapping crops, the middle one 15 % brighter (gain compensation).
+ for (k, (x0, g)) in [(0usize, 1.0f32), (130, 1.15), (260, 1.0)].into_iter().enumerate() {
+ s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 220, 200, g), 220, 200, depth), None);
+ }
+ let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition"})).unwrap();
+ assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}");
+ let (w, h) = (r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap());
+ assert!((w as i64 - 480).abs() <= 2 && (h as i64 - 200).abs() <= 2, "{depth:?} {w}×{h}");
+ let d = &s.active().unwrap().doc;
+ assert_eq!(d.layers.len(), 3);
+ assert!(d.layers.iter().all(|l| l.mask.is_some()));
+ // Masks partition the panorama: every covered pixel is shown by exactly one layer.
+ for &(x, y) in &[(20, 100), (200, 50), (380, 150), (470, 120)] {
+ let shown: f32 = d.layers.iter().map(|l| l.mask.as_ref().unwrap().value(x, y) * l.surface().unwrap().rgba(x, y)[3]).sum();
+ assert!((shown - 1.0).abs() < 0.01, "({x},{y}) {shown}");
+ }
+ // The composite matches the scene up to the global gain.
+ let comp = photocraft_compose::flatten(d);
+ let at = |x: i32, y: i32| comp.px[(y * comp.rect.width() as i32 + x) as usize];
+ let gains = r["photometric"]["gains"].as_array().unwrap();
+ assert!(gains[1][0].as_f64().unwrap() > gains[0][0].as_f64().unwrap() * 1.05, "{r}");
+ let probe = at(160, 100);
+ let truth = sc[110 * sw + 160];
+ assert!((probe[1] - truth[1]).abs() < 0.08, "{probe:?} vs {truth:?}");
+ }
+ // Perspective + no blending: plain layers, no masks.
+ let (sw, sh) = (520, 220);
+ let sc = scene(sw, sh, 8);
+ let mut s = Session::new();
+ for (k, x0) in [0usize, 180].into_iter().enumerate() {
+ s.add_document(doc_from(&format!("p{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None);
+ }
+ let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "perspective", "blend": false})).unwrap();
+ assert_eq!(r["layout"], "perspective");
+ let d = &s.active().unwrap().doc;
+ assert!(d.layers.iter().all(|l| l.mask.is_none()));
+ assert!((r["width"].as_i64().unwrap() - 440).abs() <= 8, "{r}");
+ assert!(s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "zigzag"})).is_err());
+ let mut empty = Session::new();
+ assert!(empty.execute("file.automate.photomerge", json!({})).is_err());
+ }
+
+ #[test]
+ fn photomerge_cylindrical_with_fill() {
+ let (sw, sh) = (900, 260);
+ let sc = scene(sw, sh, 21);
+ let f = 260.0f64;
+ let mut s = Session::new();
+ let (tw, th) = (260usize, 200usize);
+ for (k, pan) in [-0.45f64, 0.0, 0.45].into_iter().enumerate() {
+ let px: Vec<[f32; 4]> = (0..tw * th)
+ .map(|i| {
+ let (dx, dy) = ((i % tw) as f64 - tw as f64 / 2.0, (i / tw) as f64 - th as f64 / 2.0);
+ let (u, v) = (sw as f64 / 2.0 + f * (dx.atan2(f) + pan), sh as f64 / 2.0 + f * dy / dx.hypot(f));
+ sc[(v.round().clamp(0.0, sh as f64 - 1.0) as usize) * sw + u.round().clamp(0.0, sw as f64 - 1.0) as usize]
+ })
+ .collect();
+ s.add_document(doc_from(&format!("c{k}"), &px, tw, th, SampleType::U8), None);
+ }
+ let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "cylindrical", "contentAwareFill": true})).unwrap();
+ assert_eq!(r["layout"], "cylindrical");
+ assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}");
+ let d = &s.active().unwrap().doc;
+ let top = d.layers.last().unwrap();
+ assert_eq!(top.name, "Content-Aware Fill");
+ // The fill layer is opaque everywhere (the bow-tie corners are filled).
+ let b = d.bounds();
+ assert!(top.surface().unwrap().rgba(1, 1)[3] > 0.99 && top.surface().unwrap().rgba(b.x1 - 2, b.y1 - 2)[3] > 0.99);
+ }
+
+ #[test]
+ fn hdr_merge_from_synthetic_exposures() {
+ let (w, h) = (96usize, 64usize);
+ let radiance: Vec<[f32; 3]> = (0..w * h).map(|i| { let x = (i % w) as f32 / w as f32; let b = 0.003 * 2f32.powf(x * 11.0) * (1.0 + 0.2 * ((i / w) as f32 * 0.3).sin()); [b, b * 0.9, b * 0.7] }).collect();
+ let shoot = |dt: f32| -> Vec<[f32; 4]> { radiance.iter().map(|r| { let f = |v: f32| photocraft_algo_srgb((v * dt).min(1.0)); [f(r[0]), f(r[1]), f(r[2]), 1.0] }).collect() };
+ let mut s = Session::new();
+ for (k, dt) in [0.25f32, 1.0, 4.0].into_iter().enumerate() {
+ let mut d = doc_from(&format!("e{k}"), &shoot(dt), w, h, SampleType::U8);
+ d.metadata.exif = Some(std::sync::Arc::new(exif::build(&exif::CameraInfo { exposure_time: Some(dt as f64 / 100.0), f_number: Some(8.0), iso: Some(100.0), ..Default::default() })));
+ s.add_document(d, None);
+ }
+ let r = s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true})).unwrap();
+ assert_eq!(r["exposureSource"], "exif");
+ let ev: Vec<f64> = r["ev"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert!((ev[1] - 2.0).abs() < 1e-6 && (ev[2] - 4.0).abs() < 1e-6, "{ev:?}");
+ let d = &s.active().unwrap().doc;
+ assert_eq!(d.depth, SampleType::F32);
+ let l = d.layers[0].surface().unwrap();
+ // Linear output: ratios across the ramp follow the radiance.
+ let (a, b) = (l.rgba(20, 30)[1] as f64, l.rgba(80, 30)[1] as f64);
+ let expect = radiance[30 * w + 80][1] as f64 / radiance[30 * w + 20][1] as f64;
+ assert!(((b / a) / expect).ln().abs() < 0.3, "{} vs {expect}", b / a);
+ assert!(r["stops"].as_f64().unwrap() > 7.0, "{r}");
+ let out = r["document"].as_u64().unwrap() as usize;
+ s.close(out);
+ // 8-bit tone-mapped output with explicit EVs.
+ for method in ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"] {
+ let r = s.execute("file.automate.mergeToHdrPro", json!({"paths": [], "useOpenDocuments": true, "exposures": [0, 2, 4], "mode": "8", "method": method})).unwrap();
+ assert_eq!(r["exposureSource"], "params");
+ let d = &s.active().unwrap().doc;
+ assert_eq!(d.depth, SampleType::U8);
+ let out = r["document"].as_u64().unwrap() as usize;
+ s.close(out);
+ }
+ assert!(s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true, "exposures": [0, 1]})).is_err());
+ }
+
+ fn photocraft_algo_srgb(v: f32) -> f32 {
+ if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
+ }
+
+ #[test]
+ fn crop_and_straighten_makes_documents() {
+ let (w, h) = (500usize, 360usize);
+ let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h];
+ let photos = [([140.0f64, 120.0f64], 160.0f64, 110.0f64, 6.0f64), ([360.0, 240.0], 150.0, 120.0, -9.0)];
+ for (c, pw, ph, ang) in photos {
+ let (s, co) = ang.to_radians().sin_cos();
+ for y in 0..h {
+ for x in 0..w {
+ let (dx, dy) = (x as f64 + 0.5 - c[0], y as f64 + 0.5 - c[1]);
+ let (u, v) = (co * dx + s * dy, -s * dx + co * dy);
+ if u.abs() < pw / 2.0 && v.abs() < ph / 2.0 {
+ px[y * w + x] = [0.2 + (u / pw) as f32 * 0.3, 0.3, 0.6, 1.0];
+ }
+ }
+ }
+ }
+ let mut s = Session::new();
+ s.add_document(doc_from("scan", &px, w, h, SampleType::U16), None);
+ assert!(s.is_enabled("file.automate.cropAndStraightenPhotos"));
+ let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap();
+ let found = r["photos"].as_array().unwrap();
+ assert_eq!(found.len(), 2, "{r}");
+ assert_eq!(s.documents().len(), 3);
+ assert!((found[0]["angle"].as_f64().unwrap() - 6.0).abs() < 1.0);
+ let d = &s.documents()[1].doc;
+ assert!((d.size.width as i64 - 158).abs() <= 4 && (d.size.height as i64 - 108).abs() <= 4, "{:?}", d.size);
+ assert_eq!(d.depth, SampleType::U16);
+ // Upright: the photo's horizontal gradient runs along x.
+ let l = d.layers[0].surface().unwrap();
+ let (a, b) = (l.rgba(10, d.size.height as i32 / 2)[0], l.rgba(d.size.width as i32 - 10, d.size.height as i32 / 2)[0]);
+ assert!(b > a + 0.15, "{a} {b}");
+ let (c, e) = (l.rgba(d.size.width as i32 / 2, 6)[0], l.rgba(d.size.width as i32 / 2, d.size.height as i32 - 6)[0]);
+ assert!((c - e).abs() < 0.05);
+ }
+}
diff --git a/crates/engine/src/pick_cmds.rs b/crates/engine/src/pick_cmds.rs
new file mode 100644
index 000000000..a5015cc54
--- /dev/null
+++ b/crates/engine/src/pick_cmds.rs
@@ -0,0 +1,113 @@
+//! Move tool Auto-Select: pick the topmost visible layer with pixels at a canvas point (Photoshop's
+//! options bar "Auto-Select: Layer | Group", ⌘-click with the Move tool, and the canvas right-click
+//! layer list).
+
+use photocraft_doc::{Document, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document".into())
+}
+
+/// Layers with visible pixels at (x, y), topmost first (hidden layers and hidden groups skipped).
+pub fn layers_at(doc: &Document, x: i32, y: i32) -> Vec<LayerId> {
+ let rows = doc.walk();
+ let mut out = Vec::new();
+ for (path, _, l) in rows.iter().rev() {
+ // The layer and every enclosing group must be visible.
+ if !(1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible)) {
+ continue;
+ }
+ if matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) {
+ continue;
+ }
+ let alpha = match &l.content {
+ // Fill layers cover the canvas (their mask limits them).
+ LayerContent::Fill(_) => 1.0,
+ _ => match l.surface() {
+ Some(s) => {
+ let mut px = [[0.0f32; 4]; 1];
+ s.read_rgba_into(Rect::from_xywh(x, y, 1, 1), &mut px);
+ px[0][3]
+ }
+ None => 0.0,
+ },
+ };
+ let mask = l.mask.as_ref().filter(|m| m.enabled).map_or(1.0, |m| {
+ let mut v = [0.0f32];
+ m.surface.read_pixel(x, y, &mut v);
+ v[0]
+ });
+ if alpha * mask > 0.0 {
+ out.push(l.id);
+ }
+ }
+ out
+}
+
+/// The outermost group containing `id` (the layer itself when it isn't in a group).
+fn top_group(doc: &Document, id: LayerId) -> LayerId {
+ doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(path, _, _)| doc.layer_at(&path[..1])).map_or(id, |l| l.id)
+}
+
+fn pick(s: &mut Session, p: &Value) -> Result<Value> {
+ let x = p.get("x").and_then(Value::as_f64).ok_or_else(|| EngineError::BadParams { cmd: "layer.pickAt".into(), msg: "missing `x`".into() })?.floor() as i32;
+ let y = p.get("y").and_then(Value::as_f64).ok_or_else(|| EngineError::BadParams { cmd: "layer.pickAt".into(), msg: "missing `y`".into() })?.floor() as i32;
+ let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let hits = layers_at(&doc, x, y);
+ if p.get("list").and_then(Value::as_bool).unwrap_or(false) {
+ let names: Vec<Value> = hits.iter().filter_map(|id| doc.layer(*id)).map(|l| json!({"layer": l.id.0, "name": l.name})).collect();
+ return Ok(json!({ "layers": names }));
+ }
+ let Some(&hit) = hits.first() else { return Ok(json!({ "layer": null })) };
+ let target = if p.get("target").and_then(Value::as_str) == Some("group") { top_group(&doc, hit) } else { hit };
+ if p.get("select").and_then(Value::as_bool).unwrap_or(true) {
+ let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace");
+ s.execute("layer.select", json!({"layer": target.0, "mode": mode}))?;
+ }
+ Ok(json!({ "layer": target.0 }))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: "layer.pickAt",
+ label: "Auto-Select Layer",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"x":px,"y":px,"target":"layer|group"="layer","select":bool=true,"mode":"replace|toggle|add"="replace","list":bool=false (return every layer with pixels there, topmost first)} → {layer} | {layers}"##,
+ enabled: has_doc,
+ journal: false,
+ run: pick,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn picks_topmost_layer_with_pixels() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();
+ let bg = s.active().unwrap().doc.layers[0].id;
+ s.execute("layer.new.layer", json!({"name": "A"})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ let a = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.new.layer", json!({"name": "B"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ // Empty B is skipped; A wins inside its square, the Background elsewhere.
+ assert_eq!(s.execute("layer.pickAt", json!({"x": 5, "y": 5})).unwrap()["layer"], a.0);
+ assert_eq!(s.active().unwrap().active_layer, Some(a));
+ assert_eq!(s.execute("layer.pickAt", json!({"x": 30, "y": 30, "select": false})).unwrap()["layer"], bg.0);
+ let list = s.execute("layer.pickAt", json!({"x": 5, "y": 5, "list": true})).unwrap();
+ assert_eq!(list["layers"].as_array().unwrap().len(), 2);
+ // Hidden layers are ignored.
+ s.execute("layer.setProps", json!({"layer": a.0, "visible": false})).unwrap();
+ assert_eq!(s.execute("layer.pickAt", json!({"x": 5, "y": 5, "select": false})).unwrap()["layer"], bg.0);
+ }
+}
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
index 4d749d009..5e49ac3a2 100644
--- a/crates/engine/src/prefs.rs
+++ b/crates/engine/src/prefs.rs
@@ -632,6 +632,14 @@ pub struct Preferences {
pub shortcuts: BTreeMap<String, String>,
pub menus: MenuCustomization,
pub toolbar: ToolbarCustomization,
+ /// Edit › Check Spelling: words added to the dictionary ("Add").
+ pub user_dictionary: Vec<String>,
+ /// Window › Workspace › New Workspace…: saved layouts by name (JSON owned by the shell).
+ pub workspaces: BTreeMap<String, Value>,
+ /// Window › Workspace › Lock Workspace: panels can't be moved.
+ pub workspace_locked: bool,
+ /// File › Scripts › Script Events Manager: event → script bindings.
+ pub script_events: crate::automate_cmds::ScriptEvents,
}
/// Preferences dialog sections in Photoshop's order: (id, title).
@@ -993,6 +1001,7 @@ impl Session {
if let Value::Object(m) = &mut v {
m.insert("colorSettings".into(), serde_json::to_value(&self.color.settings).unwrap_or(Value::Null));
m.insert("version".into(), json!(1));
+ m.insert("presets".into(), self.presets.to_json(self));
}
serde_json::to_string_pretty(&v).unwrap_or_default()
}
@@ -1002,11 +1011,15 @@ impl Session {
pub fn load_prefs_json(&mut self, s: &str) -> std::result::Result<(), String> {
let mut v: Value = serde_json::from_str(s).map_err(|e| format!("preferences: {e}"))?;
let color = v.as_object_mut().and_then(|m| m.remove("colorSettings"));
+ let presets = v.as_object_mut().and_then(|m| m.remove("presets"));
let prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?;
if let Some(c) = color {
self.color.settings = serde_json::from_value(c).unwrap_or_default();
}
self.prefs.edit(|p| *p = prefs);
+ if let Some(v) = presets {
+ self.load_presets_json(v);
+ }
self.apply_prefs();
Ok(())
}
diff --git a/crates/engine/src/presets/clone_source.rs b/crates/engine/src/presets/clone_source.rs
new file mode 100644
index 000000000..69cc3eaae
--- /dev/null
+++ b/crates/engine/src/presets/clone_source.rs
@@ -0,0 +1,351 @@
+//! Window › Clone Source: five clone source slots for Clone Stamp and Healing Brush, each with
+//! a sample point, an offset, W/H scale, rotation and flips, plus the overlay options.
+//!
+//! `paint.cloneStamp` / `paint.healingBrush` read the active slot when the call names no
+//! `source`/`offset`, and always take its transform unless the call gives its own
+//! (`scale`, `rotation`, `flipH`, `flipV`). The transform maps the destination around the
+//! anchor (where the stroke started after the source was set) onto the source around the
+//! sample point: a 200 % width paints the source twice as wide, a 30° rotation paints it turned
+//! 30° counter-clockwise on screen (Photoshop's sense).
+
+use photocraft_geom::Rect;
+use photocraft_paint::retouch::Region;
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{always, bad};
+use crate::commands::CommandSpec;
+use crate::{Result, Session};
+
+pub const SLOTS: usize = 5;
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CloneSource {
+ /// Sample point (document px) set by ⌥-click.
+ pub source: Option<[f64; 2]>,
+ /// Destination point paired with `source` (first aligned stroke after setting it).
+ pub anchor: Option<[f64; 2]>,
+ /// Layer the source was set on (informational, like the panel's document/layer line).
+ pub layer: Option<u64>,
+ /// W and H in percent.
+ pub scale: [f64; 2],
+ /// Degrees, counter-clockwise.
+ pub rotation: f64,
+ pub flip_h: bool,
+ pub flip_v: bool,
+}
+
+impl Default for CloneSource {
+ fn default() -> Self {
+ CloneSource { source: None, anchor: None, layer: None, scale: [100.0, 100.0], rotation: 0.0, flip_h: false, flip_v: false }
+ }
+}
+
+impl CloneSource {
+ pub fn is_identity(&self) -> bool {
+ (self.scale[0] - 100.0).abs() < 1e-9 && (self.scale[1] - 100.0).abs() < 1e-9 && self.rotation.rem_euclid(360.0).abs() < 1e-9 && !self.flip_h && !self.flip_v
+ }
+ /// The panel's Offset X/Y: source − anchor (once a stroke paired them).
+ pub fn offset(&self) -> Option<[f64; 2]> {
+ Some([self.source?[0] - self.anchor?[0], self.source?[1] - self.anchor?[1]])
+ }
+ fn to_json(&self, i: usize) -> Value {
+ json!({
+ "index": i, "source": self.source, "anchor": self.anchor, "offset": self.offset(), "layer": self.layer,
+ "width": self.scale[0], "height": self.scale[1], "rotation": self.rotation, "flipH": self.flip_h, "flipV": self.flip_v,
+ })
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CloneOverlay {
+ pub show: bool,
+ /// Percent.
+ pub opacity: f32,
+ /// Clipped to the brush.
+ pub clipped: bool,
+ pub auto_hide: bool,
+ pub invert: bool,
+ /// normal | darken | lighten | difference
+ pub blend: String,
+}
+
+impl Default for CloneOverlay {
+ fn default() -> Self {
+ CloneOverlay { show: true, opacity: 100.0, clipped: true, auto_hide: true, invert: false, blend: "normal".into() }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct CloneSources {
+ pub slots: [CloneSource; SLOTS],
+ pub active: usize,
+ pub overlay: CloneOverlay,
+}
+
+impl CloneSources {
+ pub fn active(&self) -> &CloneSource {
+ &self.slots[self.active.min(SLOTS - 1)]
+ }
+ pub fn active_mut(&mut self) -> &mut CloneSource {
+ &mut self.slots[self.active.min(SLOTS - 1)]
+ }
+}
+
+/// How a clone stroke samples: destination `d` reads the source at
+/// `source + m · (d − anchor)` (`m` row-major 2 × 2).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Mapping {
+ pub source: (f64, f64),
+ pub anchor: (f64, f64),
+ pub m: [f64; 4],
+}
+
+impl Mapping {
+ pub fn is_translation(&self) -> bool {
+ (self.m[0] - 1.0).abs() < 1e-12 && self.m[1].abs() < 1e-12 && self.m[2].abs() < 1e-12 && (self.m[3] - 1.0).abs() < 1e-12
+ }
+ /// Integer translation (identity transform).
+ pub fn offset(&self) -> (i32, i32) {
+ ((self.source.0 - self.anchor.0).round() as i32, (self.source.1 - self.anchor.1).round() as i32)
+ }
+ pub fn map(&self, x: f64, y: f64) -> (f64, f64) {
+ let (dx, dy) = (x - self.anchor.0, y - self.anchor.1);
+ (self.source.0 + self.m[0] * dx + self.m[1] * dy, self.source.1 + self.m[2] * dx + self.m[3] * dy)
+ }
+ /// Source pixels needed to resample `dst` (with a one-pixel apron for bilinear).
+ pub fn source_rect(&self, dst: Rect) -> Rect {
+ let pts = [(dst.x0, dst.y0), (dst.x1, dst.y0), (dst.x0, dst.y1), (dst.x1, dst.y1)].map(|(x, y)| self.map(x as f64, y as f64));
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for (x, y) in pts {
+ (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
+ }
+ Rect::new(x0.floor() as i32 - 2, y0.floor() as i32 - 2, x1.ceil() as i32 + 2, y1.ceil() as i32 + 2)
+ }
+}
+
+/// Matrix taking destination offsets to source offsets for a slot's W/H, rotation and flips.
+pub fn transform_matrix(scale: [f64; 2], rotation_deg: f64, flip_h: bool, flip_v: bool) -> [f64; 4] {
+ let sx = (scale[0] / 100.0).max(1e-3) * if flip_h { -1.0 } else { 1.0 };
+ let sy = (scale[1] / 100.0).max(1e-3) * if flip_v { -1.0 } else { 1.0 };
+ // Forward (source → destination): rotate after scaling. Rotation is counter-clockwise on
+ // screen, which is clockwise in y-down maths.
+ let (s, c) = (-rotation_deg.to_radians()).sin_cos();
+ let f = [c * sx, -s * sy, s * sx, c * sy];
+ let det = f[0] * f[3] - f[1] * f[2];
+ [f[3] / det, -f[1] / det, -f[2] / det, f[0] / det]
+}
+
+fn pt(p: &Value, k: &str) -> Option<(f64, f64)> {
+ let a = p.get(k)?.as_array()?;
+ Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))
+}
+
+/// Resolve a clone stroke's mapping from its params and the active slot. `first` is the
+/// stroke's first point. With `"aligned"` strokes the slot remembers the anchor so later
+/// strokes keep sampling relative to the original pairing.
+pub fn mapping(s: &mut Session, p: &Value, first: (f64, f64), cmd: &str) -> Result<Mapping> {
+ let aligned = p.get("aligned").and_then(Value::as_bool).unwrap_or(true);
+ let slot = s.presets.clone.active().clone();
+ let explicit_tf = ["scale", "rotation", "flipH", "flipV"].iter().any(|k| p.get(*k).is_some());
+ let m = if explicit_tf {
+ let sc = p.get("scale").and_then(Value::as_array).map_or([100.0, 100.0], |a| [a.first().and_then(Value::as_f64).unwrap_or(100.0), a.get(1).and_then(Value::as_f64).unwrap_or(100.0)]);
+ let flag = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false);
+ transform_matrix(sc, p.get("rotation").and_then(Value::as_f64).unwrap_or(0.0), flag("flipH"), flag("flipV"))
+ } else {
+ transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v)
+ };
+ let anchor_param = pt(p, "anchor");
+ if let Some(off) = pt(p, "offset") {
+ let a = anchor_param.unwrap_or(first);
+ return Ok(Mapping { source: (a.0 + off.0, a.1 + off.1), anchor: a, m });
+ }
+ if let Some(src) = pt(p, "source") {
+ return Ok(Mapping { source: src, anchor: anchor_param.unwrap_or(first), m });
+ }
+ let Some(src) = slot.source else { return Err(bad(cmd, "missing `source` ([x,y]) or `offset` ([dx,dy]); or set one with cloneSource.set")) };
+ let src = (src[0], src[1]);
+ let anchor = match (aligned, slot.anchor) {
+ (true, Some(a)) => (a[0], a[1]),
+ _ => first,
+ };
+ if aligned {
+ s.presets.clone.active_mut().anchor = Some([anchor.0, anchor.1]);
+ }
+ Ok(Mapping { source: src, anchor, m })
+}
+
+/// Bilinear resample of `src` (covering [`Mapping::source_rect`]) onto `dst`, interpolating
+/// premultiplied by the alpha channel `alpha` when there is one. Outside `src` is transparent.
+pub fn resample(src: &Region, dst: Rect, map: &Mapping, alpha: Option<usize>) -> Region {
+ let n = src.ch;
+ let mut out = Region::new(dst, n);
+ let w = dst.width() as usize;
+ let fetch = |x: i32, y: i32, buf: &mut [f32]| {
+ if x < src.rect.x0 || y < src.rect.y0 || x >= src.rect.x1 || y >= src.rect.y1 {
+ buf.fill(0.0);
+ return;
+ }
+ buf.copy_from_slice(src.px(x, y));
+ if let Some(a) = alpha {
+ let av = buf[a];
+ for (c, v) in buf.iter_mut().enumerate() {
+ if c != a {
+ *v *= av;
+ }
+ }
+ }
+ };
+ let mut q = [vec![0.0f32; n], vec![0.0f32; n], vec![0.0f32; n], vec![0.0f32; n]];
+ for (i, px) in out.data.chunks_exact_mut(n).enumerate() {
+ let (x, y) = (dst.x0 + (i % w) as i32, dst.y0 + (i / w) as i32);
+ let (sx, sy) = map.map(x as f64 + 0.5, y as f64 + 0.5);
+ let (fx, fy) = (sx - 0.5, sy - 0.5);
+ let (x0, y0) = (fx.floor() as i32, fy.floor() as i32);
+ let (tx, ty) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32);
+ fetch(x0, y0, &mut q[0]);
+ fetch(x0 + 1, y0, &mut q[1]);
+ fetch(x0, y0 + 1, &mut q[2]);
+ fetch(x0 + 1, y0 + 1, &mut q[3]);
+ for c in 0..n {
+ let top = q[0][c] + (q[1][c] - q[0][c]) * tx;
+ let bot = q[2][c] + (q[3][c] - q[2][c]) * tx;
+ px[c] = top + (bot - top) * ty;
+ }
+ if let Some(a) = alpha {
+ let av = px[a];
+ for (c, v) in px.iter_mut().enumerate() {
+ if c != a {
+ *v = if av > 1e-6 { *v / av } else { 0.0 };
+ }
+ }
+ }
+ }
+ out
+}
+
+// ------------------------------------------------------------------ commands
+
+fn index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
+ match p.get("index").and_then(Value::as_u64) {
+ Some(i) if (i as usize) < SLOTS => Ok(i as usize),
+ Some(i) => Err(bad(cmd, format!("index {i} out of range (0..{SLOTS})"))),
+ None => Ok(s.presets.clone.active),
+ }
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let c = &s.presets.clone;
+ Ok(json!({"active": c.active, "sources": c.slots.iter().enumerate().map(|(i, x)| x.to_json(i)).collect::<Vec<_>>(), "overlay": serde_json::to_value(&c.overlay).unwrap_or(Value::Null)}))
+}
+
+fn select(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "cloneSource.select";
+ let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad(CMD, "missing `index`"))? as usize;
+ if i >= SLOTS {
+ return Err(bad(CMD, format!("index {i} out of range (0..{SLOTS})")));
+ }
+ s.presets.clone.active = i;
+ Ok(s.presets.clone.active().to_json(i))
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "cloneSource.set";
+ let i = index(s, p, CMD)?;
+ let active_layer = s.active().and_then(|d| d.active_layer).map(|l| l.0);
+ let slot = &mut s.presets.clone.slots[i];
+ if let Some((x, y)) = pt(p, "source") {
+ // A new sample point re-pairs with the next stroke.
+ slot.source = Some([x, y]);
+ slot.anchor = None;
+ slot.layer = p.get("layer").and_then(Value::as_u64).or(active_layer);
+ }
+ if let Some((dx, dy)) = pt(p, "offset") {
+ // Offset X/Y fields: keep the anchor (or the source as anchor) and move the source.
+ let a = slot.anchor.or(slot.source).ok_or_else(|| bad(CMD, "set a `source` before an offset"))?;
+ slot.anchor = Some(a);
+ slot.source = Some([a[0] + dx, a[1] + dy]);
+ }
+ if let Some(a) = p.get("scale").and_then(Value::as_array) {
+ slot.scale = [a.first().and_then(Value::as_f64).unwrap_or(100.0), a.get(1).and_then(Value::as_f64).unwrap_or(100.0)];
+ }
+ let num = |k: &str| p.get(k).and_then(Value::as_f64);
+ if let Some(w) = num("width") {
+ slot.scale[0] = w;
+ }
+ if let Some(h) = num("height") {
+ slot.scale[1] = h;
+ }
+ if slot.scale.iter().any(|v| !(1.0..=1000.0).contains(&v.abs())) {
+ slot.scale = slot.scale.map(|v| v.clamp(1.0, 1000.0));
+ }
+ if let Some(r) = num("rotation") {
+ slot.rotation = (r + 180.0).rem_euclid(360.0) - 180.0;
+ }
+ if let Some(b) = p.get("flipH").and_then(Value::as_bool) {
+ slot.flip_h = b;
+ }
+ if let Some(b) = p.get("flipV").and_then(Value::as_bool) {
+ slot.flip_v = b;
+ }
+ if p.get("clear").and_then(Value::as_bool) == Some(true) {
+ *slot = CloneSource::default();
+ }
+ if p.get("select").and_then(Value::as_bool).unwrap_or(true) {
+ s.presets.clone.active = i;
+ }
+ Ok(s.presets.clone.slots[i].to_json(i))
+}
+
+fn reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = index(s, p, "cloneSource.resetTransform")?;
+ let slot = &mut s.presets.clone.slots[i];
+ (slot.scale, slot.rotation, slot.flip_h, slot.flip_v) = ([100.0, 100.0], 0.0, false, false);
+ Ok(slot.to_json(i))
+}
+
+fn overlay(s: &mut Session, p: &Value) -> Result<Value> {
+ let o = &mut s.presets.clone.overlay;
+ let flag = |k: &str| p.get(k).and_then(Value::as_bool);
+ if let Some(b) = flag("show") {
+ o.show = b;
+ }
+ if let Some(v) = p.get("opacity").and_then(Value::as_f64) {
+ o.opacity = (v as f32).clamp(0.0, 100.0);
+ }
+ if let Some(b) = flag("clipped") {
+ o.clipped = b;
+ }
+ if let Some(b) = flag("autoHide") {
+ o.auto_hide = b;
+ }
+ if let Some(b) = flag("invert") {
+ o.invert = b;
+ }
+ if let Some(m) = p.get("blend").and_then(Value::as_str) {
+ if !matches!(m, "normal" | "darken" | "lighten" | "difference") {
+ return Err(bad("cloneSource.overlay", format!("unknown overlay mode `{m}` (normal|darken|lighten|difference)")));
+ }
+ o.blend = m.into();
+ }
+ Ok(serde_json::to_value(&*o).unwrap_or(Value::Null))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: "cloneSource.list", label: "Clone Sources", menu: &[], shortcut: None, params: "{} → {active,sources:[{index,source,anchor,offset,layer,width,height,rotation,flipH,flipV}],overlay}", enabled: always, run: list, journal: false },
+ CommandSpec { id: "cloneSource.select", label: "Select Clone Source", menu: &[], shortcut: None, params: r##"{"index":0..4}"##, enabled: always, run: select, journal: true },
+ CommandSpec {
+ id: "cloneSource.set",
+ label: "Set Clone Source",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"index":0..4?=active,"source":[x,y]? (⌥-click; re-pairs with the next stroke),"offset":[dx,dy]?,"width":%?,"height":%?|"scale":[w%,h%]?,"rotation":deg?,"flipH":bool?,"flipV":bool?,"layer":id?,"clear":bool?,"select":bool=true}"##,
+ enabled: always,
+ run: set,
+ journal: true,
+ },
+ CommandSpec { id: "cloneSource.resetTransform", label: "Reset Transform", menu: &[], shortcut: None, params: r##"{"index":0..4?=active}"##, enabled: always, run: reset_transform, journal: true },
+ CommandSpec { id: "cloneSource.overlay", label: "Clone Source Overlay", menu: &[], shortcut: None, params: r##"{"show":bool?,"opacity":0..100?,"clipped":bool?,"autoHide":bool?,"invert":bool?,"blend":"normal|darken|lighten|difference"?}"##, enabled: always, run: overlay, journal: true },
+ ]
+}
diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs
new file mode 100644
index 000000000..62553456a
--- /dev/null
+++ b/crates/engine/src/presets/gradients.rs
@@ -0,0 +1,346 @@
+//! Window › Gradients: gradient presets in groups, the Gradient tool's current gradient and
+//! Gradient Fill layers made from presets.
+//!
+//! A preset has colour stops (a fixed colour, or the live foreground/background colour, as in
+//! Photoshop's "Foreground to Background") and transparency stops, both at `0..=1`. Midpoints are
+//! always 50 %. Built-in colours are our own.
+
+use photocraft_doc::{Color, Fill, Layer, LayerContent};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{Group, Named, always, bad, edit_groups, find, group_index, req_str, str_param, unique_name};
+use crate::commands::CommandSpec;
+use crate::{Result, Session};
+
+/// A stop colour: fixed, or the current foreground/background colour.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum StopColor {
+ Foreground,
+ Background,
+ Rgb([f32; 3]),
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct GradientPreset {
+ pub name: String,
+ /// Colour stops `(location 0..1, colour)`, sorted by location.
+ pub stops: Vec<(f32, StopColor)>,
+ /// Transparency stops `(location, opacity 0..1)`; empty = opaque.
+ #[serde(default)]
+ pub opacity: Vec<(f32, f32)>,
+}
+
+impl Named for GradientPreset {
+ fn name(&self) -> &str {
+ &self.name
+ }
+ fn set_name(&mut self, n: String) {
+ self.name = n;
+ }
+}
+
+fn hex(s: &str) -> [f32; 3] {
+ let s = s.trim_start_matches('#');
+ let b = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).map_or(0.0, |v| v as f32 / 255.0);
+ [b(0), b(2), b(4)]
+}
+
+fn hex_of(c: [f32; 3]) -> String {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ format!("#{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2]))
+}
+
+fn lerp4(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] {
+ std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t)
+}
+
+/// Piecewise-linear value of sorted `(t, v)` stops at `t` (clamped at the ends).
+fn sample<V: Copy>(stops: &[(f32, V)], t: f32, mix: impl Fn(V, V, f32) -> V) -> Option<V> {
+ let first = stops.first()?;
+ if t <= first.0 {
+ return Some(first.1);
+ }
+ for w in stops.windows(2) {
+ let ((t0, a), (t1, b)) = (w[0], w[1]);
+ if t <= t1 {
+ let u = if t1 > t0 { (t - t0) / (t1 - t0) } else { 1.0 };
+ return Some(mix(a, b, u));
+ }
+ }
+ stops.last().map(|s| s.1)
+}
+
+impl GradientPreset {
+ pub fn new(name: &str, colors: &[&str]) -> Self {
+ let n = colors.len().max(2) - 1;
+ GradientPreset { name: name.into(), stops: colors.iter().enumerate().map(|(i, c)| (i as f32 / n as f32, StopColor::Rgb(hex(c)))).collect(), opacity: Vec::new() }
+ }
+ pub fn foreground_to_background() -> Self {
+ GradientPreset { name: "Foreground to Background".into(), stops: vec![(0.0, StopColor::Foreground), (1.0, StopColor::Background)], opacity: Vec::new() }
+ }
+
+ /// RGBA stops for painting: colour and transparency stops merged. Where both vary, extra
+ /// samples keep the product close to Photoshop's per-pixel interpolation.
+ pub fn resolve(&self, fg: [f32; 4], bg: [f32; 4]) -> Vec<(f32, [f32; 4])> {
+ let rgb = |c: StopColor| match c {
+ StopColor::Foreground => [fg[0], fg[1], fg[2], 1.0],
+ StopColor::Background => [bg[0], bg[1], bg[2], 1.0],
+ StopColor::Rgb(c) => [c[0], c[1], c[2], 1.0],
+ };
+ let mut cs: Vec<(f32, [f32; 4])> = self.stops.iter().map(|(t, c)| (t.clamp(0.0, 1.0), rgb(*c))).collect();
+ cs.sort_by(|a, b| a.0.total_cmp(&b.0));
+ if cs.is_empty() {
+ cs = vec![(0.0, [fg[0], fg[1], fg[2], 1.0]), (1.0, [bg[0], bg[1], bg[2], 1.0])];
+ }
+ let mut os: Vec<(f32, f32)> = self.opacity.iter().map(|(t, a)| (t.clamp(0.0, 1.0), a.clamp(0.0, 1.0))).collect();
+ os.sort_by(|a, b| a.0.total_cmp(&b.0));
+ if os.is_empty() || os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) {
+ return cs;
+ }
+ let mut ts: Vec<f32> = cs.iter().map(|s| s.0).chain(os.iter().map(|s| s.0)).chain([0.0, 1.0]).collect();
+ ts.sort_by(f32::total_cmp);
+ ts.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
+ let mut all = Vec::new();
+ for w in ts.windows(2) {
+ for k in 0..4 {
+ all.push(w[0] + (w[1] - w[0]) * k as f32 / 4.0);
+ }
+ }
+ all.push(1.0);
+ all.into_iter()
+ .map(|t| {
+ let mut c = sample(&cs, t, lerp4).unwrap_or([0.0; 4]);
+ c[3] = sample(&os, t, |a, b, u| a + (b - a) * u).unwrap_or(1.0);
+ (t, c)
+ })
+ .collect()
+ }
+
+ /// Stops for a Gradient Fill layer / overlay (live colours resolved now, like Photoshop).
+ pub fn doc_stops(&self, fg: [f32; 4], bg: [f32; 4]) -> Vec<(f32, Color)> {
+ self.resolve(fg, bg).into_iter().map(|(t, c)| (t, Color::rgba(c[0], c[1], c[2], c[3]))).collect()
+ }
+
+ pub fn to_json(&self) -> Value {
+ let stops: Vec<Value> = self
+ .stops
+ .iter()
+ .map(|(t, c)| match c {
+ StopColor::Foreground => json!([t, "foreground"]),
+ StopColor::Background => json!([t, "background"]),
+ StopColor::Rgb(c) => json!([t, hex_of(*c)]),
+ })
+ .collect();
+ let opacity: Vec<Value> = self.opacity.iter().map(|(t, a)| json!([t, (a * 100.0).round()])).collect();
+ json!({"name": self.name, "stops": stops, "transparency": opacity})
+ }
+
+ /// Parse `{"stops":[[t,"#hex"|"foreground"|"background"],…],"transparency":[[t,0..100],…]}`.
+ pub fn from_params(name: &str, p: &Value, cmd: &str) -> Result<Self> {
+ let arr = p.get("stops").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing `stops`"))?;
+ let mut stops = Vec::new();
+ for (i, s) in arr.iter().enumerate() {
+ let (t, c) = match s {
+ Value::Array(a) if a.len() == 2 => (a[0].as_f64().map(|v| v as f32), a[1].as_str()),
+ Value::String(c) => (Some(if arr.len() > 1 { i as f32 / (arr.len() - 1) as f32 } else { 0.0 }), Some(c.as_str())),
+ _ => (None, None),
+ };
+ let (Some(t), Some(c)) = (t, c) else { return Err(bad(cmd, "stops are [location, \"#rrggbb\"|\"foreground\"|\"background\"]")) };
+ let c = match c {
+ "foreground" => StopColor::Foreground,
+ "background" => StopColor::Background,
+ h if h.trim_start_matches('#').len() == 6 && h.trim_start_matches('#').chars().all(|c| c.is_ascii_hexdigit()) => StopColor::Rgb(hex(h)),
+ o => return Err(bad(cmd, format!("bad stop colour `{o}`"))),
+ };
+ stops.push((t.clamp(0.0, 1.0), c));
+ }
+ if stops.len() < 2 {
+ return Err(bad(cmd, "a gradient needs at least 2 colour stops"));
+ }
+ stops.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let mut opacity: Vec<(f32, f32)> = p
+ .get("transparency")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(|o| Some((o.get(0)?.as_f64()? as f32, (o.get(1)?.as_f64()? as f32 / 100.0).clamp(0.0, 1.0)))).collect())
+ .unwrap_or_default();
+ opacity.sort_by(|a, b| a.0.total_cmp(&b.0));
+ Ok(GradientPreset { name: name.into(), stops, opacity })
+ }
+}
+
+/// Built-in groups, laid out like Photoshop's default Gradients panel (Basics, then folders by
+/// hue). The colours are our own.
+pub fn builtin() -> Vec<Group<GradientPreset>> {
+ let fam = |prefix: &str, sets: &[&[&str]]| -> Vec<GradientPreset> { sets.iter().enumerate().map(|(i, c)| GradientPreset::new(&format!("{prefix} {:02}", i + 1), c)).collect() };
+ let fg_transparent = GradientPreset { name: "Foreground to Transparent".into(), stops: vec![(0.0, StopColor::Foreground), (1.0, StopColor::Foreground)], opacity: vec![(0.0, 1.0), (1.0, 0.0)] };
+ vec![
+ Group::new("Basics", vec![GradientPreset::foreground_to_background(), fg_transparent, GradientPreset::new("Black, White", &["#000000", "#ffffff"])]),
+ Group::new("Blues", fam("Blue", &[&["#0b3d91", "#4fa3e0"], &["#1c2a5a", "#3f6fd8", "#a8d4ff"], &["#00b4d8", "#03045e"], &["#5ec8f2", "#e6f6ff"], &["#253b80", "#20b2aa"], &["#89c2ff", "#1d4ed8", "#0a1a40"]])),
+ Group::new("Purples", fam("Purple", &[&["#3c096c", "#c77dff"], &["#5a189a", "#e0aaff"], &["#240046", "#7b2cbf", "#f3d9ff"], &["#9d4edd", "#4361ee"], &["#6a0572", "#ab83a1"], &["#2d0b59", "#ff6fd8"]])),
+ Group::new("Pinks", fam("Pink", &[&["#ff4d8d", "#ffd1e1"], &["#c9184a", "#ff8fab"], &["#ff70a6", "#ffd670"], &["#8e2c5a", "#f7a1c4", "#fff0f5"], &["#ff5fa2", "#a855f7"], &["#ffc2d6", "#ff2e63"]])),
+ Group::new("Reds", fam("Red", &[&["#7f0000", "#ff3b30"], &["#d00000", "#ffba08"], &["#370617", "#9d0208", "#f48c06"], &["#e5383b", "#f5f3f4"], &["#a4161a", "#0b090a"], &["#ff595e", "#ffca3a"]])),
+ Group::new("Oranges", fam("Orange", &[&["#ff6d00", "#ffd60a"], &["#e85d04", "#ffba08"], &["#9c3d0b", "#ff9e40", "#fff1d6"], &["#ff7b00", "#ff0054"], &["#fb8500", "#023047"], &["#ffb703", "#fb5607"]])),
+ Group::new("Greens", fam("Green", &[&["#004b23", "#70e000"], &["#2d6a4f", "#b7e4c7"], &["#1b4332", "#40916c", "#d8f3dc"], &["#38b000", "#ccff33"], &["#0b6e4f", "#08a0a8"], &["#606c38", "#dda15e"]])),
+ Group::new("Browns", fam("Brown", &[&["#3e2412", "#a47148"], &["#6f4518", "#e6ccb2"], &["#2b1708", "#7f5539", "#ddb892"], &["#8b5e34", "#ffd8a8"], &["#582f0e", "#b6ad90"], &["#4a3728", "#c08552", "#f3e9dc"]])),
+ Group::new("Grays", fam("Gray", &[&["#212529", "#f8f9fa"], &["#495057", "#dee2e6"], &["#000000", "#6c757d", "#ffffff"], &["#343a40", "#adb5bd", "#343a40"], &["#8d99ae", "#2b2d42"], &["#e9ecef", "#ced4da", "#868e96"]])),
+ ]
+}
+
+// ------------------------------------------------------------------ commands
+
+/// RGBA stops `(location, colour)` ready to paint.
+pub type Stops = Vec<(f32, [f32; 4])>;
+
+const CMD_SELECT: &str = "gradient.presets.select";
+
+/// Gradient for the Gradient tool: `"gradient": preset name`, else explicit `"stops"`, else the
+/// current gradient (Gradients panel selection). `None` when the caller gave `colors` (the
+/// legacy evenly spaced form `paint.gradient` handles itself).
+pub fn tool_stops(s: &Session, p: &Value) -> Result<Option<Stops>> {
+ let (fg, bg) = (s.tools.foreground, s.tools.background);
+ if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) {
+ return Ok(None);
+ }
+ if let Some(name) = str_param(p, "gradient") {
+ let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad("paint.gradient", format!("no gradient preset \"{name}\"")))?;
+ return Ok(Some(s.presets.gradients[gi].items[ii].resolve(fg, bg)));
+ }
+ if p.get("stops").is_some() {
+ return Ok(Some(GradientPreset::from_params("Custom", p, "paint.gradient")?.resolve(fg, bg)));
+ }
+ Ok(Some(s.presets.gradient.resolve(fg, bg)))
+}
+
+/// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`.
+fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<GradientPreset> {
+ if let Some(name) = str_param(p, "preset") {
+ let (gi, ii) = find(&s.presets.gradients, name, str_param(p, "group")).ok_or_else(|| bad(cmd, format!("no gradient preset \"{name}\" (see gradient.presets.list)")))?;
+ return Ok(s.presets.gradients[gi].items[ii].clone());
+ }
+ if p.get("stops").is_some() {
+ return GradientPreset::from_params(str_param(p, "name").unwrap_or("Custom"), p, cmd);
+ }
+ Ok(s.presets.gradient.clone())
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let groups: Vec<Value> = s.presets.gradients.iter().map(|g| json!({"name": g.name, "presets": g.items.iter().map(GradientPreset::to_json).collect::<Vec<_>>()})).collect();
+ Ok(json!({"groups": groups, "current": s.presets.gradient.to_json()}))
+}
+
+fn active_gradient_fill(s: &Session) -> Option<photocraft_doc::LayerId> {
+ let d = s.active()?;
+ let id = d.active_layer?;
+ matches!(d.doc.layer(id)?.content, LayerContent::Fill(Fill::Gradient { .. })).then_some(id)
+}
+
+fn select(s: &mut Session, p: &Value) -> Result<Value> {
+ let g = preset_param(s, p, CMD_SELECT)?;
+ s.presets.gradient = g.clone();
+ s.presets_changed();
+ let mut out = json!({"current": g.to_json()});
+ // Clicking a preset with a Gradient Fill layer selected changes that layer (Photoshop).
+ if p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true)
+ && let Some(id) = active_gradient_fill(s)
+ {
+ let stops_new = g.doc_stops(s.tools.foreground, s.tools.background);
+ s.edit("Change Gradient Fill", |doc, _| {
+ if let Some(l) = doc.layer_mut(id)
+ && let LayerContent::Fill(Fill::Gradient { stops, .. }) = &mut l.content
+ {
+ *stops = stops_new;
+ }
+ Ok(())
+ })?;
+ out["layer"] = json!(id.0);
+ }
+ Ok(out)
+}
+
+fn apply(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "gradient.presets.apply";
+ let g = preset_param(s, p, CMD)?;
+ let stops = g.doc_stops(s.tools.foreground, s.tools.background);
+ let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(90.0) as f32;
+ let scale = (p.get("scale").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0).clamp(0.1, 1.5);
+ let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
+ let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
+ let id = s.edit("New Gradient Fill Layer", |doc, active| {
+ let fill = Fill::Gradient { stops, angle, scale, style, reverse };
+ let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)));
+ *active = Some(id);
+ Ok(id)
+ })?;
+ Ok(json!({"layer": id.0, "preset": g.name}))
+}
+
+fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "gradient.presets.new";
+ let mut g = if p.get("stops").is_some() { GradientPreset::from_params("", p, CMD)? } else { s.presets.gradient.clone() };
+ g.name = unique_name(&s.presets.gradients, str_param(p, "name").unwrap_or("Custom"));
+ let gi = group_index(&mut s.presets.gradients, str_param(p, "group"));
+ s.presets.gradients[gi].items.push(g.clone());
+ let group = s.presets.gradients[gi].name.clone();
+ s.presets_changed();
+ Ok(json!({"name": g.name, "group": group}))
+}
+
+fn edit(s: &mut Session, p: &Value) -> Result<Value> {
+ let action = req_str(p, "action", "gradient.presets.edit")?.to_string();
+ let r = edit_groups(&mut s.presets.gradients, &action, p, "gradient.presets.edit")?;
+ s.presets_changed();
+ Ok(r)
+}
+
+fn reset(s: &mut Session, p: &Value) -> Result<Value> {
+ let append = p.get("append").and_then(Value::as_bool).unwrap_or(false);
+ let mut b = builtin();
+ if append {
+ for g in &mut b {
+ g.name = unique_group(&s.presets.gradients, &g.name);
+ }
+ s.presets.gradients.extend(b);
+ } else {
+ s.presets.gradients = b;
+ }
+ s.presets_changed();
+ Ok(json!({"groups": s.presets.gradients.len()}))
+}
+
+pub(crate) fn unique_group<T>(groups: &[Group<T>], base: &str) -> String {
+ let taken = |n: &str| groups.iter().any(|g| g.name == n);
+ if !taken(base) { base.to_string() } else { (1..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default() }
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ let stops = r##""stops":[[t 0..1,"#rrggbb"|"foreground"|"background"],…],"transparency":[[t,opacity 0..100],…]?"##;
+ let leak = |s: String| -> &'static str { Box::leak(s.into_boxed_str()) };
+ vec![
+ CommandSpec { id: "gradient.presets.list", label: "Gradient Presets", menu: &[], shortcut: None, params: "{} → {groups:[{name,presets:[{name,stops,transparency}]}],current}", enabled: always, run: list, journal: false },
+ CommandSpec {
+ id: CMD_SELECT,
+ label: "Select Gradient",
+ menu: &[],
+ shortcut: None,
+ params: leak(format!(r##"{{"preset":name|{stops},"group":name?,"applyToLayer":bool=true (also recolours a selected Gradient Fill layer)}} → {{current,layer?}}. The Gradient tool paints with it."##)),
+ enabled: always,
+ run: select,
+ journal: true,
+ },
+ CommandSpec {
+ id: "gradient.presets.apply",
+ label: "New Gradient Fill Layer from Preset",
+ menu: &[],
+ shortcut: None,
+ params: leak(format!(r##"{{"preset":name?=current|{stops},"angle":deg=90,"style":"linear|radial|angle|reflected|diamond"="linear","scale":10..150=100,"reverse":bool}} → {{layer}}"##)),
+ enabled: super::has_doc,
+ run: apply,
+ journal: true,
+ },
+ CommandSpec { id: "gradient.presets.new", label: "New Gradient Preset", menu: &[], shortcut: None, params: leak(format!(r##"{{"name":str="Custom","group":name?=first,{stops} (default: the current gradient)}}"##)), enabled: always, run: new_preset, journal: true },
+ CommandSpec { id: "gradient.presets.edit", label: "Edit Gradient Presets", menu: &[], shortcut: None, params: super::GROUP_EDIT_PARAMS, enabled: always, run: edit, journal: true },
+ CommandSpec { id: "gradient.presets.reset", label: "Restore Default Gradients", menu: &[], shortcut: None, params: r##"{"append":bool=false}"##, enabled: always, run: reset, journal: true },
+ ]
+}
diff --git a/crates/engine/src/presets/mod.rs b/crates/engine/src/presets/mod.rs
new file mode 100644
index 000000000..90e2849ef
--- /dev/null
+++ b/crates/engine/src/presets/mod.rs
@@ -0,0 +1,310 @@
+//! Preset panels: Window › Gradients, Patterns, Styles, Shapes, Tool Presets and Clone Source.
+//!
+//! Photoshop keeps presets in named groups (folders) that the panels show as thumbnail grids or
+//! lists. The engine owns that data so every frontend (GUI, CLI, MCP) sees and edits the same
+//! sets through `<kind>.presets.*` commands:
+//!
+//! - gradients ([`gradients`]): colour + transparency stops; the selected one drives the
+//! Gradient tool (`paint.gradient` without `colors`) and Gradient Fill layers;
+//! - patterns ([`patterns`]): groups over the existing pattern library (`pattern.*`);
+//! - styles ([`styles`]): layer effects (plus optional blending) applied to the selected layers;
+//! - shapes ([`shapes`]): vector shapes for the Custom Shape tool, placed as shape layers;
+//! - tool presets ([`tools`]): a tool plus its options (opaque JSON the shell fills in);
+//! - clone sources ([`clone_source`]): five source slots with offset, scale, rotation and flip
+//! that `paint.cloneStamp` / `paint.healingBrush` follow.
+//!
+//! The built-in groups are our own (clean-room): colours, styles and shapes were designed here,
+//! not copied from Photoshop's presets. User edits persist with the preferences document: see
+//! [`PresetState::to_json`] (saved under `"presets"` by [`Session::prefs_to_json`]).
+
+pub mod clone_source;
+pub mod gradients;
+pub mod patterns;
+pub mod shapes;
+pub mod styles;
+pub mod tools;
+
+#[cfg(test)]
+mod tests;
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// A named folder of presets.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Group<T> {
+ pub name: String,
+ pub items: Vec<T>,
+}
+
+impl<T> Group<T> {
+ pub fn new(name: &str, items: Vec<T>) -> Self {
+ Group { name: name.into(), items }
+ }
+}
+
+/// Anything with a display name (presets, pattern references).
+pub trait Named {
+ fn name(&self) -> &str;
+ fn set_name(&mut self, n: String);
+}
+
+impl Named for String {
+ fn name(&self) -> &str {
+ self
+ }
+ fn set_name(&mut self, n: String) {
+ *self = n;
+ }
+}
+
+/// All preset sets plus the panel state the engine needs.
+#[derive(Clone, Debug)]
+pub struct PresetState {
+ pub gradients: Vec<Group<gradients::GradientPreset>>,
+ /// The Gradient tool's current gradient (Gradients panel selection / gradient picker).
+ pub gradient: gradients::GradientPreset,
+ pub styles: Vec<Group<styles::StylePreset>>,
+ pub shapes: Vec<Group<shapes::ShapePreset>>,
+ /// Pattern groups: pattern names per folder (patterns themselves live in the library).
+ pub pattern_groups: Vec<Group<String>>,
+ /// The pattern the Patterns panel selected (Fill, Pattern fill layers default to it).
+ pub pattern: Option<String>,
+ pub tool_presets: Vec<tools::ToolPreset>,
+ pub clone: clone_source::CloneSources,
+ /// Bumped on every preset change (UIs key thumbnail caches on it).
+ pub rev: u64,
+}
+
+impl Default for PresetState {
+ fn default() -> Self {
+ PresetState {
+ gradients: gradients::builtin(),
+ gradient: gradients::GradientPreset::foreground_to_background(),
+ styles: styles::builtin(),
+ shapes: shapes::builtin(),
+ pattern_groups: patterns::builtin_groups(),
+ pattern: None,
+ tool_presets: tools::builtin(),
+ clone: Default::default(),
+ rev: 0,
+ }
+ }
+}
+
+/// What persists (user-visible preset sets, not transient panel state).
+#[derive(Serialize, Deserialize)]
+struct Persisted {
+ #[serde(default)]
+ gradients: Option<Vec<Group<gradients::GradientPreset>>>,
+ #[serde(default)]
+ gradient: Option<gradients::GradientPreset>,
+ #[serde(default)]
+ styles: Option<Vec<Group<styles::StylePreset>>>,
+ #[serde(default)]
+ shapes: Option<Vec<Group<shapes::ShapePreset>>>,
+ #[serde(default)]
+ pattern_groups: Option<Vec<Group<String>>>,
+ #[serde(default)]
+ tool_presets: Option<Vec<tools::ToolPreset>>,
+ #[serde(default)]
+ custom_shapes: Option<Vec<crate::edit_menu_cmds::CustomShape>>,
+}
+
+impl PresetState {
+ /// JSON saved with the preferences (`"presets"` key).
+ pub fn to_json(&self, s: &Session) -> Value {
+ let p = Persisted {
+ gradients: Some(self.gradients.clone()),
+ gradient: Some(self.gradient.clone()),
+ styles: Some(self.styles.clone()),
+ shapes: Some(self.shapes.clone()),
+ pattern_groups: Some(self.pattern_groups.clone()),
+ tool_presets: Some(self.tool_presets.clone()),
+ custom_shapes: Some(s.edit_state.custom_shapes.clone()),
+ };
+ serde_json::to_value(p).unwrap_or(Value::Null)
+ }
+}
+
+impl Session {
+ /// Restore presets saved by [`PresetState::to_json`]. Missing sets keep their defaults; a
+ /// malformed blob is ignored (presets are never worth refusing to start over).
+ pub fn load_presets_json(&mut self, v: Value) {
+ let Ok(p) = serde_json::from_value::<Persisted>(v) else { return };
+ let st = &mut self.presets;
+ if let Some(g) = p.gradients {
+ st.gradients = g;
+ }
+ if let Some(g) = p.gradient {
+ st.gradient = g;
+ }
+ if let Some(g) = p.styles {
+ st.styles = g;
+ }
+ if let Some(g) = p.shapes {
+ st.shapes = g;
+ }
+ if let Some(g) = p.pattern_groups {
+ st.pattern_groups = g;
+ }
+ if let Some(t) = p.tool_presets {
+ st.tool_presets = t;
+ }
+ if let Some(c) = p.custom_shapes {
+ self.edit_state.custom_shapes = c;
+ }
+ self.presets.rev += 1;
+ }
+
+ /// Record a preset change: bumps the panel revision and marks the preferences document dirty
+ /// so the shell persists it.
+ pub(crate) fn presets_changed(&mut self) {
+ self.presets.rev += 1;
+ self.prefs.edit(|_| ());
+ }
+}
+
+// ------------------------------------------------------------------ shared helpers
+
+pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+pub(crate) fn always(_: &Session) -> std::result::Result<(), String> {
+ Ok(())
+}
+
+pub(crate) fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+pub(crate) fn has_layer(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into())
+}
+
+pub(crate) fn str_param<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
+ p.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
+}
+
+pub(crate) fn req_str<'a>(p: &'a Value, k: &str, cmd: &str) -> Result<&'a str> {
+ str_param(p, k).ok_or_else(|| bad(cmd, format!("missing `{k}`")))
+}
+
+/// Locate a preset by name (optionally within `group`): (group index, item index).
+pub(crate) fn find<T: Named>(groups: &[Group<T>], name: &str, group: Option<&str>) -> Option<(usize, usize)> {
+ groups.iter().enumerate().filter(|(_, g)| group.is_none_or(|n| g.name == n)).find_map(|(gi, g)| g.items.iter().position(|i| i.name() == name).map(|ii| (gi, ii)))
+}
+
+/// `base`, or `base 2`, `base 3`… so names stay unique across all groups (Photoshop allows
+/// duplicates, but agents address presets by name).
+pub(crate) fn unique_name<T: Named>(groups: &[Group<T>], base: &str) -> String {
+ let taken = |n: &str| groups.iter().any(|g| g.items.iter().any(|i| i.name() == n));
+ if !taken(base) {
+ return base.to_string();
+ }
+ (2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
+}
+
+/// Index of `group` (created at the end when missing), or the first group (created as
+/// "Presets" when there is none).
+pub(crate) fn group_index<T>(groups: &mut Vec<Group<T>>, group: Option<&str>) -> usize {
+ match group {
+ Some(n) => groups.iter().position(|g| g.name == n).unwrap_or_else(|| {
+ groups.push(Group::new(n, Vec::new()));
+ groups.len() - 1
+ }),
+ None => {
+ if groups.is_empty() {
+ groups.push(Group::new("Presets", Vec::new()));
+ }
+ 0
+ }
+ }
+}
+
+/// Generic group/item edits shared by every preset kind: `rename`, `delete`, `move`,
+/// `newGroup`, `renameGroup`, `deleteGroup`.
+pub(crate) fn edit_groups<T: Named>(groups: &mut Vec<Group<T>>, action: &str, p: &Value, cmd: &str) -> Result<Value> {
+ let group = str_param(p, "group");
+ match action {
+ "rename" => {
+ let name = req_str(p, "preset", cmd)?;
+ let to = req_str(p, "name", cmd)?.to_string();
+ let (gi, ii) = find(groups, name, group).ok_or_else(|| bad(cmd, format!("no preset \"{name}\"")))?;
+ if name != to && find(groups, &to, None).is_some() {
+ return Err(bad(cmd, format!("a preset named \"{to}\" already exists")));
+ }
+ groups[gi].items[ii].set_name(to.clone());
+ Ok(json!({"name": to}))
+ }
+ "delete" => {
+ let names: Vec<String> = match p.get("preset") {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ _ => vec![req_str(p, "preset", cmd)?.to_string()],
+ };
+ for name in &names {
+ let (gi, ii) = find(groups, name, group).ok_or_else(|| bad(cmd, format!("no preset \"{name}\"")))?;
+ groups[gi].items.remove(ii);
+ }
+ Ok(json!({"deleted": names.len()}))
+ }
+ "move" => {
+ let name = req_str(p, "preset", cmd)?;
+ let to = req_str(p, "to", cmd)?;
+ let (gi, ii) = find(groups, name, group).ok_or_else(|| bad(cmd, format!("no preset \"{name}\"")))?;
+ let item = groups[gi].items.remove(ii);
+ let ti = group_index(groups, Some(to));
+ let at = p.get("index").and_then(Value::as_u64).map_or(groups[ti].items.len(), |i| (i as usize).min(groups[ti].items.len()));
+ groups[ti].items.insert(at, item);
+ Ok(json!({"group": to}))
+ }
+ "newGroup" => {
+ let base = str_param(p, "name").unwrap_or("Group");
+ let taken = |n: &str| groups.iter().any(|g| g.name == n);
+ let name = if taken(base) { (1..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default() } else { base.to_string() };
+ groups.push(Group::new(&name, Vec::new()));
+ Ok(json!({"group": name}))
+ }
+ "renameGroup" => {
+ let g = req_str(p, "group", cmd)?;
+ let to = req_str(p, "name", cmd)?.to_string();
+ let i = groups.iter().position(|x| x.name == g).ok_or_else(|| bad(cmd, format!("no group \"{g}\"")))?;
+ groups[i].name = to.clone();
+ Ok(json!({"group": to}))
+ }
+ "deleteGroup" => {
+ let g = req_str(p, "group", cmd)?;
+ let i = groups.iter().position(|x| x.name == g).ok_or_else(|| bad(cmd, format!("no group \"{g}\"")))?;
+ let removed = groups.remove(i);
+ Ok(json!({"group": g, "deleted": removed.items.len()}))
+ }
+ _ => Err(bad(cmd, format!("unknown action {action}"))),
+ }
+}
+
+/// Params doc for the generic group commands.
+pub(crate) const GROUP_EDIT_PARAMS: &str = r##"{"action":"rename|delete|move|newGroup|renameGroup|deleteGroup","preset":name|[names] (rename/delete/move),"group":name? (narrows the lookup; the group for renameGroup/deleteGroup),"name":str (rename: new name; newGroup/renameGroup: group name),"to":group (move),"index":n? (move)}"##;
+
+/// Every preset-panel command.
+pub fn specs() -> Vec<CommandSpec> {
+ let mut v = gradients::specs();
+ v.extend(patterns::specs());
+ v.extend(styles::specs());
+ v.extend(shapes::specs());
+ v.extend(tools::specs());
+ v.extend(clone_source::specs());
+ v
+}
+
+/// Run another command's implementation from inside a preset command (checks `enabled`, but
+/// doesn't journal it: the outer command is what an action replays).
+pub(crate) fn call(s: &mut Session, id: &str, p: Value) -> Result<Value> {
+ let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
+ (spec.enabled)(s).map_err(|why| EngineError::Disabled(id.to_string(), why))?;
+ (spec.run)(s, &p)
+}
diff --git a/crates/engine/src/presets/patterns.rs b/crates/engine/src/presets/patterns.rs
new file mode 100644
index 000000000..589fa09a3
--- /dev/null
+++ b/crates/engine/src/presets/patterns.rs
@@ -0,0 +1,170 @@
+//! Window › Patterns: folders over the pattern library (`pattern.*` owns the patterns
+//! themselves), the selected pattern, and Pattern Fill layers made from it.
+//!
+//! Groups hold pattern **ids**. Library patterns that are in no group (newly defined or imported)
+//! are shown in a trailing "Patterns" group; ids whose pattern was deleted are dropped.
+
+use photocraft_doc::{Fill, LayerContent};
+use serde_json::{Value, json};
+
+use super::{Group, always, bad, edit_groups, group_index, req_str, str_param};
+use crate::commands::CommandSpec;
+use crate::{Result, Session};
+
+const UNGROUPED: &str = "Patterns";
+
+/// Built-in folders for the built-in procedural patterns.
+pub fn builtin_groups() -> Vec<Group<String>> {
+ let lib = crate::pattern_cmds::builtin();
+ let ids = |names: &[&str]| -> Vec<String> { names.iter().filter_map(|n| lib.iter().find(|p| p.name == *n).map(|p| p.id.clone())).collect() };
+ vec![Group::new("Geometric", ids(&["Checkerboard", "Diagonal Lines", "Dots", "Grid"])), Group::new("Textures", ids(&["Bricks", "Weave", "Paper Noise"]))]
+}
+
+/// Bring the groups in line with the library (see the module docs).
+pub fn sync(s: &mut Session) {
+ let lib: Vec<String> = s.patterns.items.iter().map(|p| p.id.clone()).collect();
+ let groups = &mut s.presets.pattern_groups;
+ for g in groups.iter_mut() {
+ g.items.retain(|id| lib.contains(id));
+ }
+ let loose: Vec<String> = lib.iter().filter(|id| !groups.iter().any(|g| g.items.contains(id))).cloned().collect();
+ if !loose.is_empty() {
+ let gi = group_index(groups, Some(UNGROUPED));
+ groups[gi].items.extend(loose);
+ }
+}
+
+/// The selected pattern, if it is still in the library.
+pub fn current(s: &Session) -> Option<&photocraft_doc::Pattern> {
+ let id = s.presets.pattern.as_deref()?;
+ s.patterns.items.iter().find(|p| p.id == id)
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ sync(s);
+ let groups: Vec<Value> = s
+ .presets
+ .pattern_groups
+ .iter()
+ .map(|g| {
+ let pats: Vec<Value> = g.items.iter().filter_map(|id| s.patterns.items.iter().find(|p| &p.id == id)).map(|p| json!({"id": p.id, "name": p.display_name(), "width": p.width, "height": p.height})).collect();
+ json!({"name": g.name, "patterns": pats})
+ })
+ .collect();
+ Ok(json!({"groups": groups, "current": current(s).map(|p| p.id.clone())}))
+}
+
+fn pattern_key(s: &Session, p: &Value, cmd: &str) -> Result<photocraft_doc::Pattern> {
+ let key = str_param(p, "pattern").unwrap_or("");
+ crate::pattern_cmds::resolve(s, key).ok_or_else(|| bad(cmd, format!("no pattern \"{key}\" (see pattern.presets.list)")))
+}
+
+fn active_pattern_fill(s: &Session) -> Option<photocraft_doc::LayerId> {
+ let d = s.active()?;
+ let id = d.active_layer?;
+ matches!(d.doc.layer(id)?.content, LayerContent::Fill(Fill::Pattern { .. })).then_some(id)
+}
+
+fn select(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "pattern.presets.select";
+ let pat = pattern_key(s, p, CMD)?;
+ s.presets.pattern = Some(pat.id.clone());
+ s.presets.rev += 1;
+ let mut out = json!({"pattern": pat.id, "name": pat.display_name()});
+ if p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true)
+ && let Some(id) = active_pattern_fill(s)
+ {
+ s.edit("Change Pattern Fill", |doc, _| {
+ crate::pattern_cmds::ensure_in_doc(doc, &pat);
+ if let Some(l) = doc.layer_mut(id)
+ && let LayerContent::Fill(Fill::Pattern { name, id: pid, .. }) = &mut l.content
+ {
+ *name = pat.name.clone();
+ *pid = pat.id.clone();
+ }
+ Ok(())
+ })?;
+ out["layer"] = json!(id.0);
+ }
+ Ok(out)
+}
+
+fn apply(s: &mut Session, p: &Value) -> Result<Value> {
+ let pat = pattern_key(s, p, "pattern.presets.apply")?;
+ let mut q = p.clone();
+ q["pattern"] = json!(pat.id);
+ super::call(s, "layer.newFillLayer.pattern", q)
+}
+
+fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = super::call(s, "edit.definePattern", p.clone())?;
+ let id = r.get("pattern").and_then(Value::as_str).unwrap_or_default().to_string();
+ sync(s);
+ if let Some(g) = str_param(p, "group") {
+ for gr in &mut s.presets.pattern_groups {
+ gr.items.retain(|x| *x != id);
+ }
+ let gi = group_index(&mut s.presets.pattern_groups, Some(g));
+ s.presets.pattern_groups[gi].items.push(id.clone());
+ }
+ s.presets_changed();
+ Ok(json!({"pattern": id}))
+}
+
+fn edit(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "pattern.presets.edit";
+ sync(s);
+ let action = req_str(p, "action", CMD)?.to_string();
+ // Rename/delete act on the library pattern (by id or name).
+ let r = match action.as_str() {
+ "rename" => super::call(s, "pattern.rename", json!({"pattern": req_str(p, "preset", CMD)?, "name": req_str(p, "name", CMD)?}))?,
+ "delete" => {
+ let keys: Vec<String> = match p.get("preset") {
+ Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
+ _ => vec![req_str(p, "preset", CMD)?.to_string()],
+ };
+ for k in &keys {
+ super::call(s, "pattern.delete", json!({"pattern": k}))?;
+ }
+ json!({"deleted": keys.len()})
+ }
+ "deleteGroup" => {
+ // Deleting a folder deletes its patterns, as in Photoshop.
+ let g = req_str(p, "group", CMD)?;
+ let i = s.presets.pattern_groups.iter().position(|x| x.name == g).ok_or_else(|| bad(CMD, format!("no group \"{g}\"")))?;
+ let gone = s.presets.pattern_groups.remove(i);
+ s.patterns.items.retain(|q| !gone.items.contains(&q.id));
+ json!({"group": g, "deleted": gone.items.len()})
+ }
+ "move" => {
+ let key = req_str(p, "preset", CMD)?;
+ let id = crate::pattern_cmds::resolve(s, key).map(|q| q.id).ok_or_else(|| bad(CMD, format!("no pattern \"{key}\"")))?;
+ let mut q = p.clone();
+ q["preset"] = json!(id);
+ edit_groups(&mut s.presets.pattern_groups, "move", &q, CMD)?
+ }
+ a => edit_groups(&mut s.presets.pattern_groups, a, p, CMD)?,
+ };
+ sync(s);
+ s.presets_changed();
+ Ok(r)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: "pattern.presets.list", label: "Pattern Presets", menu: &[], shortcut: None, params: "{} → {groups:[{name,patterns:[{id,name,width,height}]}],current}", enabled: always, run: list, journal: false },
+ CommandSpec {
+ id: "pattern.presets.select",
+ label: "Select Pattern",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"pattern":id|name,"applyToLayer":bool=true (also changes a selected Pattern Fill layer)} (Fill and new Pattern Fill layers default to it)"##,
+ enabled: always,
+ run: select,
+ journal: true,
+ },
+ CommandSpec { id: "pattern.presets.apply", label: "New Pattern Fill Layer from Preset", menu: &[], shortcut: None, params: r##"{"pattern":id|name?=selected,"scale":1..1000=100,"angle":deg=0} → {layer}"##, enabled: super::has_doc, run: apply, journal: true },
+ CommandSpec { id: "pattern.presets.new", label: "New Pattern Preset", menu: &[], shortcut: None, params: r##"{"name":str?,"group":name?,"rect":[x0,y0,x1,y1]?} (Define Pattern from the selection/canvas into a group)"##, enabled: super::has_doc, run: new_preset, journal: true },
+ CommandSpec { id: "pattern.presets.edit", label: "Edit Pattern Presets", menu: &[], shortcut: None, params: super::GROUP_EDIT_PARAMS, enabled: always, run: edit, journal: true },
+ ]
+}
diff --git a/crates/engine/src/presets/shapes.rs b/crates/engine/src/presets/shapes.rs
new file mode 100644
index 000000000..a84439e75
--- /dev/null
+++ b/crates/engine/src/presets/shapes.rs
@@ -0,0 +1,417 @@
+//! Window › Shapes and the Custom Shape tool: vector shape presets in groups, placed as shape
+//! layers through `shape.create`.
+//!
+//! Built-in shapes were drawn from scratch for PhotoCraft in a 100 × 100 box with a small path
+//! language ([`parse`]): `M x y`, `L x y…`, `C x1 y1 x2 y2 x y…`, `Q x1 y1 x y…`, `Z`, plus `O cx cy r`
+//! (a circle) and `!` before `M`/`O` to subtract that subpath (holes). Shapes defined with Edit ›
+//! Define Custom Shape appear in a trailing "Custom Shapes" group.
+
+use photocraft_doc::vector::{Knot, Path, PathOp, Subpath};
+use photocraft_geom::{Affine, Point, Rect};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{Group, Named, always, bad, edit_groups, find, group_index, has_doc, req_str, str_param, unique_name};
+use crate::commands::CommandSpec;
+use crate::vector_cmds::path_json;
+use crate::{EngineError, Result, Session};
+
+/// Group listing Edit › Define Custom Shape results (`EditState::custom_shapes`).
+pub const CUSTOM_GROUP: &str = "Custom Shapes";
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ShapePreset {
+ pub name: String,
+ pub path: Path,
+}
+
+impl Named for ShapePreset {
+ fn name(&self) -> &str {
+ &self.name
+ }
+ fn set_name(&mut self, n: String) {
+ self.name = n;
+ }
+}
+
+fn circle(cx: f64, cy: f64, r: f64) -> Subpath {
+ // Four cubic quarter arcs (κ = 0.5523).
+ let k = r * 0.552_284_75;
+ let knot = |x: f64, y: f64, ix: f64, iy: f64, ox: f64, oy: f64| Knot::smooth(Point::new(x, y), Point::new(ix, iy), Point::new(ox, oy));
+ Subpath {
+ closed: true,
+ op: PathOp::Combine,
+ knots: vec![
+ knot(cx, cy - r, cx - k, cy - r, cx + k, cy - r),
+ knot(cx + r, cy, cx + r, cy - k, cx + r, cy + k),
+ knot(cx, cy + r, cx + k, cy + r, cx - k, cy + r),
+ knot(cx - r, cy, cx - r, cy + k, cx - r, cy - k),
+ ],
+ }
+}
+
+/// Parse the path language described in the module docs.
+pub fn parse(src: &str) -> std::result::Result<Path, String> {
+ let toks: Vec<String> = src.replace(',', " ").replace('!', " ! ").split_whitespace().map(str::to_string).collect();
+ let mut i = 0;
+ let num = |i: &mut usize| -> std::result::Result<f64, String> {
+ let v = toks.get(*i).ok_or("unexpected end")?.parse::<f64>().map_err(|_| format!("expected a number at `{}`", toks[*i]))?;
+ *i += 1;
+ Ok(v)
+ };
+ let is_num = |i: usize| toks.get(i).is_some_and(|t| t.parse::<f64>().is_ok());
+ let mut subs: Vec<Subpath> = Vec::new();
+ let mut cur: Option<Subpath> = None;
+ let mut op = PathOp::Combine;
+ let finish = |cur: &mut Option<Subpath>, subs: &mut Vec<Subpath>, closed: bool| {
+ if let Some(mut s) = cur.take() {
+ s.closed = closed;
+ if closed && s.knots.len() > 1 {
+ let (f, l) = (s.knots[0].anchor, s.knots[s.knots.len() - 1].anchor);
+ if (f.x - l.x).abs() < 1e-9 && (f.y - l.y).abs() < 1e-9 {
+ let last = s.knots.pop().expect("len > 1");
+ s.knots[0].in_ctrl = last.in_ctrl;
+ }
+ }
+ if !s.knots.is_empty() {
+ subs.push(s);
+ }
+ }
+ };
+ while i < toks.len() {
+ let t = toks[i].clone();
+ i += 1;
+ match t.as_str() {
+ "!" => op = PathOp::Subtract,
+ "M" => {
+ finish(&mut cur, &mut subs, true);
+ let (x, y) = (num(&mut i)?, num(&mut i)?);
+ cur = Some(Subpath { closed: true, knots: vec![Knot::corner(x, y)], op });
+ op = PathOp::Combine;
+ }
+ "L" => {
+ let s = cur.as_mut().ok_or("L before M")?;
+ while is_num(i) {
+ let (x, y) = (num(&mut i)?, num(&mut i)?);
+ s.knots.push(Knot::corner(x, y));
+ }
+ }
+ "C" | "Q" => {
+ let s = cur.as_mut().ok_or("curve before M")?;
+ while is_num(i) {
+ let last = s.knots.last().expect("M pushed a knot").anchor;
+ let (c1, c2, p) = if t == "C" {
+ let c1 = Point::new(num(&mut i)?, num(&mut i)?);
+ let c2 = Point::new(num(&mut i)?, num(&mut i)?);
+ (c1, c2, Point::new(num(&mut i)?, num(&mut i)?))
+ } else {
+ let q = Point::new(num(&mut i)?, num(&mut i)?);
+ let p = Point::new(num(&mut i)?, num(&mut i)?);
+ (Point::new(last.x + (q.x - last.x) * 2.0 / 3.0, last.y + (q.y - last.y) * 2.0 / 3.0), Point::new(p.x + (q.x - p.x) * 2.0 / 3.0, p.y + (q.y - p.y) * 2.0 / 3.0), p)
+ };
+ s.knots.last_mut().expect("non-empty").out_ctrl = c1;
+ s.knots.push(Knot { anchor: p, in_ctrl: c2, out_ctrl: p, smooth: false });
+ }
+ }
+ "Z" => finish(&mut cur, &mut subs, true),
+ "O" => {
+ finish(&mut cur, &mut subs, true);
+ let mut c = circle(num(&mut i)?, num(&mut i)?, num(&mut i)?);
+ c.op = op;
+ op = PathOp::Combine;
+ subs.push(c);
+ }
+ o => return Err(format!("unknown command `{o}`")),
+ }
+ }
+ finish(&mut cur, &mut subs, true);
+ if subs.is_empty() {
+ return Err("empty path".into());
+ }
+ Ok(Path::new(subs))
+}
+
+/// Star / burst polygon with `n` points in the 100 box (`ratio` = inner / outer radius).
+fn star(n: usize, ratio: f64, rot: f64) -> String {
+ let mut s = String::new();
+ for k in 0..2 * n {
+ let r = if k % 2 == 0 { 50.0 } else { 50.0 * ratio };
+ let a = rot + std::f64::consts::PI * k as f64 / n as f64 - std::f64::consts::FRAC_PI_2;
+ s += &format!("{} {:.3} {:.3} ", if k == 0 { "M" } else { "L" }, 50.0 + r * a.cos(), 50.0 + r * a.sin());
+ }
+ s + "Z"
+}
+
+fn sun() -> String {
+ let mut s = "O 50 50 22 ".to_string();
+ for k in 0..12 {
+ let a = std::f64::consts::TAU * k as f64 / 12.0;
+ let p = |r: f64, da: f64| (50.0 + r * (a + da).cos(), 50.0 + r * (a + da).sin());
+ let (b1, b2, tip) = (p(28.0, -0.12), p(28.0, 0.12), p(50.0, 0.0));
+ s += &format!("M {:.3} {:.3} L {:.3} {:.3} L {:.3} {:.3} Z ", b1.0, b1.1, tip.0, tip.1, b2.0, b2.1);
+ }
+ s
+}
+
+fn flower() -> String {
+ let mut s = String::new();
+ for k in 0..6 {
+ let a = std::f64::consts::TAU * k as f64 / 6.0 - std::f64::consts::FRAC_PI_2;
+ s += &format!("O {:.3} {:.3} 18 ", 50.0 + 30.0 * a.cos(), 50.0 + 30.0 * a.sin());
+ }
+ s + "O 50 50 20 ! O 50 50 9"
+}
+
+fn shout() -> String {
+ // A jagged burst stretched into a bubble, with a tail.
+ let mut s = String::new();
+ let n = 14;
+ for k in 0..2 * n {
+ let r = if k % 2 == 0 { 1.0 } else { 0.78 };
+ let a = std::f64::consts::PI * k as f64 / n as f64;
+ s += &format!("{} {:.3} {:.3} ", if k == 0 { "M" } else { "L" }, 50.0 + 50.0 * r * a.cos(), 40.0 + 40.0 * r * a.sin());
+ }
+ s + "Z M 30 70 L 14 100 L 46 74 Z"
+}
+
+/// Built-in groups (our own drawings).
+pub fn builtin() -> Vec<Group<ShapePreset>> {
+ let mk = |list: Vec<(&str, String)>| -> Vec<ShapePreset> { list.into_iter().filter_map(|(n, src)| parse(&src).ok().map(|path| ShapePreset { name: n.into(), path })).collect() };
+ let s = |x: &str| x.to_string();
+ vec![
+ Group::new(
+ "Symbols",
+ mk(vec![
+ ("Heart", s("M 50 92 C 20 70 0 52 0 30 C 0 12 14 0 28 0 C 40 0 47 8 50 16 C 53 8 60 0 72 0 C 86 0 100 12 100 30 C 100 52 80 70 50 92 Z")),
+ ("Star", star(5, 0.4, 0.0)),
+ ("Six-Point Star", star(6, 0.55, 0.0)),
+ ("Burst", star(16, 0.72, 0.0)),
+ ("Check Mark", s("M 5 55 L 20 40 L 38 58 L 82 12 L 97 27 L 38 88 Z")),
+ ("Cross", s("M 20 5 L 50 35 L 80 5 L 95 20 L 65 50 L 95 80 L 80 95 L 50 65 L 20 95 L 5 80 L 35 50 L 5 20 Z")),
+ ("Plus", s("M 38 0 L 62 0 L 62 38 L 100 38 L 100 62 L 62 62 L 62 100 L 38 100 L 38 62 L 0 62 L 0 38 L 38 38 Z")),
+ ("Ring", s("O 50 50 50 ! O 50 50 32")),
+ ("Lightning", s("M 58 0 L 18 56 L 44 56 L 34 100 L 82 38 L 55 38 L 70 0 Z")),
+ ("Diamond", s("M 50 0 L 90 50 L 50 100 L 10 50 Z")),
+ ]),
+ ),
+ Group::new(
+ "Arrows",
+ mk(vec![
+ ("Arrow Right", s("M 0 35 L 55 35 L 55 15 L 100 50 L 55 85 L 55 65 L 0 65 Z")),
+ ("Arrow Left", s("M 100 35 L 45 35 L 45 15 L 0 50 L 45 85 L 45 65 L 100 65 Z")),
+ ("Arrow Up", s("M 35 100 L 35 45 L 15 45 L 50 0 L 85 45 L 65 45 L 65 100 Z")),
+ ("Arrow Down", s("M 35 0 L 35 55 L 15 55 L 50 100 L 85 55 L 65 55 L 65 0 Z")),
+ ("Double Arrow", s("M 0 50 L 25 20 L 25 38 L 75 38 L 75 20 L 100 50 L 75 80 L 75 62 L 25 62 L 25 80 Z")),
+ ("Chevron", s("M 10 0 L 45 0 L 95 50 L 45 100 L 10 100 L 60 50 Z")),
+ ("Curved Arrow", s("M 8 92 C 8 45 35 22 68 22 L 68 4 L 98 34 L 68 64 L 68 44 C 48 44 30 58 30 92 Z")),
+ ]),
+ ),
+ Group::new(
+ "Speech Bubbles",
+ mk(vec![
+ ("Speech Bubble", s("M 15 5 L 85 5 C 93 5 100 12 100 20 L 100 60 C 100 68 93 75 85 75 L 45 75 L 20 98 L 25 75 L 15 75 C 7 75 0 68 0 60 L 0 20 C 0 12 7 5 15 5 Z")),
+ ("Round Bubble", s("M 50 5 C 78 5 100 22 100 42 C 100 62 78 79 50 79 C 44 79 38 78 33 77 L 12 95 L 18 72 C 7 65 0 54 0 42 C 0 22 22 5 50 5 Z")),
+ ("Thought Bubble", s("M 50 5 C 78 5 100 20 100 38 C 100 56 78 71 50 71 C 22 71 0 56 0 38 C 0 20 22 5 50 5 Z O 22 82 8 O 9 95 5")),
+ ("Shout Bubble", shout()),
+ ]),
+ ),
+ Group::new(
+ "Nature",
+ mk(vec![
+ ("Leaf", s("M 50 0 C 80 20 95 50 80 75 C 72 88 60 92 53 92 L 53 100 L 47 100 L 47 92 C 40 92 28 88 20 75 C 5 50 20 20 50 0 Z ! M 48.5 22 L 51.5 22 L 51.5 88 L 48.5 88 Z")),
+ ("Sun", sun()),
+ ("Crescent Moon", s("O 45 50 45 ! O 66 40 38")),
+ ("Cloud", s("M 25 80 C 10 80 0 70 0 58 C 0 46 10 37 22 37 C 24 20 38 10 54 10 C 70 10 82 20 85 34 C 95 35 100 45 100 57 C 100 70 90 80 78 80 Z")),
+ ("Raindrop", s("M 50 0 C 60 25 85 45 85 68 C 85 87 69 100 50 100 C 31 100 15 87 15 68 C 15 45 40 25 50 0 Z")),
+ ("Flower", flower()),
+ ("Tree", s("M 50 0 L 85 45 L 68 45 L 92 75 L 56 75 L 56 100 L 44 100 L 44 75 L 8 75 L 32 45 L 15 45 Z")),
+ ]),
+ ),
+ Group::new(
+ "Animals",
+ mk(vec![
+ ("Fish", s("M 0 50 C 15 25 45 15 70 32 L 96 12 L 88 50 L 96 88 L 70 68 C 45 85 15 75 0 50 Z ! O 20 45 4")),
+ ("Cat", s("M 15 10 L 35 30 C 45 27 55 27 65 30 L 85 10 L 88 50 C 92 75 72 95 50 95 C 28 95 8 75 12 50 Z ! O 36 58 6 ! O 64 58 6")),
+ ("Bird", s("M 0 40 C 15 30 35 32 50 50 C 65 32 85 30 100 40 C 85 40 65 48 50 70 C 35 48 15 40 0 40 Z")),
+ ("Butterfly", s("M 50 30 C 40 5 5 0 5 25 C 5 45 30 50 45 50 C 25 55 10 75 25 90 C 38 100 48 80 50 65 C 52 80 62 100 75 90 C 90 75 75 55 55 50 C 70 50 95 45 95 25 C 95 0 60 5 50 30 Z")),
+ ("Paw Print", s("M 50 50 C 68 50 82 66 82 80 C 82 92 70 96 60 94 C 55 93 52 91 50 91 C 48 91 45 93 40 94 C 30 96 18 92 18 80 C 18 66 32 50 50 50 Z O 18 42 10 O 37 22 11 O 63 22 11 O 82 42 10")),
+ ("Rabbit", s("O 50 72 26 M 34 52 C 22 30 24 2 34 2 C 44 2 46 30 44 50 Z M 66 52 C 78 30 76 2 66 2 C 56 2 54 30 56 50 Z")),
+ ]),
+ ),
+ ]
+}
+
+/// Every shape the panel shows: the preset groups plus Define Custom Shape results.
+pub fn all_groups(s: &Session) -> Vec<Group<ShapePreset>> {
+ let mut g = s.presets.shapes.clone();
+ let custom: Vec<ShapePreset> = s.edit_state.custom_shapes.iter().map(|c| ShapePreset { name: c.name.clone(), path: c.path.clone() }).collect();
+ if !custom.is_empty() {
+ g.push(Group::new(CUSTOM_GROUP, custom));
+ }
+ g
+}
+
+fn lookup(s: &Session, name: &str, group: Option<&str>, cmd: &str) -> Result<ShapePreset> {
+ let groups = all_groups(s);
+ let (gi, ii) = find(&groups, name, group).ok_or_else(|| bad(cmd, format!("no shape \"{name}\" (see shape.presets.list)")))?;
+ Ok(groups[gi].items[ii].clone())
+}
+
+/// Coverage (0..1) of `path` fitted into a `size`² swatch with a small margin.
+pub fn thumbnail(path: &Path, size: u32) -> Vec<f32> {
+ let size = size.clamp(4, 512);
+ let m = (size as f64 * 0.08).max(1.0);
+ let fitted = fit(path, [m, m, size as f64 - 2.0 * m, size as f64 - 2.0 * m], true);
+ photocraft_vector::path_coverage(&fitted, Rect::new(0, 0, size as i32, size as i32))
+}
+
+/// Map `path` (its control bounds) onto `rect` = [x, y, w, h]; `keep` preserves the aspect ratio
+/// (centred in the rect).
+pub fn fit(path: &Path, rect: [f64; 4], keep: bool) -> Path {
+ let Some((x0, y0, x1, y1)) = path.control_bounds() else { return path.clone() };
+ let (bw, bh) = ((x1 - x0).max(1e-9), (y1 - y0).max(1e-9));
+ let (mut sx, mut sy) = (rect[2] / bw, rect[3] / bh);
+ let (mut ox, mut oy) = (rect[0], rect[1]);
+ if keep {
+ let k = sx.min(sy);
+ ox += (rect[2] - bw * k) / 2.0;
+ oy += (rect[3] - bh * k) / 2.0;
+ (sx, sy) = (k, k);
+ }
+ path.transform(&Affine { m: [sx, 0.0, 0.0, sy, ox - x0 * sx, oy - y0 * sy] })
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let groups: Vec<Value> = all_groups(s)
+ .iter()
+ .map(|g| {
+ let items: Vec<Value> = g.items.iter().map(|i| json!({"name": i.name, "subpaths": i.path.subpaths.len()})).collect();
+ json!({"name": g.name, "shapes": items})
+ })
+ .collect();
+ Ok(json!({"groups": groups}))
+}
+
+fn place(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "shape.presets.place";
+ let name = req_str(p, "preset", CMD)?;
+ let shape = lookup(s, name, str_param(p, "group"), CMD)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let (w, h) = (d.doc.size.width as f64, d.doc.size.height as f64);
+ let keep = p.get("keepAspect").and_then(Value::as_bool).unwrap_or(true);
+ let rect = match p.get("rect").and_then(Value::as_array) {
+ Some(a) if a.len() == 4 => {
+ let v: Vec<f64> = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();
+ // Negative sizes (dragging up/left) flip into a positive rect.
+ let (x, wd) = if v[2] < 0.0 { (v[0] + v[2], -v[2]) } else { (v[0], v[2]) };
+ let (y, hd) = if v[3] < 0.0 { (v[1] + v[3], -v[3]) } else { (v[1], v[3]) };
+ if wd < 1.0 || hd < 1.0 {
+ return Err(bad(CMD, "the shape rect is empty"));
+ }
+ [x, y, wd, hd]
+ }
+ _ => {
+ let side = w.min(h) * 0.5;
+ [(w - side) / 2.0, (h - side) / 2.0, side, side]
+ }
+ };
+ let path = fit(&shape.path, rect, keep);
+ let mut q = json!({"kind": "path", "path": path_json(&path), "name": str_param(p, "name").unwrap_or(&shape.name)});
+ for k in ["fill", "stroke", "addTo", "op"] {
+ if let Some(v) = p.get(k) {
+ q[k] = v.clone();
+ }
+ }
+ let mut r = super::call(s, "shape.create", q)?;
+ r["preset"] = json!(shape.name);
+ Ok(r)
+}
+
+fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "shape.presets.new";
+ let path = match p.get("path") {
+ Some(v @ Value::Object(_)) => crate::vector_cmds::parse_path(v).map_err(|e| bad(CMD, e))?,
+ Some(Value::String(src)) if src.trim_start().starts_with(['M', 'O', '!']) => parse(src).map_err(|e| bad(CMD, e))?,
+ other => {
+ let d = s.active().ok_or_else(|| bad(CMD, "no document (pass `path`)"))?;
+ crate::edit_menu_cmds::current_path(&d.doc, d.active_layer, other.and_then(Value::as_str)).ok_or_else(|| bad(CMD, "select a path or shape layer first"))?
+ }
+ };
+ if path.is_empty() {
+ return Err(bad(CMD, "the path is empty"));
+ }
+ // Normalise into the 100 box so thumbnails and placing don't depend on where it was drawn.
+ let path = fit(&path, [0.0, 0.0, 100.0, 100.0], true);
+ let name = unique_name(&s.presets.shapes, str_param(p, "name").unwrap_or("Shape"));
+ let gi = group_index(&mut s.presets.shapes, str_param(p, "group"));
+ let group = s.presets.shapes[gi].name.clone();
+ s.presets.shapes[gi].items.push(ShapePreset { name: name.clone(), path });
+ s.presets_changed();
+ Ok(json!({"name": name, "group": group}))
+}
+
+fn edit(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "shape.presets.edit";
+ let action = req_str(p, "action", CMD)?.to_string();
+ // Define Custom Shape results live in the edit state; rename/delete them there.
+ let custom = |s: &Session, n: &str| str_param(p, "group").is_none_or(|g| g == CUSTOM_GROUP) && find(&s.presets.shapes, n, None).is_none() && s.edit_state.custom_shapes.iter().any(|c| c.name == n);
+ let r = match action.as_str() {
+ "rename" if custom(s, req_str(p, "preset", CMD)?) => {
+ let (n, to) = (req_str(p, "preset", CMD)?, req_str(p, "name", CMD)?);
+ if let Some(c) = s.edit_state.custom_shapes.iter_mut().find(|c| c.name == n) {
+ c.name = to.to_string();
+ }
+ json!({"name": to})
+ }
+ "delete" if p.get("preset").and_then(Value::as_str).is_some_and(|n| custom(s, n)) => {
+ let n = req_str(p, "preset", CMD)?;
+ s.edit_state.custom_shapes.retain(|c| c.name != n);
+ json!({"deleted": 1})
+ }
+ a => edit_groups(&mut s.presets.shapes, a, p, CMD)?,
+ };
+ s.presets_changed();
+ Ok(r)
+}
+
+fn reset(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut b = builtin();
+ if p.get("append").and_then(Value::as_bool).unwrap_or(false) {
+ for g in &mut b {
+ g.name = super::gradients::unique_group(&s.presets.shapes, &g.name);
+ }
+ s.presets.shapes.extend(b);
+ } else {
+ s.presets.shapes = b;
+ }
+ s.presets_changed();
+ Ok(json!({"groups": s.presets.shapes.len()}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: "shape.presets.list", label: "Shape Presets", menu: &[], shortcut: None, params: "{} → {groups:[{name,shapes:[{name,subpaths}]}]}", enabled: always, run: list, journal: false },
+ CommandSpec {
+ id: "shape.presets.place",
+ label: "Place Custom Shape",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"preset":name,"group":name?,"rect":[x,y,w,h]? (default: centred, half the canvas),"keepAspect":bool=true,"fill":…?=foreground,"stroke":…?,"name":str?,"addTo":layerId?,"op":"combine|subtract|intersect|exclude"?} → shape.info (Custom Shape tool / Shapes panel; fill and stroke as in shape.create)"##,
+ enabled: has_doc,
+ run: place,
+ journal: true,
+ },
+ CommandSpec {
+ id: "shape.presets.new",
+ label: "New Shape Preset",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"name":str="Shape","group":name?,"path":{…path}|"M x y L …" (preset path language)|"work"|saved path name? (default: work path, active shape layer or vector mask)}"##,
+ enabled: always,
+ run: new_preset,
+ journal: true,
+ },
+ CommandSpec { id: "shape.presets.edit", label: "Edit Shape Presets", menu: &[], shortcut: None, params: super::GROUP_EDIT_PARAMS, enabled: always, run: edit, journal: true },
+ CommandSpec { id: "shape.presets.reset", label: "Restore Default Shapes", menu: &[], shortcut: None, params: r##"{"append":bool=false}"##, enabled: always, run: reset, journal: true },
+ ]
+}
diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs
new file mode 100644
index 000000000..a392caf0f
--- /dev/null
+++ b/crates/engine/src/presets/styles.rs
@@ -0,0 +1,279 @@
+//! Window › Styles: layer style presets. A style is a list of layer effects plus, optionally,
+//! the blending options it was saved with (blend mode, fill opacity). Applying one replaces the
+//! selected layers' effects (Photoshop; ⇧-click adds instead: `"add": true`).
+//!
+//! The built-in groups are our own designs, built from the same effect params as
+//! `layer.layerStyle.*`.
+
+use photocraft_color::{BlendMode, ColorMode, SampleType};
+use photocraft_doc::{Document, Effect, Layer, Size};
+use photocraft_geom::Rect;
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{Group, Named, always, bad, edit_groups, find, group_index, has_layer, req_str, str_param, unique_name};
+use crate::commands::CommandSpec;
+use crate::layer_style::effect_from_params;
+use crate::{EngineError, Result, Session};
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct StylePreset {
+ pub name: String,
+ pub effects: Vec<Effect>,
+ /// Blending options saved with the style ("Include Layer Blending Options").
+ #[serde(default)]
+ pub blend: Option<BlendMode>,
+ #[serde(default)]
+ pub fill_opacity: Option<f32>,
+}
+
+impl Named for StylePreset {
+ fn name(&self) -> &str {
+ &self.name
+ }
+ fn set_name(&mut self, n: String) {
+ self.name = n;
+ }
+}
+
+impl StylePreset {
+ /// From `[[kind, params], …]` in `layer.layerStyle.<kind>` form.
+ fn from_spec(name: &str, fx: Value, fill: Option<f32>) -> Self {
+ let effects = fx.as_array().map(|a| a.iter().filter_map(|e| effect_from_params(e.get(0)?.as_str()?, e.get(1).unwrap_or(&Value::Null))).collect()).unwrap_or_default();
+ StylePreset { name: name.into(), effects, blend: None, fill_opacity: fill }
+ }
+
+ pub fn to_json(&self) -> Value {
+ json!({
+ "name": self.name,
+ "effects": self.effects.iter().map(|e| e.label()).collect::<Vec<_>>(),
+ "blend": self.blend.map(|b| b.label()),
+ "fillOpacity": self.fill_opacity.map(|f| (f * 100.0).round()),
+ })
+ }
+}
+
+/// Built-in style groups (our own designs).
+pub fn builtin() -> Vec<Group<StylePreset>> {
+ let s = StylePreset::from_spec;
+ vec![
+ Group::new(
+ "Basics",
+ vec![
+ s("Default Style (None)", json!([]), None),
+ s("Drop Shadow", json!([["dropShadow", {"distance": 6, "size": 8, "opacity": 60}]]), None),
+ s("Soft Shadow", json!([["dropShadow", {"distance": 2, "size": 16, "opacity": 45}]]), None),
+ s("Black Stroke", json!([["stroke", {"size": 3, "color": "#000000", "position": "outside"}]]), None),
+ s("White Stroke", json!([["stroke", {"size": 3, "color": "#ffffff", "position": "outside"}]]), None),
+ s("Inner Shadow", json!([["innerShadow", {"distance": 4, "size": 6, "opacity": 55}]]), None),
+ s("Outer Glow", json!([["outerGlow", {"size": 14, "color": "#ffe9a8", "opacity": 80}]]), None),
+ s("Emboss", json!([["bevelEmboss", {"style": "emboss", "size": 4, "depth": 120}]]), None),
+ ],
+ ),
+ Group::new(
+ "Text Effects",
+ vec![
+ s("Neon Blue", json!([["colorOverlay", {"color": "#d8f4ff"}], ["innerGlow", {"color": "#3fb6ff", "size": 6, "opacity": 90, "blend": "normal"}], ["outerGlow", {"color": "#1e90ff", "size": 22, "opacity": 90}]]), None),
+ s("Neon Pink", json!([["colorOverlay", {"color": "#ffe1f3"}], ["innerGlow", {"color": "#ff4fb4", "size": 6, "opacity": 90, "blend": "normal"}], ["outerGlow", {"color": "#ff2d95", "size": 22, "opacity": 90}]]), None),
+ s("Chrome", json!([["gradientOverlay", {"from": "#3a3f47", "to": "#f4f6f8", "angle": 90}], ["bevelEmboss", {"style": "inner", "size": 6, "depth": 250, "soften": 1}], ["stroke", {"size": 1, "color": "#2a2d33", "position": "outside"}]]), None),
+ s("Gold", json!([["gradientOverlay", {"from": "#8a5a12", "to": "#ffe08a", "angle": 90}], ["bevelEmboss", {"style": "inner", "size": 5, "depth": 180}], ["dropShadow", {"distance": 3, "size": 5, "opacity": 50}]]), None),
+ s("Comic Outline", json!([["colorOverlay", {"color": "#ffd23f"}], ["stroke", {"size": 4, "color": "#111111", "position": "outside"}], ["dropShadow", {"distance": 6, "size": 0, "opacity": 100, "angle": 135}]]), None),
+ s("Letterpress", json!([["colorOverlay", {"color": "#5b6168"}], ["innerShadow", {"distance": 2, "size": 2, "opacity": 70}], ["dropShadow", {"distance": 1, "size": 0, "color": "#ffffff", "opacity": 60, "blend": "screen", "angle": 90}]]), None),
+ s("Hollow", json!([["stroke", {"size": 2, "color": "#222222", "position": "inside"}]]), Some(0.0)),
+ ],
+ ),
+ Group::new(
+ "Buttons",
+ vec![
+ s("Glass", json!([["gradientOverlay", {"from": "#2b6cb0", "to": "#90cdf4", "angle": 90}], ["innerGlow", {"color": "#ffffff", "size": 6, "opacity": 45, "blend": "screen"}], ["bevelEmboss", {"style": "inner", "size": 8, "depth": 100, "soften": 4}], ["dropShadow", {"distance": 3, "size": 8, "opacity": 40}]]), None),
+ s("Gel Green", json!([["gradientOverlay", {"from": "#1f7a3a", "to": "#7be495", "angle": 90}], ["innerShadow", {"distance": 2, "size": 5, "opacity": 35}], ["bevelEmboss", {"style": "inner", "size": 10, "depth": 150, "soften": 6}]]), None),
+ s("Pressed", json!([["colorOverlay", {"color": "#d7dbe0"}], ["innerShadow", {"distance": 3, "size": 6, "opacity": 60}], ["stroke", {"size": 1, "color": "#9aa1a9", "position": "inside"}]]), None),
+ s("Pill Red", json!([["gradientOverlay", {"from": "#9b1c1c", "to": "#f87171", "angle": 90}], ["bevelEmboss", {"style": "pillow", "size": 6, "depth": 120}], ["dropShadow", {"distance": 2, "size": 4, "opacity": 45}]]), None),
+ s("Flat Shadow", json!([["colorOverlay", {"color": "#3b82f6"}], ["dropShadow", {"distance": 5, "size": 0, "opacity": 35, "angle": 90}]]), None),
+ s("Satin Plum", json!([["colorOverlay", {"color": "#7e3a8c"}], ["satin", {"color": "#1b0420", "opacity": 55, "size": 18, "distance": 14}], ["bevelEmboss", {"style": "inner", "size": 4, "depth": 80}]]), None),
+ ],
+ ),
+ ]
+}
+
+fn find_style<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<&'a StylePreset> {
+ let name = req_str(p, "preset", cmd)?;
+ let (gi, ii) = find(&s.presets.styles, name, str_param(p, "group")).ok_or_else(|| bad(cmd, format!("no style \"{name}\" (see style.presets.list)")))?;
+ Ok(&s.presets.styles[gi].items[ii])
+}
+
+fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ let groups: Vec<Value> = s.presets.styles.iter().map(|g| json!({"name": g.name, "presets": g.items.iter().map(StylePreset::to_json).collect::<Vec<_>>()})).collect();
+ Ok(json!({"groups": groups}))
+}
+
+/// Target layers: `"layers": [ids]`, `"layer": id`, else every selected layer.
+fn targets(s: &Session, p: &Value) -> Vec<photocraft_doc::LayerId> {
+ if let Some(a) = p.get("layers").and_then(Value::as_array) {
+ return a.iter().filter_map(Value::as_u64).map(photocraft_doc::LayerId).collect();
+ }
+ if let Some(id) = p.get("layer").and_then(Value::as_u64) {
+ return vec![photocraft_doc::LayerId(id)];
+ }
+ crate::layer_multi_cmds::selected(s)
+}
+
+fn apply(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "style.presets.apply";
+ let style = find_style(s, p, CMD)?.clone();
+ let add = p.get("add").and_then(Value::as_bool).unwrap_or(false);
+ let ids = targets(s, p);
+ if ids.is_empty() {
+ return Err(bad(CMD, "no target layers"));
+ }
+ // Pattern overlays name their pattern; resolve to library patterns copied into the document.
+ let mut effects = Vec::new();
+ let mut pats = Vec::new();
+ for fx in style.effects {
+ let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx)?;
+ effects.push(fx);
+ pats.extend(pat);
+ }
+ let label = format!("Apply Style: {}", style.name);
+ s.edit(&label, |doc, _| {
+ for pat in &pats {
+ crate::pattern_cmds::ensure_in_doc(doc, pat);
+ }
+ for id in &ids {
+ let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
+ // Styles can't sit on the Background: Photoshop turns it into a normal layer first.
+ if l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, photocraft_doc::LayerContent::Raster(_)) {
+ l.name = "Layer 0".into();
+ l.locks.transparency = false;
+ l.locks.position = false;
+ }
+ if add {
+ l.effects.items.extend(effects.iter().cloned());
+ } else {
+ l.effects.items = effects.clone();
+ l.effects.psd_raw = None;
+ }
+ l.effects.psd_raw = None;
+ l.effects.enabled = true;
+ if !add || style.blend.is_some() {
+ if let Some(b) = style.blend {
+ l.blend = b;
+ }
+ if let Some(f) = style.fill_opacity {
+ l.fill_opacity = f;
+ } else if !add {
+ l.fill_opacity = 1.0;
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"layers": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "style": style.name}))
+}
+
+fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "style.presets.new";
+ let id = crate::commands::layer_param(s, p)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let with_fx = p.get("includeEffects").and_then(Value::as_bool).unwrap_or(true);
+ let with_blend = p.get("includeBlending").and_then(Value::as_bool).unwrap_or(true);
+ if !with_fx && !with_blend {
+ return Err(bad(CMD, "include effects and/or blending options"));
+ }
+ let style = StylePreset {
+ name: unique_name(&s.presets.styles, str_param(p, "name").unwrap_or("Style")),
+ effects: if with_fx { l.effects.items.clone() } else { Vec::new() },
+ blend: with_blend.then_some(l.blend),
+ fill_opacity: with_blend.then_some(l.fill_opacity),
+ };
+ let gi = group_index(&mut s.presets.styles, str_param(p, "group"));
+ let out = json!({"name": style.name, "group": s.presets.styles[gi].name, "effects": style.effects.len()});
+ s.presets.styles[gi].items.push(style);
+ s.presets_changed();
+ Ok(out)
+}
+
+fn edit(s: &mut Session, p: &Value) -> Result<Value> {
+ let action = req_str(p, "action", "style.presets.edit")?.to_string();
+ let r = edit_groups(&mut s.presets.styles, &action, p, "style.presets.edit")?;
+ s.presets_changed();
+ Ok(r)
+}
+
+fn reset(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut b = builtin();
+ if p.get("append").and_then(Value::as_bool).unwrap_or(false) {
+ for g in &mut b {
+ g.name = super::gradients::unique_group(&s.presets.styles, &g.name);
+ }
+ s.presets.styles.extend(b);
+ } else {
+ s.presets.styles = b;
+ }
+ s.presets_changed();
+ Ok(json!({"groups": s.presets.styles.len()}))
+}
+
+/// Swatch for the Styles panel: the style on a rounded square, `size`² RGBA8 (straight alpha,
+/// transparent around the square).
+pub fn thumbnail(s: &Session, style: &StylePreset, size: u32) -> Vec<u8> {
+ let size = size.clamp(8, 256);
+ let mut doc = Document::new("style", Size::new(size, size), ColorMode::Rgb, SampleType::U8);
+ let fmt = doc.pixel_format();
+ let mut l = Layer::raster("swatch", fmt);
+ let m = (size as f32 * 0.2).round();
+ let (x0, x1) = (m, size as f32 - m);
+ let r = size as f32 * 0.12;
+ if let Some(surf) = l.surface_mut() {
+ let mut px = Vec::with_capacity((size * size * 4) as usize);
+ for y in 0..size {
+ for x in 0..size {
+ // Coverage of a rounded square (1 px anti-aliasing).
+ let (cx, cy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let qx = (cx - (x0 + x1) / 2.0).abs() - ((x1 - x0) / 2.0 - r);
+ let qy = (cy - (x0 + x1) / 2.0).abs() - ((x1 - x0) / 2.0 - r);
+ let d = (qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0)) - r;
+ let a = (0.5 - d).clamp(0.0, 1.0);
+ px.extend_from_slice(&[0.86, 0.86, 0.86, a]);
+ }
+ }
+ surf.write_region(Rect::new(0, 0, size as i32, size as i32), &px);
+ }
+ for fx in &style.effects {
+ if let Ok((fx, pat)) = crate::pattern_cmds::resolve_effect(s, fx.clone()) {
+ if let Some(p) = pat {
+ crate::pattern_cmds::ensure_in_doc(&mut doc, &p);
+ }
+ l.effects.items.push(fx);
+ }
+ }
+ l.effects.enabled = true;
+ if let Some(b) = style.blend {
+ l.blend = b;
+ }
+ if let Some(f) = style.fill_opacity {
+ l.fill_opacity = f;
+ }
+ doc.layers.push(l);
+ photocraft_compose::render(&doc, doc.bounds()).to_rgba8().pixels
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: "style.presets.list", label: "Style Presets", menu: &[], shortcut: None, params: "{} → {groups:[{name,presets:[{name,effects,blend,fillOpacity}]}]}", enabled: always, run: list, journal: false },
+ CommandSpec {
+ id: "style.presets.apply",
+ label: "Apply Style",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"preset":name,"group":name?,"layers":[ids]?|"layer":id? (default: the selected layers),"add":bool=false (⇧-click: add to the existing effects)} → {layers,style}"##,
+ enabled: has_layer,
+ run: apply,
+ journal: true,
+ },
+ CommandSpec { id: "style.presets.new", label: "New Style…", menu: &[], shortcut: None, params: r##"{"name":str="Style","group":name?,"layer":id?,"includeEffects":bool=true,"includeBlending":bool=true} (from the layer's effects)"##, enabled: has_layer, run: new_preset, journal: true },
+ CommandSpec { id: "style.presets.edit", label: "Edit Style Presets", menu: &[], shortcut: None, params: super::GROUP_EDIT_PARAMS, enabled: always, run: edit, journal: true },
+ CommandSpec { id: "style.presets.reset", label: "Restore Default Styles", menu: &[], shortcut: None, params: r##"{"append":bool=false}"##, enabled: always, run: reset, journal: true },
+ ]
+}
diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rs
new file mode 100644
index 000000000..9e4bb1a28
--- /dev/null
+++ b/crates/engine/src/presets/tests.rs
@@ -0,0 +1,420 @@
+use serde_json::{Value, json};
+
+use crate::Session;
+use photocraft_doc::{Fill, LayerContent, LayerId};
+
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap();
+ s
+}
+
+fn active(s: &Session) -> LayerId {
+ s.active().unwrap().active_layer.unwrap()
+}
+
+fn layer_px(s: &Session, x: i32, y: i32) -> Vec<f32> {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
+}
+
+// ------------------------------------------------------------------ gradients
+
+#[test]
+fn gradient_builtins_and_listing() {
+ let mut s = Session::new();
+ let v = s.execute("gradient.presets.list", json!({})).unwrap();
+ let groups = v["groups"].as_array().unwrap();
+ let names: Vec<&str> = groups.iter().map(|g| g["name"].as_str().unwrap()).collect();
+ assert_eq!(names[0], "Basics");
+ assert!(names.contains(&"Blues") && names.contains(&"Grays"));
+ assert_eq!(v["current"]["name"], "Foreground to Background");
+ assert_eq!(groups[0]["presets"][1]["transparency"][1], json!([1.0, 0.0]));
+}
+
+#[test]
+fn gradient_tool_uses_selected_preset_at_every_depth() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ // Default (Foreground to Background): black → white, as before presets existed.
+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [63, 0]})).unwrap();
+ assert!(layer_px(&s, 0, 10)[0] < 0.02, "depth {depth}");
+ assert!(layer_px(&s, 63, 10)[0] > 0.98);
+ s.execute("gradient.presets.select", json!({"preset": "Red 01"})).unwrap();
+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [63, 0]})).unwrap();
+ let left = layer_px(&s, 0, 10);
+ // Red 01 starts at #7f0000.
+ assert!((left[0] - 127.0 / 255.0).abs() < 0.02 && left[1] < 0.01, "depth {depth}: {left:?}");
+ // Explicit stops and a named preset override the selection.
+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [63, 0], "stops": [[0, "#00ff00"], [1, "#0000ff"]]})).unwrap();
+ assert!(layer_px(&s, 0, 10)[1] > 0.98);
+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [63, 0], "gradient": "Black, White"})).unwrap();
+ assert!(layer_px(&s, 63, 10)[0] > 0.98);
+ }
+}
+
+#[test]
+fn foreground_to_transparent_paints_alpha() {
+ let mut s = session(8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("gradient.presets.select", json!({"preset": "Foreground to Transparent"})).unwrap();
+ s.execute("paint.gradient", json!({"from": [0, 0], "to": [63, 0]})).unwrap();
+ assert!(layer_px(&s, 0, 5)[3] > 0.95);
+ assert!(layer_px(&s, 63, 5)[3] < 0.05);
+ let mid = layer_px(&s, 32, 5)[3];
+ assert!((mid - 0.5).abs() < 0.05, "{mid}");
+}
+
+#[test]
+fn gradient_apply_creates_fill_layer_and_select_recolours_it() {
+ let mut s = session(8);
+ let r = s.execute("gradient.presets.apply", json!({"preset": "Blue 01", "angle": 0})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ let stops = |s: &Session| match &s.active().unwrap().doc.layer(id).unwrap().content {
+ LayerContent::Fill(Fill::Gradient { stops, angle, .. }) => (stops.clone(), *angle),
+ _ => panic!("not a gradient fill"),
+ };
+ let (st, angle) = stops(&s);
+ assert_eq!(angle, 0.0);
+ assert!((st[0].1.c[2] - 0x91 as f32 / 255.0).abs() < 1e-3);
+ // Clicking another preset with the fill layer selected changes it (one undo step).
+ let r = s.execute("gradient.presets.select", json!({"preset": "Green 01"})).unwrap();
+ assert_eq!(r["layer"], json!(id.0));
+ assert!(stops(&s).0[0].1.c[1] > 0.25);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!((stops(&s).0[0].1.c[2] - 0x91 as f32 / 255.0).abs() < 1e-3);
+}
+
+#[test]
+fn gradient_new_rename_move_delete_groups() {
+ let mut s = Session::new();
+ let rev = s.prefs.rev();
+ s.execute("gradient.presets.select", json!({"stops": [[0, "#112233"], [0.5, "foreground"], [1, "#ffffff"]], "transparency": [[0, 100], [1, 50]]})).unwrap();
+ let r = s.execute("gradient.presets.new", json!({"name": "Mine", "group": "My Gradients"})).unwrap();
+ assert_eq!(r["group"], "My Gradients");
+ assert!(s.prefs.rev() > rev, "preset edits mark preferences dirty");
+ let dup = s.execute("gradient.presets.new", json!({"name": "Mine"})).unwrap();
+ assert_eq!(dup["name"], "Mine 2");
+ s.execute("gradient.presets.edit", json!({"action": "rename", "preset": "Mine", "name": "Ours"})).unwrap();
+ assert!(s.execute("gradient.presets.edit", json!({"action": "rename", "preset": "Ours", "name": "Mine 2"})).is_err());
+ s.execute("gradient.presets.edit", json!({"action": "move", "preset": "Mine 2", "to": "My Gradients", "index": 0})).unwrap();
+ let v = s.execute("gradient.presets.list", json!({})).unwrap();
+ let mine = v["groups"].as_array().unwrap().iter().find(|g| g["name"] == "My Gradients").unwrap().clone();
+ assert_eq!(mine["presets"][0]["name"], "Mine 2");
+ assert_eq!(mine["presets"][1]["stops"][1], json!([0.5, "foreground"]));
+ assert_eq!(mine["presets"][1]["transparency"][1], json!([1.0, 50.0]));
+ s.execute("gradient.presets.edit", json!({"action": "delete", "preset": ["Ours", "Mine 2"]})).unwrap();
+ s.execute("gradient.presets.edit", json!({"action": "deleteGroup", "group": "My Gradients"})).unwrap();
+ s.execute("gradient.presets.edit", json!({"action": "deleteGroup", "group": "Blues"})).unwrap();
+ s.execute("gradient.presets.reset", json!({})).unwrap();
+ let v = s.execute("gradient.presets.list", json!({})).unwrap();
+ assert!(v["groups"].as_array().unwrap().iter().any(|g| g["name"] == "Blues"));
+ // Bad params.
+ assert!(s.execute("gradient.presets.select", json!({"preset": "nope"})).is_err());
+ assert!(s.execute("gradient.presets.select", json!({"stops": [[0, "#zzzzzz"], [1, "#000000"]]})).is_err());
+ assert!(s.execute("gradient.presets.edit", json!({"action": "explode"})).is_err());
+}
+
+#[test]
+fn presets_persist_through_preferences_json() {
+ let mut s = Session::new();
+ s.execute("gradient.presets.new", json!({"name": "Saved", "stops": [[0, "#ff0000"], [1, "#0000ff"]]})).unwrap();
+ s.execute("tool.presets.new", json!({"name": "Big Brush", "tool": "brush", "options": {"brush": {"size": 300.0}}})).unwrap();
+ s.execute("shape.presets.new", json!({"name": "Tri", "path": "M 0 0 L 10 0 L 5 10 Z"})).unwrap();
+ s.execute("style.presets.edit", json!({"action": "deleteGroup", "group": "Buttons"})).unwrap();
+ let text = s.prefs_to_json();
+ let mut t = Session::new();
+ t.load_prefs_json(&text).unwrap();
+ let names = |t: &mut Session, cmd: &str, key: &str| -> Vec<String> {
+ let v = t.execute(cmd, json!({})).unwrap();
+ v["groups"].as_array().unwrap().iter().flat_map(|g| g[key].as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap().to_string()).collect::<Vec<_>>()).collect()
+ };
+ assert!(names(&mut t, "gradient.presets.list", "presets").contains(&"Saved".to_string()));
+ assert!(names(&mut t, "shape.presets.list", "shapes").contains(&"Tri".to_string()));
+ let styles = t.execute("style.presets.list", json!({})).unwrap();
+ assert!(!styles["groups"].as_array().unwrap().iter().any(|g| g["name"] == "Buttons"));
+ let tp = t.execute("tool.presets.list", json!({"tool": "Brush Tool"})).unwrap();
+ assert!(tp["presets"].as_array().unwrap().iter().any(|p| p["name"] == "Big Brush"));
+ // Older preference files without presets keep the defaults.
+ let mut u = Session::new();
+ u.load_prefs_json("{}").unwrap();
+ assert_eq!(names(&mut u, "gradient.presets.list", "presets").len(), Session::new().presets.gradients.iter().map(|g| g.items.len()).sum::<usize>());
+}
+
+// ------------------------------------------------------------------ patterns
+
+#[test]
+fn pattern_groups_select_apply_and_sync() {
+ let mut s = session(8);
+ let v = s.execute("pattern.presets.list", json!({})).unwrap();
+ let groups = v["groups"].as_array().unwrap();
+ assert_eq!(groups[0]["name"], "Geometric");
+ assert_eq!(groups[0]["patterns"].as_array().unwrap().len(), 4);
+ s.execute("pattern.presets.select", json!({"pattern": "Bricks"})).unwrap();
+ // Pattern fill layers and Fill default to the selected pattern.
+ let r = s.execute("pattern.presets.apply", json!({})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ let name_of = |s: &Session| match &s.active().unwrap().doc.layer(id).unwrap().content {
+ LayerContent::Fill(Fill::Pattern { name, .. }) => name.clone(),
+ _ => panic!(),
+ };
+ assert_eq!(name_of(&s), "Bricks");
+ let r = s.execute("pattern.presets.select", json!({"pattern": "Dots"})).unwrap();
+ assert_eq!(r["layer"], json!(id.0));
+ assert_eq!(name_of(&s), "Dots");
+ // A newly defined pattern lands in the trailing group, and can be moved / grouped.
+ let r = s.execute("pattern.presets.new", json!({"name": "Mine", "rect": [0, 0, 8, 8], "group": "Custom"})).unwrap();
+ let pid = r["pattern"].as_str().unwrap().to_string();
+ let v = s.execute("pattern.presets.list", json!({})).unwrap();
+ let custom = v["groups"].as_array().unwrap().iter().find(|g| g["name"] == "Custom").unwrap().clone();
+ assert_eq!(custom["patterns"][0]["id"], json!(pid));
+ s.execute("pattern.presets.edit", json!({"action": "move", "preset": "Mine", "to": "Geometric"})).unwrap();
+ s.execute("pattern.presets.edit", json!({"action": "rename", "preset": "Mine", "name": "Ours"})).unwrap();
+ s.execute("pattern.presets.edit", json!({"action": "delete", "preset": "Ours"})).unwrap();
+ let v = s.execute("pattern.presets.list", json!({})).unwrap();
+ assert_eq!(v["groups"][0]["patterns"].as_array().unwrap().len(), 4);
+ // Deleting a group deletes its patterns from the library.
+ s.execute("pattern.presets.edit", json!({"action": "deleteGroup", "group": "Textures"})).unwrap();
+ assert!(crate::pattern_cmds::resolve(&s, "Weave").is_none());
+}
+
+// ------------------------------------------------------------------ styles
+
+#[test]
+fn styles_apply_to_selected_layers_and_new_from_layer() {
+ let mut s = session(16);
+ let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().map(LayerId).unwrap_or_else(|| active(&s));
+ let b = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().map(LayerId).unwrap_or_else(|| active(&s));
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
+ let r = s.execute("style.presets.apply", json!({"preset": "Gold"})).unwrap();
+ assert_eq!(r["layers"].as_array().unwrap().len(), 2);
+ let fx = |s: &Session, id: LayerId| s.active().unwrap().doc.layer(id).unwrap().effects.items.len();
+ assert_eq!((fx(&s, a), fx(&s, b)), (3, 3));
+ // ⇧-click adds; plain apply replaces; Default Style clears.
+ s.execute("style.presets.apply", json!({"preset": "Black Stroke", "add": true, "layer": a.0})).unwrap();
+ assert_eq!(fx(&s, a), 4);
+ s.execute("style.presets.apply", json!({"preset": "Hollow", "layer": b.0})).unwrap();
+ let lb = s.active().unwrap().doc.layer(b).unwrap().clone();
+ assert_eq!((lb.effects.items.len(), lb.fill_opacity), (1, 0.0));
+ s.execute("style.presets.apply", json!({"preset": "Default Style (None)", "layer": b.0})).unwrap();
+ assert_eq!(s.active().unwrap().doc.layer(b).unwrap().fill_opacity, 1.0);
+ // One undo step per apply.
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(fx(&s, b), 1);
+ // New Style from the layer, applied elsewhere.
+ s.execute("layer.select", json!({"layer": a.0})).unwrap();
+ s.execute("style.presets.new", json!({"name": "From A", "group": "Mine"})).unwrap();
+ s.execute("style.presets.apply", json!({"preset": "From A", "layer": b.0})).unwrap();
+ assert_eq!(fx(&s, b), 4);
+ assert!(s.execute("style.presets.apply", json!({"preset": "nope"})).is_err());
+ // Thumbnails render the effect around the swatch.
+ let st = s.presets.styles[0].items.iter().find(|x| x.name == "Outer Glow").unwrap().clone();
+ let px = super::styles::thumbnail(&s, &st, 48);
+ assert_eq!(px.len(), 48 * 48 * 4);
+ assert!(px[(4 * 48 + 24) * 4 + 3] == 0 || px[(7 * 48 + 24) * 4 + 3] > 0, "glow reaches outside the square");
+ assert!(px[(24 * 48 + 24) * 4 + 3] == 255);
+}
+
+#[test]
+fn styles_with_pattern_overlay_copy_the_pattern() {
+ let mut s = session(8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let id = active(&s);
+ s.presets.styles[0].items.push(super::styles::StylePreset {
+ name: "Bricky".into(),
+ effects: vec![crate::layer_style::effect_from_params("patternOverlay", &json!({"pattern": "Bricks"})).unwrap()],
+ blend: None,
+ fill_opacity: None,
+ });
+ s.execute("style.presets.apply", json!({"preset": "Bricky", "layer": id.0})).unwrap();
+ assert!(s.active().unwrap().doc.patterns.iter().any(|p| p.name == "Bricks"));
+}
+
+// ------------------------------------------------------------------ shapes
+
+#[test]
+fn shape_path_language_parses() {
+ let p = super::shapes::parse("M 0 0 L 10 0 L 10 10 Z ! O 5 5 2").unwrap();
+ assert_eq!(p.subpaths.len(), 2);
+ assert_eq!(p.subpaths[0].knots.len(), 3);
+ assert_eq!(p.subpaths[1].op, photocraft_doc::vector::PathOp::Subtract);
+ assert!(super::shapes::parse("M 0 0 L x").is_err());
+ assert!(super::shapes::parse("").is_err());
+ assert!(super::shapes::parse("L 1 1").is_err());
+ // Every built-in parsed and has an area.
+ for g in super::shapes::builtin() {
+ assert!(!g.items.is_empty(), "{}", g.name);
+ for sh in g.items {
+ let cov = super::shapes::thumbnail(&sh.path, 32);
+ assert!(cov.iter().sum::<f32>() > 20.0, "{} is empty", sh.name);
+ }
+ }
+ let n: usize = super::shapes::builtin().iter().map(|g| g.items.len()).sum();
+ assert!(n >= 30, "{n}");
+}
+
+#[test]
+fn shapes_place_as_shape_layers() {
+ let mut s = session(8);
+ let r = s.execute("shape.presets.place", json!({"preset": "Heart", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ let l = s.active().unwrap().doc.layer(id).unwrap().clone();
+ assert_eq!(l.name, "Heart");
+ let LayerContent::Shape(sh) = &l.content else { panic!("not a shape layer") };
+ let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap();
+ // Keep aspect: 20 px tall, centred horizontally in the 40 px rect.
+ assert!((y0 - 10.0).abs() < 0.01 && (y1 - 30.0).abs() < 0.01, "{y0} {y1}");
+ // The heart's box is 100 × 92: 20 px tall → 21.7 px wide, centred on x = 30.
+ assert!(((x1 - x0) - 20.0 * 100.0 / 92.0).abs() < 0.05 && ((x0 + x1) / 2.0 - 30.0).abs() < 0.01, "{x0} {x1}");
+ // Free (dragged without ⇧) fills the rect; negative drags flip.
+ let r = s.execute("shape.presets.place", json!({"preset": "Arrow Right", "rect": [50, 40, -40, -20], "keepAspect": false})).unwrap();
+ let l = s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().clone();
+ let LayerContent::Shape(sh) = &l.content else { panic!() };
+ assert_eq!(sh.path.control_bounds().unwrap(), (10.0, 20.0, 50.0, 40.0));
+ // Default placement: centred, half the short side.
+ s.execute("shape.presets.place", json!({"preset": "Ring"})).unwrap();
+ assert!(s.execute("shape.presets.place", json!({"preset": "Unicorn"})).is_err());
+ assert!(s.execute("shape.presets.place", json!({"preset": "Heart", "rect": [0, 0, 0, 5]})).is_err());
+ // Undo removes the layer.
+ let n = s.active().unwrap().doc.layers.len();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().doc.layers.len(), n - 1);
+}
+
+#[test]
+fn custom_shapes_join_the_shapes_panel() {
+ let mut s = session(8);
+ s.execute("shape.create", json!({"kind": "star", "rect": [0, 0, 30, 30]})).unwrap();
+ s.execute("edit.defineCustomShape", json!({"name": "My Star"})).unwrap();
+ let v = s.execute("shape.presets.list", json!({})).unwrap();
+ let last = v["groups"].as_array().unwrap().last().unwrap().clone();
+ assert_eq!(last["name"], super::shapes::CUSTOM_GROUP);
+ s.execute("shape.presets.place", json!({"preset": "My Star"})).unwrap();
+ s.execute("shape.presets.edit", json!({"action": "rename", "preset": "My Star", "name": "Star 2"})).unwrap();
+ s.execute("shape.presets.edit", json!({"action": "delete", "preset": "Star 2"})).unwrap();
+ assert!(s.edit_state.custom_shapes.is_empty());
+ // New preset from the active shape layer, normalised to the 100 box.
+ s.execute("shape.presets.new", json!({"name": "From Layer", "group": "Mine"})).unwrap();
+ let g = s.presets.shapes.iter().find(|g| g.name == "Mine").unwrap();
+ let b = g.items[0].path.control_bounds().unwrap();
+ assert!(b.2.max(b.3) > 99.9);
+}
+
+// ------------------------------------------------------------------ tool presets
+
+#[test]
+fn tool_presets_save_filter_select() {
+ let mut s = Session::new();
+ s.execute("tools.setBrush", json!({"size": 77.0})).unwrap();
+ s.execute("tool.presets.new", json!({"name": "Seventy Seven", "tool": "brush", "includeColor": true, "options": {"toolOptions": {"x": 1}}})).unwrap();
+ s.execute("tools.setBrush", json!({"size": 5.0})).unwrap();
+ s.tools.foreground = [1.0, 0.0, 0.0, 1.0];
+ let v = s.execute("tool.presets.list", json!({"tool": "eraser"})).unwrap();
+ assert!(v["presets"].as_array().unwrap().iter().all(|p| p["tool"] == "eraser"));
+ let r = s.execute("tool.presets.select", json!({"preset": "Seventy Seven"})).unwrap();
+ assert_eq!(r["tool"], "brush");
+ assert_eq!(r["options"]["toolOptions"]["x"], 1);
+ // Options passed explicitly win over the current brush.
+ assert!(r["options"]["brush"].is_null() || r["options"]["brush"].is_object());
+ assert_eq!(s.tools.foreground, [0.0, 0.0, 0.0, 1.0]);
+ s.execute("tool.presets.new", json!({"name": "Eraser 77", "tool": "eraser"})).unwrap();
+ let r = s.execute("tool.presets.select", json!({"preset": "Eraser 77"})).unwrap();
+ // Selecting "Seventy Seven" restored its 77 px brush, which the new preset captured.
+ assert_eq!(r["options"]["brush"]["size"], json!(77.0));
+ s.execute("tool.presets.select", json!({"preset": "Soft Round 100 px"})).unwrap();
+ assert_eq!(s.tools.brush.size, 100.0);
+ s.execute("tool.presets.edit", json!({"action": "rename", "preset": "Eraser 77", "name": "E"})).unwrap();
+ s.execute("tool.presets.edit", json!({"action": "delete", "preset": "E"})).unwrap();
+ assert!(s.execute("tool.presets.select", json!({"preset": "E"})).is_err());
+ assert!(s.execute("tool.presets.edit", json!({"action": "newGroup"})).is_err());
+ assert!(s.execute("tool.presets.new", json!({"name": "x"})).is_err());
+}
+
+// ------------------------------------------------------------------ clone source
+
+fn clone_doc(depth: u32) -> Session {
+ let mut s = session(depth);
+ // A horizontal ramp in red, green = row, so transforms are measurable.
+ s.edit("ramp", |doc, _| {
+ let surf = doc.layers[0].surface_mut().unwrap();
+ let fmt = surf.format();
+ let mut px = Vec::new();
+ for y in 0..48 {
+ for x in 0..64 {
+ px.extend(photocraft_raster::from_rgba(&fmt, [x as f32 / 63.0, y as f32 / 47.0, 0.0, 1.0]));
+ }
+ }
+ surf.write_region(photocraft_geom::Rect::new(0, 0, 64, 48), &px);
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+#[test]
+fn clone_source_slots_and_identity_matches_offset() {
+ for depth in [8, 16, 32] {
+ let mut s = clone_doc(depth);
+ s.execute("cloneSource.set", json!({"index": 2, "source": [10, 10]})).unwrap();
+ let v = s.execute("cloneSource.list", json!({})).unwrap();
+ assert_eq!(v["active"], 2);
+ assert_eq!(v["sources"][2]["source"], json!([10.0, 10.0]));
+ // Stroke at (40, 30) without params samples the active slot: offset (−30, −20).
+ s.execute("paint.cloneStamp", json!({"points": [[40, 30]], "size": 5, "hardness": 100})).unwrap();
+ let px = layer_px(&s, 40, 30);
+ assert!((px[0] - 10.0 / 63.0).abs() < 0.01 && (px[1] - 10.0 / 47.0).abs() < 0.01, "depth {depth}: {px:?}");
+ // Aligned: the pairing stuck, the next stroke keeps the offset.
+ let v = s.execute("cloneSource.list", json!({})).unwrap();
+ assert_eq!(v["sources"][2]["offset"], json!([-30.0, -20.0]));
+ s.execute("paint.cloneStamp", json!({"points": [[50, 40]], "size": 3, "hardness": 100})).unwrap();
+ let px = layer_px(&s, 50, 40);
+ assert!((px[0] - 20.0 / 63.0).abs() < 0.01, "{px:?}");
+ }
+}
+
+#[test]
+fn clone_source_flip_scale_rotation() {
+ let mut s = clone_doc(16);
+ s.execute("cloneSource.set", json!({"source": [20, 20], "flipH": true})).unwrap();
+ s.execute("paint.cloneStamp", json!({"points": [[40, 24]], "size": 21, "hardness": 100})).unwrap();
+ // Flipped: 2 px right of the anchor samples 2 px left of the source.
+ let px = layer_px(&s, 42, 24);
+ assert!((px[0] - 18.0 / 63.0).abs() < 0.02, "{px:?}");
+ s.execute("cloneSource.resetTransform", json!({})).unwrap();
+ s.execute("cloneSource.set", json!({"source": [20, 20], "width": 200, "height": 200})).unwrap();
+ let mut s2 = clone_doc(16);
+ s2.presets.clone = s.presets.clone.clone();
+ s2.execute("paint.cloneStamp", json!({"points": [[40, 24]], "size": 21, "hardness": 100})).unwrap();
+ // 200 %: 4 px right of the anchor samples 2 px right of the source.
+ let px = layer_px(&s2, 44, 24);
+ assert!((px[0] - 22.0 / 63.0).abs() < 0.02, "{px:?}");
+ // Rotation 90° (counter-clockwise on screen): 3 px right of the anchor comes from 3 px
+ // below the source.
+ let mut s3 = clone_doc(32);
+ s3.execute("cloneSource.set", json!({"source": [20, 20], "rotation": 90})).unwrap();
+ s3.execute("paint.cloneStamp", json!({"points": [[40, 24]], "size": 21, "hardness": 100})).unwrap();
+ let px = layer_px(&s3, 43, 24);
+ assert!((px[0] - 20.0 / 63.0).abs() < 0.02 && (px[1] - 23.0 / 47.0).abs() < 0.02, "{px:?}");
+ // Explicit params override the slot; healing follows the slot too.
+ let mut s4 = clone_doc(8);
+ s4.execute("cloneSource.set", json!({"source": [20, 20], "rotation": 45})).unwrap();
+ s4.execute("paint.healingBrush", json!({"points": [[40, 24]], "size": 7})).unwrap();
+ s4.execute("paint.cloneStamp", json!({"points": [[10, 40]], "offset": [5, 0], "rotation": 0, "size": 3, "hardness": 100})).unwrap();
+ let px = layer_px(&s4, 10, 40);
+ assert!((px[0] - 15.0 / 63.0).abs() < 0.01, "{px:?}");
+}
+
+#[test]
+fn clone_source_errors_and_overlay() {
+ let mut s = clone_doc(8);
+ assert!(s.execute("paint.cloneStamp", json!({"points": [[4, 4]]})).is_err());
+ assert!(s.execute("cloneSource.select", json!({"index": 5})).is_err());
+ assert!(s.execute("cloneSource.set", json!({"offset": [1, 1]})).is_err());
+ let o = s.execute("cloneSource.overlay", json!({"opacity": 40, "clipped": false, "blend": "difference"})).unwrap();
+ assert_eq!(o["opacity"], json!(40.0));
+ assert!(s.execute("cloneSource.overlay", json!({"blend": "screen"})).is_err());
+ let v: Value = s.execute("cloneSource.set", json!({"source": [1, 1], "width": 5000, "rotation": 270})).unwrap();
+ assert_eq!(v["width"], json!(1000.0));
+ assert_eq!(v["rotation"], json!(-90.0));
+}
diff --git a/crates/engine/src/presets/tools.rs b/crates/engine/src/presets/tools.rs
new file mode 100644
index 000000000..25381d9f5
--- /dev/null
+++ b/crates/engine/src/presets/tools.rs
@@ -0,0 +1,129 @@
+//! Window › Tool Presets: a tool plus its options under a name.
+//!
+//! The engine doesn't know the shell's options-bar fields, so a preset's `options` are opaque
+//! JSON that the frontend writes and reads back (the desktop shell stores its `ToolOptions` under
+//! `"toolOptions"`). Two keys the engine understands itself: `"brush"` (brush settings, applied
+//! to the session brush like `tools.setBrush`) and `"foreground"` (Include Color).
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use super::{Group, Named, always, bad, edit_groups, req_str, str_param};
+use crate::commands::CommandSpec;
+use crate::{Result, Session};
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ToolPreset {
+ pub name: String,
+ /// Tool name as the shell spells it (`"brush"`, `"eraser"`, `"gradient"`, …), case-insensitive.
+ pub tool: String,
+ #[serde(default)]
+ pub options: Value,
+}
+
+impl Named for ToolPreset {
+ fn name(&self) -> &str {
+ &self.name
+ }
+ fn set_name(&mut self, n: String) {
+ self.name = n;
+ }
+}
+
+fn norm(t: &str) -> String {
+ t.to_ascii_lowercase().replace([' ', '_', '-'], "").trim_end_matches("tool").to_string()
+}
+
+/// A few starting presets (our own).
+pub fn builtin() -> Vec<ToolPreset> {
+ let brush = |size: f32, hardness: f32| json!({"brush": {"size": size, "hardness": hardness}});
+ vec![
+ ToolPreset { name: "Soft Round 100 px".into(), tool: "brush".into(), options: brush(100.0, 0.0) },
+ ToolPreset { name: "Hard Round 12 px".into(), tool: "brush".into(), options: brush(12.0, 1.0) },
+ ToolPreset { name: "Soft Eraser 60 px".into(), tool: "eraser".into(), options: brush(60.0, 0.0) },
+ ToolPreset { name: "Radial Gradient".into(), tool: "gradient".into(), options: json!({"toolOptions": {"gradient_style": "radial"}}) },
+ ToolPreset { name: "Clone Soft 40 px".into(), tool: "cloneStamp".into(), options: brush(40.0, 0.2) },
+ ]
+}
+
+fn list(s: &mut Session, p: &Value) -> Result<Value> {
+ let filter = str_param(p, "tool").map(norm);
+ let items: Vec<Value> = s.presets.tool_presets.iter().filter(|t| filter.as_ref().is_none_or(|f| norm(&t.tool) == *f)).map(|t| json!({"name": t.name, "tool": t.tool})).collect();
+ Ok(json!({"presets": items}))
+}
+
+fn new_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "tool.presets.new";
+ let tool = req_str(p, "tool", CMD)?.to_string();
+ let mut options = p.get("options").cloned().unwrap_or_else(|| json!({}));
+ if !options.is_object() {
+ return Err(bad(CMD, "`options` must be an object"));
+ }
+ // Brush-based tools carry the current brush unless the caller sent one.
+ let brushy = ["brush", "pencil", "eraser", "clonestamp", "healing", "spothealing", "historybrush", "blur", "sharpen", "smudge", "dodge", "burn", "sponge", "mixerbrush", "colorreplacement"];
+ if options.get("brush").is_none() && brushy.contains(&norm(&tool).as_str()) {
+ options["brush"] = serde_json::to_value(&s.tools.brush).unwrap_or(Value::Null);
+ }
+ if p.get("includeColor").and_then(Value::as_bool).unwrap_or(false) {
+ let f = s.tools.foreground;
+ options["foreground"] = json!(f);
+ }
+ let groups = [Group::new("", s.presets.tool_presets.clone())];
+ let name = super::unique_name(&groups, str_param(p, "name").unwrap_or(&tool));
+ s.presets.tool_presets.push(ToolPreset { name: name.clone(), tool: tool.clone(), options });
+ s.presets_changed();
+ Ok(json!({"name": name, "tool": tool}))
+}
+
+fn select(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "tool.presets.select";
+ let name = req_str(p, "preset", CMD)?;
+ let t = s.presets.tool_presets.iter().find(|t| t.name == name).cloned().ok_or_else(|| bad(CMD, format!("no tool preset \"{name}\" (see tool.presets.list)")))?;
+ if let Some(b) = t.options.get("brush").filter(|b| b.is_object()) {
+ super::call(s, "tools.setBrush", json!({"brush": b}))?;
+ }
+ if let Some(c) = t.options.get("foreground").and_then(Value::as_array).filter(|a| a.len() >= 3) {
+ let v: Vec<f32> = c.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
+ s.tools.foreground = [v[0], v[1], v[2], v.get(3).copied().unwrap_or(1.0)];
+ }
+ Ok(json!({"name": t.name, "tool": t.tool, "options": t.options}))
+}
+
+fn edit(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "tool.presets.edit";
+ let action = req_str(p, "action", CMD)?.to_string();
+ if !matches!(action.as_str(), "rename" | "delete") {
+ return Err(bad(CMD, "tool presets support rename and delete"));
+ }
+ let mut groups = vec![Group::new("", std::mem::take(&mut s.presets.tool_presets))];
+ let r = edit_groups(&mut groups, &action, p, CMD);
+ s.presets.tool_presets = groups.pop().map(|g| g.items).unwrap_or_default();
+ let r = r?;
+ s.presets_changed();
+ Ok(r)
+}
+
+fn reset(s: &mut Session, _: &Value) -> Result<Value> {
+ s.presets.tool_presets = builtin();
+ s.presets_changed();
+ Ok(json!({"presets": s.presets.tool_presets.len()}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec { id: "tool.presets.list", label: "Tool Presets", menu: &[], shortcut: None, params: r##"{"tool":name? (Current Tool Only)} → {presets:[{name,tool}]}"##, enabled: always, run: list, journal: false },
+ CommandSpec {
+ id: "tool.presets.new",
+ label: "New Tool Preset…",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"name":str?=tool,"tool":name,"options":{…}? (opaque; "brush" defaults to the current brush for painting tools),"includeColor":bool=false}"##,
+ enabled: always,
+ run: new_preset,
+ journal: true,
+ },
+ CommandSpec { id: "tool.presets.select", label: "Select Tool Preset", menu: &[], shortcut: None, params: r##"{"preset":name} → {name,tool,options} (applies "brush" and "foreground"; the shell switches tool and options)"##, enabled: always, run: select, journal: true },
+ CommandSpec { id: "tool.presets.edit", label: "Edit Tool Presets", menu: &[], shortcut: None, params: r##"{"action":"rename|delete","preset":name|[names],"name":str (rename)}"##, enabled: always, run: edit, journal: true },
+ CommandSpec { id: "tool.presets.reset", label: "Reset Tool Presets", menu: &[], shortcut: None, params: "{}", enabled: always, run: reset, journal: true },
+ ]
+}
diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs
new file mode 100644
index 000000000..846876a3b
--- /dev/null
+++ b/crates/engine/src/print_cmds.rs
@@ -0,0 +1,519 @@
+//! File › Print…, Print One Copy, File › Package… and File › Export › Paths to Illustrator….
+//!
+//! Printing renders the flattened document into a PDF page (paper size, orientation, position,
+//! scale, colour handling with printer profile / intent / black-point compensation, corner and
+//! centre crop marks, registration marks, description and label) with a small PDF writer
+//! (ISO 32000: one page, a Flate-compressed image XObject, vector marks, Helvetica text), then
+//! hands it to the system spooler with `lp` (CUPS, macOS and Linux). `"dryRun": true` stops
+//! before spooling and reports the command line, which is how the tests exercise the path.
+//!
+//! Paths to Illustrator writes the document's paths as an Adobe Illustrator 3 compatible
+//! PostScript file (`m`/`L`/`C` path construction, `n`/`N` unpainted closed/open paths, `*u`/`*U`
+//! compound paths), following the public PostScript Language Reference and the AI3 format notes.
+
+use std::io::Write as _;
+
+use photocraft_color::ColorMode;
+use photocraft_doc::{Document, LayerContent, SmartSource};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::file_cmds::{file_name, join, native_doc, read_file, stem, write_file};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+fn other(e: impl std::fmt::Display) -> EngineError {
+ EngineError::Other(e.to_string())
+}
+
+// ---------- PDF ----------
+
+/// Paper sizes in points (portrait).
+pub const PAPERS: [(&str, f64, f64); 8] = [("letter", 612.0, 792.0), ("legal", 612.0, 1008.0), ("tabloid", 792.0, 1224.0), ("a3", 841.89, 1190.55), ("a4", 595.28, 841.89), ("a5", 419.53, 595.28), ("4x6", 288.0, 432.0), ("5x7", 360.0, 504.0)];
+
+/// The image placed on a print page.
+pub struct PrintImage {
+ pub width: u32,
+ pub height: u32,
+ /// 1 (gray), 3 (RGB) or 4 (CMYK, 1 = full ink), 8-bit interleaved.
+ pub channels: usize,
+ pub data: Vec<u8>,
+ pub icc: Option<Vec<u8>>,
+}
+
+/// Printer marks around the image.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Marks {
+ pub corner_crop: bool,
+ pub center_crop: bool,
+ pub registration: bool,
+}
+
+/// One page: paper (pt), image box (pt, origin bottom-left), marks and texts.
+pub struct PrintPage {
+ pub paper: (f64, f64),
+ pub image: PrintImage,
+ pub rect: (f64, f64, f64, f64),
+ pub marks: Marks,
+ pub description: Option<String>,
+ pub label: Option<String>,
+}
+
+fn pdf_string(s: &str) -> String {
+ let mut o = String::from("(");
+ for c in s.chars() {
+ match c {
+ '(' | ')' | '\\' => {
+ o.push('\\');
+ o.push(c);
+ }
+ c if c.is_ascii() && !c.is_ascii_control() => o.push(c),
+ _ => o.push('?'),
+ }
+ }
+ o.push(')');
+ o
+}
+
+fn deflate(data: &[u8]) -> Vec<u8> {
+ // Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default.
+ let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
+ let _ = e.write_all(data);
+ e.finish().unwrap_or_default()
+}
+
+/// Vector marks around `(x, y, w, h)`.
+fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String {
+ let mut s = String::from("q 0 G 0.3 w\n");
+ let (gap, len) = (6.0, 18.0);
+ let line = |s: &mut String, x0: f64, y0: f64, x1: f64, y1: f64| s.push_str(&format!("{x0:.2} {y0:.2} m {x1:.2} {y1:.2} l S\n"));
+ if m.corner_crop {
+ for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] {
+ line(&mut s, cx + dx * gap, cy, cx + dx * (gap + len), cy);
+ line(&mut s, cx, cy + dy * gap, cx, cy + dy * (gap + len));
+ }
+ }
+ if m.center_crop {
+ let (mx, my) = (x + w / 2.0, y + h / 2.0);
+ line(&mut s, mx, y - gap, mx, y - gap - len);
+ line(&mut s, mx, y + h + gap, mx, y + h + gap + len);
+ line(&mut s, x - gap, my, x - gap - len, my);
+ line(&mut s, x + w + gap, my, x + w + gap + len, my);
+ }
+ if m.registration {
+ let r = 5.0;
+ let off = gap + len / 2.0;
+ for (cx, cy) in [(x + w / 2.0, y - off), (x + w / 2.0, y + h + off), (x - off, y + h / 2.0), (x + w + off, y + h / 2.0)] {
+ // Circle (four Béziers) plus crosshair.
+ let k = 0.5523 * r;
+ s.push_str(&format!(
+ "{:.2} {cy:.2} m {:.2} {:.2} {:.2} {:.2} {cx:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {cy:.2} c {:.2} {:.2} {:.2} {:.2} {cx:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {cy:.2} c S\n",
+ cx + r, cx + r, cy + k, cx + k, cy + r, cy + r, cx - k, cy + r, cx - r, cy + k, cx - r, cx - r, cy - k, cx - k, cy - r, cy - r, cx + k, cy - r, cx + r, cy - k, cx + r
+ ));
+ line(&mut s, cx - r * 1.6, cy, cx + r * 1.6, cy);
+ line(&mut s, cx, cy - r * 1.6, cx, cy + r * 1.6);
+ }
+ }
+ s.push_str("Q\n");
+ s
+}
+
+/// A one-page PDF.
+pub fn print_pdf(page: &PrintPage) -> Vec<u8> {
+ let mut out: Vec<u8> = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec();
+ let mut offsets: Vec<usize> = Vec::new();
+ let mut obj = |out: &mut Vec<u8>, body: &[u8]| {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n", offsets.len()).as_bytes());
+ out.extend_from_slice(body);
+ out.extend_from_slice(b"\nendobj\n");
+ };
+ let img = &page.image;
+ let (pw, ph) = page.paper;
+ let (x, y, w, h) = page.rect;
+ // 1 catalog, 2 pages, 3 page, 4 contents, 5 image, 6 font, 7 ICC (optional).
+ obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>");
+ obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
+ obj(&mut out, format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R >> >> /Contents 4 0 R >>").as_bytes());
+ let mut content = format!("q {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n");
+ content.push_str(&marks_ops(page.marks, page.rect));
+ let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration;
+ let pad = if any_marks { 30.0 } else { 6.0 };
+ if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) {
+ content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l)));
+ }
+ if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) {
+ content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d)));
+ }
+ let c = deflate(content.as_bytes());
+ let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes();
+ body.extend_from_slice(&c);
+ body.extend_from_slice(b"\nendstream");
+ obj(&mut out, &body);
+ let device = match img.channels {
+ 1 => "/DeviceGray",
+ 4 => "/DeviceCMYK",
+ _ => "/DeviceRGB",
+ };
+ let cs = if img.icc.is_some() { "[/ICCBased 7 0 R]".to_string() } else { device.to_string() };
+ let z = deflate(&img.data);
+ let mut body = format!("<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", img.width, img.height, z.len()).into_bytes();
+ body.extend_from_slice(&z);
+ body.extend_from_slice(b"\nendstream");
+ obj(&mut out, &body);
+ obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>");
+ if let Some(icc) = &img.icc {
+ let z = deflate(icc);
+ let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes();
+ body.extend_from_slice(&z);
+ body.extend_from_slice(b"\nendstream");
+ obj(&mut out, &body);
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
+ for o in &offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
+ out
+}
+
+// ---------- Print ----------
+
+/// The flattened, colour-handled document as 8-bit samples in its print colour space.
+fn print_image(doc: &Document, p: &Value, cmd: &str) -> Result<(PrintImage, Value)> {
+ let mut t = Session::new();
+ t.add_document(doc.clone(), None);
+ let handling = p.get("colorHandling").and_then(Value::as_str).unwrap_or("printerManages");
+ let mut info = json!({"colorHandling": handling});
+ if !matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk) {
+ t.execute("image.mode.rgb", json!({}))?;
+ }
+ match handling {
+ "photocraftManages" | "photoshopManages" => {
+ let profile = p.get("printerProfile").and_then(Value::as_str).ok_or_else(|| bad(cmd, "\"photocraftManages\" needs a \"printerProfile\""))?;
+ let intent = p.get("intent").and_then(Value::as_str).unwrap_or("relative");
+ let bpc = p.get("bpc").and_then(Value::as_bool).unwrap_or(true);
+ t.execute("edit.convertToProfile", json!({"profile": profile, "intent": intent, "bpc": bpc}))?;
+ info["printerProfile"] = json!(profile);
+ info["intent"] = json!(intent);
+ info["bpc"] = json!(bpc);
+ }
+ "printerManages" | "noColorManagement" => {}
+ "separations" => return Err(bad(cmd, "Separations printing is not supported; use photocraftManages with a CMYK printer profile")),
+ h => return Err(bad(cmd, format!("unknown colorHandling `{h}` (printerManages|photocraftManages|noColorManagement)"))),
+ }
+ let d = &t.active().ok_or(EngineError::NoDocument)?.doc;
+ let icc = if handling == "noColorManagement" { None } else { d.icc_profile.as_ref().map(|v| v.to_vec()) };
+ // RGB and Grayscale: the composite over white is the print image (no layer flatten).
+ if matches!(d.mode, ColorMode::Rgb | ColorMode::Grayscale) {
+ let gray = d.mode == ColorMode::Grayscale;
+ let buf = photocraft_compose::flatten(d).over_background([1.0, 1.0, 1.0]);
+ let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ let data: Vec<u8> = if gray { buf.px.iter().map(|p| to8(p[0])).collect() } else { buf.px.iter().flat_map(|p| [to8(p[0]), to8(p[1]), to8(p[2])]).collect() };
+ return Ok((PrintImage { width: d.size.width, height: d.size.height, channels: if gray { 1 } else { 3 }, data, icc }, info));
+ }
+ t.execute("layer.flattenImage", json!({}))?;
+ let d = &t.active().ok_or(EngineError::NoDocument)?.doc;
+ let fmt = d.pixel_format();
+ let k = fmt.mode.color_channels();
+ let n = fmt.channels();
+ let surf = d.layers.first().and_then(|l| l.surface()).ok_or_else(|| other("nothing to print"))?;
+ let vals = surf.read_region(d.bounds());
+ let mut data = Vec::with_capacity(vals.len() / n * k);
+ for px in vals.chunks_exact(n) {
+ for v in &px[..k] {
+ data.push((v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ }
+ }
+ Ok((PrintImage { width: d.size.width, height: d.size.height, channels: k, data, icc }, info))
+}
+
+fn paper(p: &Value, cmd: &str) -> Result<(f64, f64)> {
+ let (w, h) = match p.get("paper") {
+ None => (612.0, 792.0),
+ Some(Value::String(name)) => PAPERS.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(name)).map(|(_, w, h)| (*w, *h)).ok_or_else(|| bad(cmd, format!("unknown paper `{name}` ({})", PAPERS.map(|p| p.0).join("|"))))?,
+ Some(Value::Array(a)) if a.len() == 2 => (a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0)),
+ _ => return Err(bad(cmd, "paper is a name or [width, height] in points")),
+ };
+ if !(w > 36.0 && h > 36.0) {
+ return Err(bad(cmd, "paper is too small"));
+ }
+ Ok(if p.get("orientation").and_then(Value::as_str) == Some("landscape") { (h.max(w), w.min(h)) } else { (w, h) })
+}
+
+/// Where the image lands on the paper.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PrintLayout {
+ /// Paper size in points (after orientation).
+ pub paper: (f64, f64),
+ /// Image box in points, origin bottom-left.
+ pub rect: (f64, f64, f64, f64),
+ /// Print scale (1.0 = 100 %).
+ pub scale: f64,
+ pub marks: Marks,
+}
+
+/// The print layout for `doc` with Print parameters `p` (used by the dialog's preview too).
+pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result<PrintLayout> {
+ let (pw, ph) = paper(p, cmd)?;
+ let dpi = f64::from(doc.resolution_dpi.max(1.0));
+ let (iw, ih) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi);
+ let marks = Marks {
+ corner_crop: p.get("cornerCropMarks").and_then(Value::as_bool).unwrap_or(false),
+ center_crop: p.get("centerCropMarks").and_then(Value::as_bool).unwrap_or(false),
+ registration: p.get("registrationMarks").and_then(Value::as_bool).unwrap_or(false),
+ };
+ let margin = if marks.corner_crop || marks.center_crop || marks.registration { 36.0 } else { 18.0 };
+ let fit = p.get("scaleToFit").and_then(Value::as_bool).unwrap_or(false);
+ let scale = if fit { ((pw - 2.0 * margin) / iw).min((ph - 2.0 * margin) / ih) } else { p.get("scale").and_then(Value::as_f64).filter(|v| *v > 0.0).unwrap_or(100.0) / 100.0 };
+ let (w, h) = (iw * scale, ih * scale);
+ let center = p.get("center").and_then(Value::as_bool).unwrap_or(true);
+ let (x, y) = if center {
+ ((pw - w) / 2.0, (ph - h) / 2.0)
+ } else {
+ // Top / left in inches from the paper's top-left corner (Photoshop's Position fields).
+ let top = p.get("top").and_then(Value::as_f64).unwrap_or(0.0) * 72.0;
+ let left = p.get("left").and_then(Value::as_f64).unwrap_or(0.0) * 72.0;
+ (left, ph - top - h)
+ };
+ Ok(PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks })
+}
+
+/// Lays out, renders and (unless dry-run) spools a print. Shared by Print and Print One Copy.
+fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks } = layout(&doc, p, cmd)?;
+ let (img, color) = print_image(&doc, p, cmd)?;
+ let description = p.get("description").and_then(Value::as_bool).unwrap_or(false).then(|| crate::file_cmds::read_file_info(doc.metadata.xmp.as_deref())["description"].as_str().unwrap_or_default().to_string());
+ let label = p.get("labels").and_then(Value::as_bool).unwrap_or(false).then(|| doc.name.clone());
+ let page = PrintPage { paper: (pw, ph), image: img, rect: (x, y, w, h), marks, description, label };
+ let pdf = print_pdf(&page);
+ let output = p.get("output").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string);
+ let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none());
+ let pdf_path = match &output {
+ Some(o) => o.clone(),
+ None => {
+ let tmp = std::env::temp_dir().to_string_lossy().into_owned();
+ join(&tmp, &format!("{}-print-{}.pdf", crate::file_cmds::sanitize(&stem(&doc.name)), std::process::id()))
+ }
+ };
+ write_file(&pdf_path, &pdf)?;
+ let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1).clamp(1, 999);
+ let mut argv: Vec<String> = vec!["lp".into()];
+ if let Some(pr) = p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()) {
+ argv.extend(["-d".into(), pr.to_string()]);
+ }
+ if copies > 1 {
+ argv.extend(["-n".into(), copies.to_string()]);
+ }
+ argv.extend(["-t".into(), doc.name.clone(), pdf_path.clone()]);
+ let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
+ let mut sent = false;
+ let mut spool = Value::Null;
+ if send && !dry {
+ spool = json!(spool_pdf(&argv)?);
+ sent = true;
+ }
+ let mut remembered = p.clone();
+ if let Some(o) = remembered.as_object_mut() {
+ o.remove("output");
+ o.remove("dryRun");
+ }
+ s.file_menu.last_print = Some(remembered);
+ crate::automate_cmds::fire_event(s, "print");
+ Ok(json!({"pdf": pdf_path, "bytes": pdf.len(), "paper": [pw, ph], "imageRect": [x, y, w, h], "scale": scale * 100.0, "copies": copies, "command": if send { json!(argv) } else { Value::Null }, "sent": sent, "spooler": spool, "color": color}))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn spool_pdf(argv: &[String]) -> Result<String> {
+ let out = std::process::Command::new(&argv[0]).args(&argv[1..]).output().map_err(|e| other(format!("could not run `lp` (CUPS): {e}")))?;
+ if !out.status.success() {
+ return Err(other(format!("lp failed: {}", String::from_utf8_lossy(&out.stderr).trim())));
+ }
+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
+}
+#[cfg(target_arch = "wasm32")]
+fn spool_pdf(_: &[String]) -> Result<String> {
+ Err(other("printing needs the desktop app"))
+}
+
+fn print(s: &mut Session, p: &Value) -> Result<Value> {
+ do_print(s, p, "file.print")
+}
+
+fn print_one_copy(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut q = s.file_menu.last_print.clone().unwrap_or_else(|| json!({}));
+ if let (Some(o), Some(extra)) = (q.as_object_mut(), p.as_object()) {
+ for (k, v) in extra {
+ o.insert(k.clone(), v.clone());
+ }
+ }
+ q["copies"] = json!(1);
+ do_print(s, &q, "file.printOneCopy")
+}
+
+// ---------- Package ----------
+
+fn package(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.package";
+ let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| bad(cmd, "missing \"dir\" (where to create the package folder)"))?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = (*d.doc).clone();
+ let name = stem(&d.path.clone().unwrap_or_else(|| doc.name.clone()));
+ // The native format keeps external links; our PSD writer has no `lnkE` (external linked
+ // file) support yet, so a PSD package would embed or flatten them.
+ let ext = match p.get("format").and_then(Value::as_str) {
+ Some(f @ ("psd" | "psb" | "pcraft")) => f.to_string(),
+ Some(f) => return Err(bad(cmd, format!("unknown package format `{f}` (pcraft|psd|psb)"))),
+ None => "pcraft".into(),
+ };
+ let folder = join(dir, &crate::file_cmds::sanitize(&name));
+ let links_dir = join(&folder, "Links");
+ // Copy every linked file once; relink the copy of the document to the copies.
+ let mut copied: Vec<(String, String)> = Vec::new();
+ let mut relinks: Vec<(photocraft_doc::LayerId, String)> = Vec::new();
+ let mut missing = Vec::new();
+ for (_, _, l) in doc.walk() {
+ let LayerContent::Smart(so) = &l.content else { continue };
+ let SmartSource::Linked { path } = &so.source else { continue };
+ let target = match copied.iter().find(|(src, _)| src == path) {
+ Some((_, t)) => t.clone(),
+ None => {
+ let mut fname = file_name(path);
+ if copied.iter().any(|(_, t)| file_name(t) == fname) {
+ fname = format!("{}-{}", copied.len(), fname);
+ }
+ let t = join(&links_dir, &fname);
+ match read_file(path) {
+ Ok(bytes) => {
+ write_file(&t, &bytes)?;
+ copied.push((path.clone(), t.clone()));
+ t
+ }
+ Err(_) => {
+ missing.push(path.clone());
+ continue;
+ }
+ }
+ }
+ };
+ relinks.push((l.id, target));
+ }
+ let mut t = Session::new();
+ t.add_document(doc, None);
+ for (id, path) in &relinks {
+ t.execute("layer.smartObjects.relinkToFile", json!({"layer": id.0, "path": path}))?;
+ }
+ let out = join(&folder, &format!("{}.{ext}", crate::file_cmds::sanitize(&name)));
+ let pdoc = t.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let warnings = crate::file_cmds::save_doc(&pdoc, &out, None)?;
+ Ok(json!({"folder": folder, "document": out, "links": copied.iter().map(|(_, t)| t).collect::<Vec<_>>(), "missing": missing, "warnings": warnings}))
+}
+
+// ---------- Paths to Illustrator ----------
+
+/// The document's paths as an Illustrator 3 PostScript file. `which`: "all", "work" or a path
+/// name. Coordinates are points (pixels at the document resolution), y up.
+pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> {
+ let dpi = f64::from(doc.resolution_dpi.max(1.0));
+ let k = 72.0 / dpi;
+ let (w, h) = (f64::from(doc.size.width) * k, f64::from(doc.size.height) * k);
+ let mut chosen: Vec<(String, &photocraft_doc::Path)> = Vec::new();
+ match which {
+ "all" => {
+ chosen.extend(doc.paths.iter().map(|p| (p.name.clone(), &p.path)));
+ if let Some(wp) = &doc.work_path {
+ chosen.push(("Work Path".into(), wp));
+ }
+ }
+ "work" => chosen.extend(doc.work_path.iter().map(|wp| ("Work Path".to_string(), wp))),
+ name => chosen.extend(doc.paths.iter().filter(|p| p.name == name).map(|p| (p.name.clone(), &p.path))),
+ }
+ let mut s = String::new();
+ s.push_str("%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: PhotoCraft\n");
+ s.push_str(&format!("%%Title: ({})\n", doc.name.replace([')', '('], "_")));
+ s.push_str(&format!("%%BoundingBox: 0 0 {} {}\n%%HiResBoundingBox: 0 0 {w:.4} {h:.4}\n%AI3_Cropmarks: 0 0 {w:.4} {h:.4}\n", w.ceil() as i64, h.ceil() as i64));
+ s.push_str("%%DocumentProcessColors: Black\n%%EndComments\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n");
+ let pt = |x: f64, y: f64| (x * k, h - y * k);
+ let mut n = 0;
+ for (name, path) in &chosen {
+ let subs: Vec<_> = path.subpaths.iter().filter(|sp| !sp.knots.is_empty()).collect();
+ if subs.is_empty() {
+ continue;
+ }
+ n += 1;
+ s.push_str(&format!("%%Note: {name}\n"));
+ let compound = subs.len() > 1;
+ if compound {
+ s.push_str("*u\n");
+ }
+ for sp in subs {
+ let (x, y) = pt(sp.knots[0].anchor.x, sp.knots[0].anchor.y);
+ s.push_str(&format!("{x:.4} {y:.4} m\n"));
+ for seg in sp.segments() {
+ let [a, c1, c2, b] = seg;
+ let straight = c1 == a && c2 == b;
+ let (bx, by) = pt(b.x, b.y);
+ if straight {
+ s.push_str(&format!("{bx:.4} {by:.4} L\n"));
+ } else {
+ let (x1, y1) = pt(c1.x, c1.y);
+ let (x2, y2) = pt(c2.x, c2.y);
+ s.push_str(&format!("{x1:.4} {y1:.4} {x2:.4} {y2:.4} {bx:.4} {by:.4} C\n"));
+ }
+ }
+ // Unpainted: `n` closes the path, `N` leaves it open.
+ s.push_str(if sp.closed { "n\n" } else { "N\n" });
+ }
+ if compound {
+ s.push_str("*U\n");
+ }
+ }
+ s.push_str("%%PageTrailer\n%%Trailer\n%%EOF\n");
+ Ok((s, n))
+}
+
+fn paths_to_illustrator(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.pathsToIllustrator";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let which = p.get("paths").and_then(Value::as_str).unwrap_or("all");
+ let (text, n) = paths_to_ai(&d.doc, which)?;
+ if n == 0 {
+ return Err(bad(cmd, format!("no paths match `{which}`")));
+ }
+ match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) {
+ Some(path) => {
+ write_file(path, text.as_bytes())?;
+ Ok(json!({"path": path, "paths": n}))
+ }
+ None => Ok(json!({"ai": text, "paths": n})),
+ }
+}
+
+fn has_paths(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.paths.is_empty() && d.doc.work_path.is_none() { Err("the document has no paths".into()) } else { Ok(()) }
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the lp command, don't spool)} → {pdf, imageRect, command, sent}"##;
+ vec![
+ spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print),
+ spec!("file.printOneCopy", "Print One Copy", &["File"], Some("Cmd+Alt+Shift+P"), "{} (the last Print settings, one copy; any Print key overrides)", native_doc, print_one_copy),
+ spec!("file.package", "Package…", &["File"], None, r##"{"dir":folder,"format":"pcraft|psd|psb"="pcraft"} → {folder, document, links, missing} (copies the document and its linked files into <dir>/<name>/, relinked to Links/)"##, native_doc, package),
+ spec!("file.export.pathsToIllustrator", "Paths to Illustrator…", &["File", "Export"], None, r##"{"path":str? (.ai; omit to return the text),"paths":"all|work|<path name>"="all"} → {path, paths}"##, has_paths, paths_to_illustrator),
+ ]
+}
+
+#[cfg(test)]
+#[path = "print_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs
new file mode 100644
index 000000000..3bb3b4cca
--- /dev/null
+++ b/crates/engine/src/print_cmds/tests.rs
@@ -0,0 +1,157 @@
+use super::*;
+use photocraft_doc::{Knot, NamedPath, Path, Subpath};
+
+fn tmp(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("photocraft-print-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d.to_string_lossy().into_owned()
+}
+
+fn session(mode: &str, depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 300, "height": 150, "mode": mode, "depth": depth, "name": "Print Me.psd", "background": "#3366cc"})).unwrap();
+ s
+}
+
+fn find(h: &[u8], n: &[u8], from: usize) -> usize {
+ from + h[from..].windows(n.len()).position(|w| w == n).unwrap()
+}
+
+/// The (inflated) image stream of a print PDF: (width, height, colour space, samples).
+fn pdf_image(pdf: &[u8]) -> (u32, u32, String, Vec<u8>) {
+ let i = find(pdf, b"/Subtype /Image", 0);
+ let end = find(pdf, b">>\nstream\n", i);
+ let dict = String::from_utf8_lossy(&pdf[i..end]).into_owned();
+ let num = |k: &str| dict.split(k).nth(1).unwrap().split_whitespace().next().unwrap().parse::<u32>().unwrap();
+ let cs = dict.split("/ColorSpace ").nth(1).unwrap().split(" /BitsPerComponent").next().unwrap().to_string();
+ let len = num("/Length ") as usize;
+ let start = end + 10;
+ let mut out = Vec::new();
+ std::io::Read::read_to_end(&mut flate2::read::ZlibDecoder::new(&pdf[start..start + len]), &mut out).unwrap();
+ (num("/Width "), num("/Height "), cs, out)
+}
+
+#[test]
+fn print_dry_run_renders_a_pdf_and_reports_lp() {
+ let dir = tmp("print");
+ for depth in [8, 16, 32] {
+ let mut s = session("rgb", depth);
+ let r = s.execute("file.print", json!({"dryRun": true, "printer": "Office", "copies": 2, "paper": "a4", "cornerCropMarks": true, "registrationMarks": true, "labels": true})).unwrap();
+ let cmd: Vec<String> = serde_json::from_value(r["command"].clone()).unwrap();
+ assert_eq!(&cmd[..5], &["lp", "-d", "Office", "-n", "2"]);
+ assert_eq!(r["sent"], false);
+ let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap();
+ assert!(pdf.starts_with(b"%PDF-1.4"));
+ assert!(String::from_utf8_lossy(&pdf).contains("/MediaBox [0 0 595.28 841.89]"));
+ let (w, h, cs, data) = pdf_image(&pdf);
+ assert_eq!((w, h), (300, 150));
+ assert_eq!(cs, "/DeviceRGB");
+ assert_eq!(&data[..3], &[0x33, 0x66, 0xcc]);
+ // 300 px at 72 ppi = 300 pt, centred.
+ let rect: Vec<f64> = serde_json::from_value(r["imageRect"].clone()).unwrap();
+ assert!((rect[2] - 300.0).abs() < 1e-6 && (rect[0] - (595.28 - 300.0) / 2.0).abs() < 1e-6);
+ let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
+ }
+ // Print to PDF: no spooling by default.
+ let mut s = session("gray", 8);
+ let out = format!("{dir}/out.pdf");
+ let r = s.execute("file.print", json!({"output": out, "scaleToFit": true, "orientation": "landscape"})).unwrap();
+ assert_eq!(r["sent"], false);
+ assert!(r["command"].is_null());
+ let (_, _, cs, _) = pdf_image(&std::fs::read(&out).unwrap());
+ assert_eq!(cs, "/DeviceGray");
+ let scale = r["scale"].as_f64().unwrap();
+ assert!(scale > 200.0, "fit to a landscape letter page: {scale}");
+ assert!(s.execute("file.print", json!({"paper": "napkin", "dryRun": true})).is_err());
+ assert!(s.execute("file.print", json!({"colorHandling": "photocraftManages", "dryRun": true})).is_err(), "needs a printer profile");
+}
+
+#[test]
+fn photocraft_manages_colors_converts_to_the_printer_profile() {
+ let mut s = session("rgb", 8);
+ let r = s.execute("file.print", json!({"dryRun": true, "colorHandling": "photocraftManages", "printerProfile": "coated-cmyk", "intent": "perceptual", "bpc": false})).unwrap();
+ assert_eq!(r["color"]["intent"], "perceptual");
+ let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap();
+ let (_, _, cs, data) = pdf_image(&pdf);
+ assert_eq!(cs, "[/ICCBased 7 0 R]");
+ assert!(String::from_utf8_lossy(&pdf).contains("/N 4 /Alternate /DeviceCMYK"));
+ assert_eq!(data.len(), 300 * 150 * 4);
+ // Blue: lots of cyan, little yellow.
+ assert!(data[0] > 150 && data[2] < 60, "{:?}", &data[..4]);
+ // The document itself is untouched.
+ assert_eq!(s.active().unwrap().doc.mode, ColorMode::Rgb);
+ let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
+}
+
+#[test]
+fn print_one_copy_repeats_the_last_settings() {
+ let mut s = session("rgb", 8);
+ s.execute("file.print", json!({"dryRun": true, "copies": 3, "paper": "a5", "scale": 50})).unwrap();
+ let r = s.execute("file.printOneCopy", json!({"dryRun": true})).unwrap();
+ assert_eq!(r["copies"], 1);
+ assert_eq!(r["paper"], json!([419.53, 595.28]));
+ assert_eq!(r["scale"], 50.0);
+ let cmd: Vec<String> = serde_json::from_value(r["command"].clone()).unwrap();
+ assert!(!cmd.contains(&"-n".to_string()));
+ let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
+}
+
+#[test]
+fn package_copies_links_and_relinks() {
+ let dir = tmp("package");
+ let link = format!("{dir}/art.png");
+ let mut src = Session::new();
+ src.execute("file.new", json!({"width": 20, "height": 20, "background": "#ff0000"})).unwrap();
+ crate::file_cmds::save_doc(&src.active().unwrap().doc, &link, None).unwrap();
+ let mut s = session("rgb", 8);
+ s.execute("file.placeLinked", json!({"path": link})).unwrap();
+ let r = s.execute("file.package", json!({"dir": format!("{dir}/pkg")})).unwrap();
+ let copied = format!("{dir}/pkg/Print Me/Links/art.png");
+ assert_eq!(r["links"], json!([copied]));
+ assert!(std::path::Path::new(&copied).is_file());
+ let docp = r["document"].as_str().unwrap();
+ assert!(docp.ends_with("Print Me/Print Me.pcraft"));
+ let back = photocraft_io::import("Print Me.pcraft", &std::fs::read(docp).unwrap()).unwrap().document;
+ let linked: Vec<String> = back
+ .walk()
+ .iter()
+ .filter_map(|(_, _, l)| match &l.content {
+ LayerContent::Smart(so) => match &so.source {
+ SmartSource::Linked { path } => Some(path.clone()),
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect();
+ assert_eq!(linked.len(), 1);
+ assert!(linked[0].ends_with("Links/art.png"), "{linked:?}");
+ // The open document still points at the original.
+ let open = &s.active().unwrap().doc;
+ assert!(open.walk().iter().any(|(_, _, l)| matches!(&l.content, LayerContent::Smart(so) if matches!(&so.source, SmartSource::Linked { path } if *path == link))));
+}
+
+#[test]
+fn paths_export_as_illustrator_postscript() {
+ let mut s = session("rgb", 8);
+ assert!(!s.is_enabled("file.export.pathsToIllustrator"));
+ s.edit("paths", |d, _| {
+ let tri = Subpath::polygon(&[(10.0, 10.0), (100.0, 10.0), (50.0, 90.0)]);
+ let mut curve = Subpath::polyline(&[(0.0, 0.0), (300.0, 150.0)]);
+ curve.knots[0] = Knot::smooth(photocraft_geom::Point::new(0.0, 0.0), photocraft_geom::Point::new(0.0, 0.0), photocraft_geom::Point::new(50.0, 0.0));
+ d.paths.push(NamedPath { name: "Shapes".into(), path: Path::new(vec![tri, curve]), psd_raw: None });
+ Ok(())
+ })
+ .unwrap();
+ let r = s.execute("file.export.pathsToIllustrator", json!({})).unwrap();
+ let ai = r["ai"].as_str().unwrap();
+ assert!(ai.starts_with("%!PS-Adobe-2.0 EPSF-1.2"));
+ assert!(ai.contains("%%BoundingBox: 0 0 300 150"));
+ assert!(ai.contains("*u\n10.0000 140.0000 m\n100.0000 140.0000 L\n"), "{ai}");
+ assert!(ai.contains("\nn\n") && ai.contains("\nN\n*U\n"));
+ assert!(ai.contains(" C\n"), "curve segment");
+ let dir = tmp("ai");
+ let r = s.execute("file.export.pathsToIllustrator", json!({"path": format!("{dir}/p.ai"), "paths": "Shapes"})).unwrap();
+ assert_eq!(r["paths"], 1);
+ assert!(s.execute("file.export.pathsToIllustrator", json!({"paths": "Nope"})).is_err());
+}
diff --git a/crates/engine/src/proof_sim.rs b/crates/engine/src/proof_sim.rs
new file mode 100644
index 000000000..9448d9144
--- /dev/null
+++ b/crates/engine/src/proof_sim.rs
@@ -0,0 +1,418 @@
+//! View › Proof Setup simulations beyond a plain profile proof, and View › 32-bit Preview
+//! Options. Both become the canvas display LUT (`ColorState::display_lut`).
+//!
+//! * Working Cyan/Magenta/Yellow/Black Plate: the composite is separated into the working CMYK
+//! (proof profile, its intent and BPC) and only that plate is printed, shown as gray ink (the
+//! plate's value printed with black ink) like Photoshop's grayscale plate preview. Working CMY
+//! Plate prints cyan, magenta and yellow with the black plate left out.
+//! * Legacy Macintosh RGB: the document's RGB numbers shown on a gamma-1.8 display (numbers
+//! preserved, sRGB primaries).
+//! * Color Blindness (protanopia / deuteranopia): Viénot, Brettel & Mollon (1999), "Digital
+//! video colourmaps for checking the legibility of displays by dichromats", Color Research &
+//! Application 24(4): linear RGB → LMS, the missing cone response replaced by its projection
+//! onto the dichromat's plane, back to RGB (gamut first reduced as in the paper).
+//! * 32-bit Preview Options: exposure (stops) and gamma applied in linear light before the
+//! display transform, for 32-bit documents. Highlight Compression maps the canvas range to the
+//! display unchanged: the canvas texture is clamped to 0–1, so there is nothing above white
+//! to compress.
+
+use photocraft_cms::{Builtin, Intent, Lut3d, Transform};
+use photocraft_color::SampleType;
+use photocraft_doc::Document;
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::color_cmds::{ColorState, composite_profile};
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// What a proof simulates.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ProofKind {
+ /// The proof profile (Working CMYK, Custom…).
+ #[default]
+ Profile,
+ /// One plate of the proof profile (0 cyan, 1 magenta, 2 yellow, 3 black).
+ Plate(u8),
+ /// Cyan, magenta and yellow plates (no black).
+ CmyPlate,
+ LegacyMacintoshRgb,
+ Protanopia,
+ Deuteranopia,
+}
+
+impl ProofKind {
+ pub fn id(self) -> &'static str {
+ match self {
+ ProofKind::Profile => "profile",
+ ProofKind::Plate(0) => "workingCyanPlate",
+ ProofKind::Plate(1) => "workingMagentaPlate",
+ ProofKind::Plate(2) => "workingYellowPlate",
+ ProofKind::Plate(_) => "workingBlackPlate",
+ ProofKind::CmyPlate => "workingCmyPlate",
+ ProofKind::LegacyMacintoshRgb => "legacyMacintoshRgb",
+ ProofKind::Protanopia => "colorBlindnessProtanopia",
+ ProofKind::Deuteranopia => "colorBlindnessDeuteranopia",
+ }
+ }
+ pub fn from_id(s: &str) -> Option<ProofKind> {
+ Some(match s {
+ "profile" => ProofKind::Profile,
+ "workingCyanPlate" => ProofKind::Plate(0),
+ "workingMagentaPlate" => ProofKind::Plate(1),
+ "workingYellowPlate" => ProofKind::Plate(2),
+ "workingBlackPlate" => ProofKind::Plate(3),
+ "workingCmyPlate" => ProofKind::CmyPlate,
+ "legacyMacintoshRgb" => ProofKind::LegacyMacintoshRgb,
+ "colorBlindnessProtanopia" => ProofKind::Protanopia,
+ "colorBlindnessDeuteranopia" => ProofKind::Deuteranopia,
+ _ => return None,
+ })
+ }
+}
+
+/// View › 32-bit Preview Options.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct HdrPreview {
+ /// "exposureGamma" | "highlightCompression".
+ pub highlight_compression: bool,
+ /// Stops, −20…20.
+ pub exposure: f32,
+ /// 0.1…9.99.
+ pub gamma: f32,
+}
+
+impl Default for HdrPreview {
+ fn default() -> Self {
+ Self { highlight_compression: false, exposure: 0.0, gamma: 1.0 }
+ }
+}
+
+impl HdrPreview {
+ pub fn is_identity(&self) -> bool {
+ self.highlight_compression || (self.exposure == 0.0 && self.gamma == 1.0)
+ }
+ fn apply(&self, v: f32) -> f32 {
+ if self.is_identity() {
+ return v;
+ }
+ let lin = srgb_decode(v) * 2f32.powf(self.exposure);
+ srgb_encode(lin.max(0.0).powf(1.0 / self.gamma).min(1.0))
+ }
+}
+
+/// Is a 32-bit preview adjustment active for `doc` (a 32-bit document with non-default options)?
+pub fn hdr_active(c: &ColorState, doc: &Document) -> bool {
+ doc.depth == SampleType::F32 && c.hdr.get(&doc.id).is_some_and(|h| !h.is_identity())
+}
+
+/// Changes whenever the display LUT of `doc` changes because of this module (for UI caches).
+pub fn signature(c: &ColorState, doc: &Document) -> String {
+ let pv = c.proof(doc.id);
+ let h = if hdr_active(c, doc) { c.hdr.get(&doc.id).copied() } else { None };
+ format!("{:?} {:?}", pv.setup.kind, h)
+}
+
+fn srgb_decode(v: f32) -> f32 {
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+}
+
+fn srgb_encode(v: f32) -> f32 {
+ let v = v.clamp(0.0, 1.0);
+ if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
+}
+
+/// Viénot et al. (1999): linear RGB → LMS.
+const RGB_LMS: [[f32; 3]; 3] = [[17.8824, 43.5161, 4.11935], [3.45565, 27.1554, 3.86714], [0.0299566, 0.184309, 1.46709]];
+/// LMS → linear RGB (the paper's values, kept verbatim).
+#[allow(clippy::excessive_precision)]
+const LMS_RGB: [[f32; 3]; 3] = [[0.080_944_45, -0.130_504_41, 0.116_721_07], [-0.010_248_533, 0.054_019_327, -0.113_614_71], [-0.000_365_297, -0.004_121_614_7, 0.693_511_4]];
+
+fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
+ [0, 1, 2].map(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2])
+}
+
+/// Simulate a dichromat's view of a linear-RGB colour.
+pub fn dichromat(rgb_lin: [f32; 3], protan: bool) -> [f32; 3] {
+ // Gamut reduction so the simulated colours stay displayable.
+ let v = rgb_lin.map(|c| 0.992_052 * c + 0.003_974);
+ let [l, m, s] = mul(&RGB_LMS, v);
+ let lms = if protan { [2.02344 * m - 2.52581 * s, m, s] } else { [l, 0.494_207 * l + 1.24827 * s, s] };
+ mul(&LMS_RGB, lms).map(|c| c.clamp(0.0, 1.0))
+}
+
+/// The display LUT when a simulation or 32-bit preview applies (None = plain profile proof).
+pub fn display_lut(c: &ColorState, doc: &Document, size: usize) -> Result<Option<Lut3d>> {
+ let pv = c.proof(doc.id);
+ let kind = if pv.enabled { pv.setup.kind } else { ProofKind::Profile };
+ let hdr = if hdr_active(c, doc) { c.hdr.get(&doc.id).copied() } else { None };
+ if kind == ProofKind::Profile && hdr.is_none() {
+ return Ok(None);
+ }
+ let err = |e: photocraft_cms::CmsError| EngineError::Other(format!("colour management: {e}"));
+ let src = composite_profile(doc);
+ let mon = c.monitor();
+ let srgb = Builtin::Srgb.profile();
+ let setup = &pv.setup;
+ // composite → display for the plain case (with the profile proof when on).
+ let base: Box<dyn Fn([f32; 3]) -> [f32; 3]> = match kind {
+ ProofKind::Profile => {
+ let t = if pv.enabled {
+ Transform::proof(&src, &setup.profile, &mon, setup.intent, setup.bpc, setup.simulate_paper)
+ } else {
+ Transform::new(&src, &mon, Intent::RelativeColorimetric, true)
+ }
+ .map_err(err)?;
+ Box::new(move |v| eval3(&t, &v))
+ }
+ ProofKind::Plate(_) | ProofKind::CmyPlate => {
+ if setup.profile.channels() != 4 {
+ return Err(EngineError::Other("plate previews need a CMYK proof profile".into()));
+ }
+ let sep = Transform::new(&src, &setup.profile, setup.intent, setup.bpc).map_err(err)?;
+ let print = Transform::new(&setup.profile, &mon, Intent::RelativeColorimetric, true).map_err(err)?;
+ Box::new(move |v| {
+ let mut ink = [0.0f32; 16];
+ sep.eval(&v, &mut ink);
+ let shown = match kind {
+ ProofKind::Plate(p) => [0.0, 0.0, 0.0, ink[usize::from(p.min(3))]],
+ _ => [ink[0], ink[1], ink[2], 0.0],
+ };
+ eval3(&print, &shown)
+ })
+ }
+ ProofKind::LegacyMacintoshRgb => {
+ let t = Transform::new(srgb, &mon, Intent::RelativeColorimetric, true).map_err(err)?;
+ // Numbers preserved, shown with a 1.8 gamma instead of the sRGB curve.
+ Box::new(move |v| eval3(&t, &v.map(|x| srgb_encode(x.max(0.0).powf(1.8)))))
+ }
+ ProofKind::Protanopia | ProofKind::Deuteranopia => {
+ let to_srgb = Transform::new(&src, srgb, Intent::RelativeColorimetric, true).map_err(err)?;
+ let to_mon = Transform::new(srgb, &mon, Intent::RelativeColorimetric, true).map_err(err)?;
+ let protan = kind == ProofKind::Protanopia;
+ Box::new(move |v| {
+ let s = eval3(&to_srgb, &v);
+ let sim = dichromat(s.map(srgb_decode), protan).map(srgb_encode);
+ eval3(&to_mon, &sim)
+ })
+ }
+ };
+ let n = size.max(2);
+ let sc = (n - 1) as f32;
+ let mut data = vec![[0.0f32, 0.0, 0.0, 1.0]; n * n * n];
+ for b in 0..n {
+ for g in 0..n {
+ for r in 0..n {
+ let mut v = [r as f32 / sc, g as f32 / sc, b as f32 / sc];
+ if let Some(h) = hdr {
+ v = v.map(|x| h.apply(x));
+ }
+ let o = base(v);
+ data[r + g * n + b * n * n] = [o[0], o[1], o[2], 1.0];
+ }
+ }
+ }
+ Ok(Some(Lut3d { size: n, data }))
+}
+
+fn eval3(t: &Transform, v: &[f32]) -> [f32; 3] {
+ let mut out = [0.0f32; 16];
+ t.eval(v, &mut out);
+ if t.outputs() == 1 { [out[0]; 3] } else { [out[0], out[1], out[2]] }
+}
+
+// ------------------------------------------------------------------ commands
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn is_32(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if d.doc.depth == SampleType::F32 { Ok(()) } else { Err("32-bit Preview Options apply to 32-bit documents".into()) }
+}
+
+/// Select a simulated proof (`kind`) and turn Proof Colors on. Plates use the working CMYK.
+pub fn set_kind(s: &mut Session, kind: ProofKind) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let (id, doc) = (st.doc.id, st.doc.clone());
+ let plates = matches!(kind, ProofKind::Plate(_) | ProofKind::CmyPlate);
+ let working = if plates { Some(s.color.resolve("working-cmyk", Some(&doc), Some(photocraft_color::ColorMode::Cmyk))?) } else { None };
+ let pv = s.color.proof_mut(id);
+ if let Some(w) = working {
+ pv.setup.profile = w;
+ pv.setup.name = "working-cmyk".into();
+ }
+ pv.setup.kind = kind;
+ pv.enabled = true;
+ Ok(json!({"proof": kind.id(), "profile": pv.setup.profile.description, "proofColors": true}))
+}
+
+fn run_kind(s: &mut Session, id: &str) -> Result<Value> {
+ let kind = id.strip_prefix("view.proofSetup.").and_then(ProofKind::from_id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
+ set_kind(s, kind)
+}
+
+fn preview_32(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "view.thirtyTwoBitPreviewOptions";
+ let id = s.active().ok_or(EngineError::NoDocument)?.doc.id;
+ let mut h = s.color.hdr.get(&id).copied().unwrap_or_default();
+ if let Some(m) = p.get("method").and_then(Value::as_str) {
+ h.highlight_compression = match m {
+ "exposureGamma" | "exposureAndGamma" => false,
+ "highlightCompression" => true,
+ o => return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("method `{o}` (exposureGamma|highlightCompression)") }),
+ };
+ }
+ if let Some(e) = p.get("exposure").and_then(Value::as_f64) {
+ h.exposure = (e as f32).clamp(-20.0, 20.0);
+ }
+ if let Some(g) = p.get("gamma").and_then(Value::as_f64) {
+ h.gamma = (g as f32).clamp(0.1, 9.99);
+ }
+ s.color.hdr.insert(id, h);
+ Ok(json!({"method": if h.highlight_compression { "highlightCompression" } else { "exposureGamma" }, "exposure": h.exposure, "gamma": h.gamma}))
+}
+
+macro_rules! kind_spec {
+ ($id:literal, $label:literal) => {
+ CommandSpec { id: $id, label: $label, menu: &["View", "Proof Setup"], shortcut: None, params: "{} (sets the proof and turns Proof Colors on)", enabled: has_doc, run: |s, _| run_kind(s, $id), journal: false }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ kind_spec!("view.proofSetup.workingCyanPlate", "Working Cyan Plate"),
+ kind_spec!("view.proofSetup.workingMagentaPlate", "Working Magenta Plate"),
+ kind_spec!("view.proofSetup.workingYellowPlate", "Working Yellow Plate"),
+ kind_spec!("view.proofSetup.workingBlackPlate", "Working Black Plate"),
+ kind_spec!("view.proofSetup.workingCmyPlate", "Working CMY Plate"),
+ kind_spec!("view.proofSetup.legacyMacintoshRgb", "Legacy Macintosh RGB"),
+ kind_spec!("view.proofSetup.colorBlindnessProtanopia", "Color Blindness — Protanopia-type"),
+ kind_spec!("view.proofSetup.colorBlindnessDeuteranopia", "Color Blindness — Deuteranopia-type"),
+ CommandSpec {
+ id: "view.thirtyTwoBitPreviewOptions",
+ label: "32-bit Preview Options…",
+ menu: &["View"],
+ shortcut: None,
+ params: r##"{"method":"exposureGamma|highlightCompression"="exposureGamma","exposure":-20..20=0,"gamma":0.1..9.99=1}"##,
+ enabled: is_32,
+ run: preview_32,
+ journal: false,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(mode: &str, depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8, "mode": mode, "depth": depth})).unwrap();
+ s
+ }
+
+ fn sample(lut: &Lut3d, idx: [usize; 3]) -> [f32; 3] {
+ let n = lut.size;
+ let v = lut.data[idx[0] + idx[1] * n + idx[2] * n * n];
+ [v[0], v[1], v[2]]
+ }
+
+ #[test]
+ fn dichromat_keeps_neutrals_and_merges_red_green() {
+ for protan in [true, false] {
+ let w = dichromat([1.0, 1.0, 1.0], protan);
+ assert!(w.iter().all(|c| (c - 1.0).abs() < 0.02), "{w:?}");
+ let g = dichromat([0.2, 0.2, 0.2], protan);
+ assert!(g.iter().all(|c| (c - 0.2).abs() < 0.02), "{g:?}");
+ // Red and green become (nearly) indistinguishable in hue: both yellowish/brown.
+ let r = dichromat([1.0, 0.0, 0.0], protan);
+ let gr = dichromat([0.0, 1.0, 0.0], protan);
+ assert!((r[0] - r[1]).abs() < 0.15 && (gr[0] - gr[1]).abs() < 0.15, "{r:?} {gr:?}");
+ // Blue stays blue.
+ let b = dichromat([0.0, 0.0, 1.0], protan);
+ assert!(b[2] > 0.8);
+ }
+ // Protanopes see red much darker than deuteranopes do.
+ assert!(dichromat([1.0, 0.0, 0.0], true)[0] < dichromat([1.0, 0.0, 0.0], false)[0]);
+ }
+
+ #[test]
+ fn plates_and_simulations_build_luts() {
+ for depth in [8, 16, 32] {
+ let mut s = session("rgb", depth);
+ for id in ["view.proofSetup.workingCyanPlate", "view.proofSetup.workingBlackPlate", "view.proofSetup.workingCmyPlate", "view.proofSetup.legacyMacintoshRgb", "view.proofSetup.colorBlindnessProtanopia", "view.proofSetup.colorBlindnessDeuteranopia"] {
+ let r = s.execute(id, json!({})).unwrap();
+ assert_eq!(r["proofColors"], true);
+ let d = s.active().unwrap().doc.clone();
+ let pv = s.color.proof(d.id);
+ assert_eq!(pv.setup.kind.id(), id.trim_start_matches("view.proofSetup."));
+ let lut = s.color.display_lut(&d, 5).unwrap();
+ assert_eq!(lut.data.len(), 125);
+ let bytes = s.color.canvas_lut(&d, 5).unwrap().unwrap();
+ assert_eq!(bytes.len(), 125 * 4);
+ }
+ }
+ }
+
+ #[test]
+ fn plate_previews_are_gray_and_track_ink() {
+ let mut s = session("rgb", 8);
+ s.execute("view.proofSetup.workingCyanPlate", json!({})).unwrap();
+ let d = s.active().unwrap().doc.clone();
+ let lut = s.color.display_lut(&d, 5).unwrap();
+ // Pure cyan: heavy cyan plate → dark gray; white: no ink → white; red: little cyan.
+ let cyan = sample(&lut, [0, 4, 4]);
+ let white = sample(&lut, [4, 4, 4]);
+ let red = sample(&lut, [4, 0, 0]);
+ for c in [cyan, white, red] {
+ assert!((c[0] - c[1]).abs() < 0.03 && (c[1] - c[2]).abs() < 0.03, "plates are gray: {c:?}");
+ }
+ assert!(white[0] > 0.9, "{white:?}");
+ assert!(cyan[0] < red[0] && cyan[0] < 0.6, "cyan {cyan:?} red {red:?}");
+ // Back to the plain working CMYK proof via Proof Setup.
+ s.execute("view.proofSetup", json!({"profile": "working-cmyk"})).unwrap();
+ assert_eq!(s.color.proof(d.id).setup.kind, ProofKind::Profile);
+ }
+
+ #[test]
+ fn legacy_mac_is_darker_in_midtones() {
+ let mut s = session("rgb", 8);
+ s.execute("view.proofSetup.legacyMacintoshRgb", json!({})).unwrap();
+ let d = s.active().unwrap().doc.clone();
+ let lut = s.color.display_lut(&d, 5).unwrap();
+ let mid = sample(&lut, [2, 2, 2]);
+ let white = sample(&lut, [4, 4, 4]);
+ // 0.5^1.8 = 0.287 linear vs 0.214 for sRGB 0.5: the gamma-1.8 display is brighter.
+ assert!(mid[0] > 0.52 && mid[0] < 0.62, "{mid:?}");
+ assert!(white[0] > 0.99);
+ }
+
+ #[test]
+ fn thirty_two_bit_preview_options() {
+ let mut s = session("rgb", 8);
+ assert!(s.execute("view.thirtyTwoBitPreviewOptions", json!({"exposure": 1})).is_err(), "8-bit: disabled");
+ let mut s = session("rgb", 32);
+ let d = s.active().unwrap().doc.clone();
+ assert!(s.color.canvas_lut(&d, 5).unwrap().is_none());
+ let r = s.execute("view.thirtyTwoBitPreviewOptions", json!({"exposure": 1.0, "gamma": 1.0})).unwrap();
+ assert_eq!(r["exposure"], 1.0);
+ assert!(hdr_active(&s.color, &d));
+ let lut = s.color.display_lut(&d, 5).unwrap();
+ // +1 stop doubles linear light: sRGB 0.25 (0.0508 linear) → 0.1016 linear ≈ 0.354 sRGB.
+ let q = sample(&lut, [1, 1, 1]);
+ assert!((q[0] - 0.354).abs() < 0.02, "{q:?}");
+ assert!(s.color.canvas_lut(&d, 5).unwrap().is_some());
+ // Highlight Compression: identity mapping, so no LUT.
+ s.execute("view.thirtyTwoBitPreviewOptions", json!({"method": "highlightCompression"})).unwrap();
+ assert!(!hdr_active(&s.color, &d));
+ assert!(s.execute("view.thirtyTwoBitPreviewOptions", json!({"method": "nope"})).is_err());
+ // Clamped ranges.
+ let r = s.execute("view.thirtyTwoBitPreviewOptions", json!({"method": "exposureGamma", "exposure": 99, "gamma": 0})).unwrap();
+ assert_eq!(r["exposure"], 20.0);
+ assert!((r["gamma"].as_f64().unwrap() - 0.1).abs() < 1e-6);
+ }
+}
diff --git a/crates/engine/src/render_cmds.rs b/crates/engine/src/render_cmds.rs
new file mode 100644
index 000000000..58665ca65
--- /dev/null
+++ b/crates/engine/src/render_cmds.rs
@@ -0,0 +1,325 @@
+//! Filter › Render › Flame…, Picture Frame… and Tree…: procedural renderers
+//! (`photocraft_algo::render2`). They draw onto the active pixel layer (or a
+//! new layer with `newLayer: true`, or when the active layer has no pixels),
+//! inside the selection, in any colour mode and depth, as one undo step.
+//! Results report what was drawn (`layer`, `bounds`, `primitives`) so agents
+//! can verify them without screenshots.
+
+use photocraft_algo::render2::{self, FlameSpec, FrameSpec, Prim, TreeSpec};
+use photocraft_doc::{Layer, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Map, Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+/// `[r, g, b(, a)]` (0–1) or `#rrggbb` → `[r, g, b, a]`.
+fn parse_colour(v: &Value) -> Option<[f32; 4]> {
+ match v {
+ Value::Array(a) if a.len() >= 3 => {
+ let c = |j: usize, d: f64| a.get(j).and_then(Value::as_f64).unwrap_or(d) as f32;
+ Some([c(0, 0.0), c(1, 0.0), c(2, 0.0), c(3, 1.0)])
+ }
+ Value::String(h) if h.len() == 7 && h.starts_with('#') => {
+ let ch = |j: usize| u8::from_str_radix(&h[j..j + 2], 16).map_or(0.0, |v| v as f32 / 255.0);
+ Some([ch(1), ch(3), ch(5), 1.0])
+ }
+ _ => None,
+ }
+}
+
+/// Params as an object with the named colour keys normalized to arrays (invalid ones dropped).
+fn normalized(p: &Value, colours: &[&str]) -> Map<String, Value> {
+ let mut m = p.as_object().cloned().unwrap_or_default();
+ m.remove("layer");
+ m.remove("newLayer");
+ m.remove("path");
+ for k in colours {
+ if let Some(v) = m.remove(*k)
+ && let Some(c) = parse_colour(&v)
+ {
+ m.insert((*k).to_string(), json!(c));
+ }
+ }
+ m
+}
+
+fn spec_from<T: serde::de::DeserializeOwned>(m: Map<String, Value>) -> Result<T> {
+ serde_json::from_value(Value::Object(m)).map_err(|e| EngineError::Other(format!("invalid parameters: {e}")))
+}
+
+/// Accepts a 1-based number or a name (camelCase) for an enumerated option.
+fn index_param(m: &mut Map<String, Value>, k: &str, names: &[&str]) {
+ if let Some(Value::String(n)) = m.get(k) {
+ let lower = n.to_ascii_lowercase().replace([' ', '-', '_'], "");
+ let i = names.iter().position(|s| s.to_ascii_lowercase().replace([' ', '-', '_'], "") == lower).map_or(1, |i| i + 1);
+ m.insert(k.to_string(), json!(i));
+ }
+}
+
+/// Flattened polylines of the path Flame follows: `path` (a saved path name, `"work"`), else the
+/// work path, else the first saved path. `None` when the document has no path.
+fn flame_paths(s: &Session, p: &Value) -> Option<Vec<Vec<(f32, f32)>>> {
+ let d = s.active()?;
+ let doc = &d.doc;
+ let path = match p.get("path").and_then(Value::as_str) {
+ Some(n) if !n.is_empty() && !n.eq_ignore_ascii_case("work") => doc.paths.iter().find(|sp| sp.name == n).map(|sp| &sp.path),
+ _ => doc.work_path.as_ref().or_else(|| doc.paths.first().map(|sp| &sp.path)),
+ }?;
+ let polys: Vec<Vec<(f32, f32)>> = photocraft_vector::flatten_path(path, 0.5)
+ .into_iter()
+ .map(|pl| {
+ let mut v: Vec<(f32, f32)> = pl.pts.iter().map(|&(x, y)| (x as f32, y as f32)).collect();
+ if pl.closed && let Some(&f) = v.first() {
+ v.push(f);
+ }
+ v
+ })
+ .filter(|v| !v.is_empty())
+ .collect();
+ (!polys.is_empty()).then_some(polys)
+}
+
+/// Draws `prims` onto the target layer as one undo step.
+fn draw(s: &mut Session, label: &str, p: &Value, prims: Vec<Prim>, extra: Value) -> Result<Value> {
+ let want_new = p.get("newLayer").and_then(Value::as_bool).unwrap_or(false);
+ let target = p.get("layer").and_then(Value::as_u64).map(LayerId);
+ let count = prims.len();
+ let (layer, created, used) = s.edit(label, |doc, active| {
+ let id = target.or(*active);
+ let raster = id.and_then(|i| doc.layer(i)).is_some_and(|l| matches!(l.content, LayerContent::Raster(_)));
+ let (id, created) = if want_new || !raster {
+ let l = Layer::new(label.trim_end_matches('…'), LayerContent::Raster(Surface::new(doc.pixel_format())));
+ let nid = doc.insert_above(*active, l);
+ *active = Some(nid);
+ (nid, true)
+ } else {
+ (id.ok_or(EngineError::Other("no active layer".into()))?, false)
+ };
+ let selection = doc.selection.clone();
+ let mut clip = doc.bounds();
+ if let Some(sel) = &selection {
+ clip = clip.intersect(&sel.content_bounds());
+ }
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ let LayerContent::Raster(surf) = &mut l.content else { return Err(EngineError::Other("not a pixel layer".into())) };
+ let used = render2::composite(surf, &prims, clip, selection.as_ref());
+ surf.prune();
+ Ok((id, created, used))
+ })?;
+ let mut r = json!({
+ "layer": layer.0,
+ "newLayer": created,
+ "bounds": if used.is_empty() { Value::Null } else { json!([used.x0, used.y0, used.x1, used.y1]) },
+ "primitives": count,
+ });
+ if let (Value::Object(m), Value::Object(e)) = (&mut r, extra) {
+ m.extend(e);
+ }
+ Ok(r)
+}
+
+fn canvas(s: &Session) -> Result<Rect> {
+ Ok(s.active().ok_or(EngineError::NoDocument)?.doc.bounds())
+}
+
+fn run_flame(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut m = normalized(p, &["color"]);
+ if !m.get("useCustomColor").and_then(Value::as_bool).unwrap_or(m.contains_key("color")) {
+ m.remove("color");
+ }
+ m.remove("useCustomColor");
+ if let Some(Value::Number(q)) = m.get("quality").cloned() {
+ m.insert("quality".into(), json!(q.as_f64().unwrap_or(2.0).clamp(0.0, 4.0) as u32));
+ } else if let Some(Value::String(q)) = m.get("quality").cloned() {
+ let i = ["draft", "low", "medium", "high", "fine"].iter().position(|n| *n == q).unwrap_or(2);
+ m.insert("quality".into(), json!(i));
+ }
+ let spec: FlameSpec = spec_from(m)?;
+ let found = flame_paths(s, p);
+ let used_path = found.is_some();
+ let paths = found.unwrap_or_else(|| {
+ let c = canvas(s).unwrap_or(Rect::new(0, 0, 1, 1));
+ if spec.flame_type == render2::FlameType::CandleLight {
+ vec![vec![(c.x0 as f32 + c.width() as f32 * 0.5, c.y0 as f32 + c.height() as f32 * 0.75)]]
+ } else {
+ vec![render2::default_flame_path(c)]
+ }
+ });
+ let prims = render2::flame(&spec, &paths);
+ draw(s, "Flame…", p, prims, json!({ "usedPath": used_path }))
+}
+
+fn run_tree(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut m = normalized(p, &["leavesColor", "branchesColor"]);
+ index_param(&mut m, "baseTreeType", &render2::tree_type_names());
+ if m.contains_key("leavesColor") && !m.contains_key("defaultLeaves") {
+ m.insert("defaultLeaves".into(), json!(false));
+ }
+ if m.contains_key("branchesColor") && !m.contains_key("customBranchColor") {
+ m.insert("customBranchColor".into(), json!(true));
+ }
+ let spec: TreeSpec = spec_from(m)?;
+ let prims = render2::tree(&spec, canvas(s)?);
+ let name = render2::tree_type_names()[(spec.base_tree_type.clamp(1, 34) - 1) as usize];
+ draw(s, "Tree…", p, prims, json!({ "treeType": name }))
+}
+
+fn run_frame(s: &mut Session, p: &Value) -> Result<Value> {
+ let mut m = normalized(p, &["vineColor", "flowerColor", "leafColor"]);
+ index_param(&mut m, "frame", &render2::FRAME_STYLES);
+ let spec: FrameSpec = spec_from(m)?;
+ let prims = render2::picture_frame(&spec, canvas(s)?);
+ let name = render2::FRAME_STYLES[(spec.frame.clamp(1, render2::FRAME_STYLES.len() as u32) - 1) as usize];
+ draw(s, "Picture Frame…", p, prims, json!({ "frame": name }))
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+/// The Render commands of this module.
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "filter.render.flame",
+ label: "Flame…",
+ menu: &["Filter", "Render"],
+ shortcut: None,
+ params: r##"{"flameType":"oneFlameAlongPath|multipleFlamesAlongPath|multipleFlamesPathDirections|multipleFlamesVariousLength|candleLight|multipleFlamesOneDirection","length":1..1000=150,"randomizeLength":bool,"width":1..1000=40,"angle":-180..180=0,"interval":1..1000=60,"adjustIntervalForLoops":bool=true,"useCustomColor":bool,"color":color,"turbulent":0..100=25,"jag":0..100=25,"opacity":0..100=75,"flameLines":1..100=20,"flameBottomAlignment":0..100=20,"flameStyle":"normal|violent|flat","flameShape":"parallel|toCenter|spread|oval|pointed","randomizeShapes":bool,"seed":u32=0,"quality":"draft|low|medium|high|fine","path":text,"newLayer":bool} → {layer,newLayer,bounds,primitives,usedPath}"##,
+ enabled: has_doc,
+ run: run_flame,
+ journal: true,
+ },
+ CommandSpec {
+ id: "filter.render.pictureFrame",
+ label: "Picture Frame…",
+ menu: &["Filter", "Render"],
+ shortcut: None,
+ params: r##"{"frame":"vineWithFlowers|vineWithLeaves|ivy|roses|daisies|berries|bamboo|waves|zigzag|dots|rope|scallops|doubleLine|snowflakes|stars|hearts","margin":0..30=4,"size":1..100=50,"arrangement":1..100=50,"lines":1..5=1,"thickness":1..100=30,"fade":0..100=0,"vineColor":color,"flowerColor":color,"leafColor":color,"seed":u32=0,"newLayer":bool} → {layer,newLayer,bounds,primitives,frame}"##,
+ enabled: has_doc,
+ run: run_frame,
+ journal: true,
+ },
+ CommandSpec {
+ id: "filter.render.tree",
+ label: "Tree…",
+ menu: &["Filter", "Render"],
+ shortcut: None,
+ params: r##"{"baseTreeType":1..34=1,"lightDirection":1..5=3,"leavesAmount":0..100=50,"leavesSize":0..200=100,"branchesHeight":50..300=100,"branchesThickness":50..200=100,"defaultLeaves":bool=true,"leavesColor":color,"customBranchColor":bool,"branchesColor":color,"flatShading":bool,"seed":u32=0,"x":0..1=0.5,"y":0..1=0.95,"size":0.05..2=0.8,"newLayer":bool} → {layer,newLayer,bounds,primitives,treeType}"##,
+ enabled: has_doc,
+ run: run_tree,
+ journal: true,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(depth: &str) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 160, "height": 120, "depth": depth})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s
+ }
+
+ fn pixels(s: &Session) -> Vec<f32> {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 160, 120))
+ }
+
+ fn opaque(s: &Session) -> usize {
+ pixels(s).chunks_exact(4).filter(|p| p[3] > 0.05).count()
+ }
+
+ #[test]
+ fn each_renderer_draws_undoes_and_is_seeded_at_every_depth() {
+ for depth in ["8", "16", "32"] {
+ for (id, p) in [("filter.render.flame", json!({})), ("filter.render.tree", json!({"baseTreeType": 7})), ("filter.render.pictureFrame", json!({"frame": "roses"}))] {
+ let mut s = session(depth);
+ let r = s.execute(id, p.clone()).unwrap_or_else(|e| panic!("{id}@{depth}: {e}"));
+ assert!(r["primitives"].as_u64().unwrap() > 0, "{id}");
+ assert!(r["bounds"].is_array(), "{id}@{depth}: {r}");
+ let n = opaque(&s);
+ assert!(n > 50, "{id}@{depth} drew {n} px");
+ let first = pixels(&s);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(opaque(&s), 0, "{id} undo");
+ s.execute(id, p.clone()).unwrap();
+ assert_eq!(pixels(&s), first, "{id} deterministic");
+ s.execute("edit.undo", json!({})).unwrap();
+ let mut q = p.clone();
+ q["seed"] = json!(5);
+ s.execute(id, q).unwrap();
+ assert_ne!(pixels(&s), first, "{id} seed changes the result");
+ }
+ }
+ }
+
+ #[test]
+ fn flame_follows_the_work_path() {
+ let mut s = session("8");
+ let r = s.execute("filter.render.flame", json!({})).unwrap();
+ assert_eq!(r["usedPath"], json!(false));
+ s.execute("edit.undo", json!({})).unwrap();
+ // A vertical line path on the left edge: the flame stays near it.
+ s.edit("path", |doc, _| {
+ let mut sub = photocraft_doc::Subpath::default();
+ for (x, y) in [(20.0, 110.0), (20.0, 20.0)] {
+ sub.knots.push(photocraft_doc::Knot::corner(x, y));
+ }
+ doc.work_path = Some(photocraft_doc::Path { subpaths: vec![sub], ..Default::default() });
+ Ok(())
+ })
+ .unwrap();
+ let r = s.execute("filter.render.flame", json!({"width": 16, "length": 60})).unwrap();
+ assert_eq!(r["usedPath"], json!(true));
+ let b: Vec<i64> = r["bounds"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect();
+ assert!(b[0] < 20 && b[2] < 60, "flame bounds {b:?} hug the path at x=20");
+ }
+
+ #[test]
+ fn selection_limits_and_new_layer() {
+ let mut s = session("8");
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 80, "height": 120})).unwrap();
+ let r = s.execute("filter.render.tree", json!({"newLayer": true, "baseTreeType": 1, "leavesAmount": 100})).unwrap();
+ assert_eq!(r["newLayer"], json!(true));
+ let px = pixels(&s);
+ let right = px.chunks_exact(4).enumerate().filter(|(i, p)| i % 160 >= 81 && p[3] > 0.0).count();
+ assert_eq!(right, 0, "nothing drawn outside the selection");
+ assert!(opaque(&s) > 50);
+ }
+
+ #[test]
+ fn works_in_cmyk_and_gray() {
+ for mode in ["cmyk", "grayscale", "lab"] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 96, "height": 96, "mode": mode})).unwrap();
+ let r = s.execute("filter.render.pictureFrame", json!({"frame": 13, "newLayer": true})).unwrap_or_else(|e| panic!("{mode}: {e}"));
+ assert!(r["bounds"].is_array(), "{mode}");
+ }
+ }
+
+ /// `cargo test --release -p photocraft-engine render_cmds::tests::bench_24mp -- --ignored --nocapture`
+ #[test]
+ #[ignore]
+ fn bench_24mp() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 6000, "height": 4000})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ for (id, p) in [
+ ("filter.render.flame", json!({"flameType": "multipleFlamesAlongPath", "length": 600, "width": 160, "interval": 120})),
+ ("filter.render.flame", json!({"length": 1500, "width": 400, "flameLines": 100, "quality": "fine"})),
+ ("filter.render.tree", json!({"baseTreeType": 1, "leavesAmount": 100})),
+ ("filter.render.tree", json!({"baseTreeType": 6, "leavesAmount": 100})),
+ ("filter.render.pictureFrame", json!({"frame": 1})),
+ ] {
+ let t = std::time::Instant::now();
+ let r = s.execute(id, p).unwrap();
+ println!("{id}: {:?} ({} prims)", t.elapsed(), r["primitives"]);
+ }
+ }
+}
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 0ad96122f..0b060a822 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -163,14 +163,24 @@ fn sample(pre: &Document, id: LayerId, surf: &Surface, which: SampleLayers, rect
}
}
-/// Integer clone offset from `offset` or `source` (source − first point).
-fn clone_offset(p: &Value, stroke: &Stroke, cmd: &str) -> Result<(i32, i32)> {
- if let Some((dx, dy)) = point(p, "offset") {
- return Ok((dx.round() as i32, dy.round() as i32));
- }
- let (sx, sy) = point(p, "source").ok_or_else(|| bad(cmd, "missing `source` ([x,y]) or `offset` ([dx,dy])"))?;
+/// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot,
+/// with the slot's (or the call's) scale, rotation and flips (see `presets::clone_source`).
+fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &str) -> Result<crate::presets::clone_source::Mapping> {
let f = stroke.points[0];
- Ok(((sx - f.x).round() as i32, (sy - f.y).round() as i32))
+ crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd)
+}
+
+/// Source pixels for destination `rect`: a translated read, or a bilinear resample when the
+/// clone source is scaled, rotated or flipped.
+fn clone_sample(pre: &Document, id: LayerId, surf: &Surface, which: SampleLayers, rect: Rect, map: &crate::presets::clone_source::Mapping) -> Region {
+ if map.is_translation() {
+ let off = map.offset();
+ let mut r = sample(pre, id, surf, which, rect.translate(off.0, off.1));
+ r.rect = rect;
+ return r;
+ }
+ let src = sample(pre, id, surf, which, map.source_rect(rect));
+ crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format()))
}
/// Result JSON shared by Clone Stamp and Healing Brush: the offset used and where the next stroke
@@ -210,15 +220,15 @@ fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) {
fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "paint.cloneStamp";
let (stroke, id) = parse_brush(s, p, CMD)?;
- let off = clone_offset(p, &stroke, CMD)?;
let which = sample_layers(p, CMD)?;
let mode = blend_param(p, CMD)?;
let aligned = flag(p, "aligned", true);
+ let map = clone_mapping(s, p, &stroke, CMD)?;
+ let off = map.offset();
let dmg = run_stroke(s, "Clone Stamp", id, |pre, surf, sel, lock| {
let (bounds, cov) = stroke_coverage(&stroke);
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
- let mut paint = sample(pre, id, surf, which, bounds.translate(off.0, off.1));
- paint.rect = bounds;
+ let paint = clone_sample(pre, id, surf, which, bounds, &map);
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
Ok(clone_result(dmg, off, aligned, p, &stroke))
@@ -265,16 +275,16 @@ fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &[bool]) ->
fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "paint.healingBrush";
let (stroke, id) = parse_brush(s, p, CMD)?;
- let off = clone_offset(p, &stroke, CMD)?;
let which = sample_layers(p, CMD)?;
let mode = blend_param(p, CMD)?;
let aligned = flag(p, "aligned", true);
+ let map = clone_mapping(s, p, &stroke, CMD)?;
+ let off = map.offset();
let dmg = run_stroke(s, "Healing Brush", id, |pre, surf, sel, lock| {
let (bounds, cov) = stroke_coverage(&stroke);
let (g, cov) = pad_coverage(bounds, &cov, 2);
let fmt = surf.format();
- let mut src = sample(pre, id, surf, which, g.translate(off.0, off.1));
- src.rect = g;
+ let src = clone_sample(pre, id, surf, which, g, &map);
// The destination the texture is fitted to: the layer itself, or what the user sees when
// sampling several layers (so healing onto an empty layer matches the composite).
let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) };
diff --git a/crates/engine/src/select_extra_cmds.rs b/crates/engine/src/select_extra_cmds.rs
new file mode 100644
index 000000000..9c8453bf6
--- /dev/null
+++ b/crates/engine/src/select_extra_cmds.rs
@@ -0,0 +1,378 @@
+//! Select › Sky, Select › Isolate Layers and Select › Transform Selection.
+//!
+//! * `select.sky` runs the classical sky segmentation of `photocraft_algo::segment::sky` on the
+//! composite (or the active layer) and combines it with the selection.
+//! * `select.isolateLayers` toggles the Layers panel's isolation filter: only the layers selected
+//! when it was turned on are listed ([`crate::DocState::isolated_layers`], view state).
+//! * `select.transformSelection` transforms the selection outline/mask only (not pixels): a
+//! quad (distort / perspective), an affine matrix, scale / rotate / skew / move about a
+//! reference point, or a warp (same params as `edit.transform.warp`).
+
+use photocraft_algo::segment::sky::{self, SkyParams};
+use photocraft_algo::segment::{Sampler, SurfaceSampler};
+use photocraft_algo::selection::{SelectionMode, combine_region};
+use photocraft_algo::transform::{Homography, Interp};
+use photocraft_algo::warp::warp_mesh_gray;
+use photocraft_doc::{Document, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+fn has_selection(s: &Session) -> std::result::Result<(), String> {
+ s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into())
+}
+fn has_layer(s: &Session) -> std::result::Result<(), String> {
+ s.active().and_then(|d| d.active_layer).map(|_| ()).ok_or_else(|| "no active layer".into())
+}
+fn f(p: &Value, k: &str, d: f64) -> f64 {
+ p.get(k).and_then(Value::as_f64).unwrap_or(d)
+}
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+struct CompositeSampler<'a>(&'a Document);
+
+impl Sampler for CompositeSampler<'_> {
+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {
+ photocraft_compose::render(self.0, r).px
+ }
+}
+
+// ---------------------------------------------------------------- Sky
+
+fn select_sky(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let canvas = doc.bounds();
+ let params = SkyParams { threshold: f(p, "threshold", 50.0) as f32, softness: f(p, "softness", 50.0) as f32 };
+ let all = p.get("sampleAllLayers").and_then(Value::as_bool).unwrap_or(true);
+ let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| l.surface());
+ let region = match (all, layer) {
+ (false, Some(surf)) => sky::select_sky(&SurfaceSampler(surf), canvas, params),
+ _ => sky::select_sky(&CompositeSampler(&doc), canvas, params),
+ };
+ let m = p.get("mode").and_then(Value::as_str).unwrap_or("replace");
+ let m = SelectionMode::parse(if m == "new" { "replace" } else { m });
+ let Some(region) = region else {
+ // Photoshop reports "No sky was detected" and leaves the selection alone.
+ return Ok(json!({ "selected": doc.selection.is_some(), "changed": false, "coverage": 0.0, "message": "No sky was detected" }));
+ };
+ let total: f64 = region.mask.iter().map(|v| f64::from(*v) / 255.0).sum();
+ let coverage = total / (canvas.width() as f64 * canvas.height() as f64).max(1.0);
+ let b = region.bbox;
+ let selected = s.edit("Select Sky", |doc, _| {
+ doc.selection = combine_region(doc.selection.as_ref(), Some(&region), m);
+ Ok(doc.selection.is_some())
+ })?;
+ Ok(json!({ "selected": selected, "changed": true, "coverage": coverage, "bounds": [b.x0, b.y0, b.width() as i32, b.height() as i32] }))
+}
+
+// ---------------------------------------------------------------- Isolate Layers
+
+fn isolate_layers(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(st.isolated_layers.is_empty());
+ st.isolated_layers = if on { st.selected_layers() } else { Vec::new() };
+ st.revision += 1;
+ Ok(json!({ "isolated": !st.isolated_layers.is_empty(), "layers": st.isolated_layers.iter().map(|l| l.0).collect::<Vec<_>>() }))
+}
+
+/// Whether a Layers panel row for `id` is listed under isolation (ancestors of an isolated layer
+/// stay visible so it can be shown in place).
+pub fn isolation_shows(doc: &Document, isolated: &[LayerId], id: LayerId) -> bool {
+ if isolated.is_empty() || isolated.contains(&id) {
+ return true;
+ }
+ fn contains(l: &photocraft_doc::Layer, set: &[LayerId]) -> bool {
+ match &l.content {
+ photocraft_doc::LayerContent::Group(g) => g.children.iter().any(|c| set.contains(&c.id) || contains(c, set)),
+ _ => false,
+ }
+ }
+ doc.layer(id).is_some_and(|l| contains(l, isolated))
+}
+
+// ---------------------------------------------------------------- Transform Selection
+
+fn reference_point(p: &Value, r: [f64; 4]) -> [f64; 2] {
+ let (x0, y0, x1, y1) = (r[0], r[1], r[2], r[3]);
+ let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
+ match p.get("reference") {
+ Some(Value::Array(a)) if a.len() >= 2 => [a[0].as_f64().unwrap_or(cx), a[1].as_f64().unwrap_or(cy)],
+ Some(Value::String(k)) => match k.as_str() {
+ "topLeft" => [x0, y0],
+ "top" => [cx, y0],
+ "topRight" => [x1, y0],
+ "left" => [x0, cy],
+ "right" => [x1, cy],
+ "bottomLeft" => [x0, y1],
+ "bottom" => [cx, y1],
+ "bottomRight" => [x1, y1],
+ _ => [cx, cy],
+ },
+ _ => [cx, cy],
+ }
+}
+
+fn quad(p: &Value) -> Option<[[f64; 2]; 4]> {
+ let a = p.get("quad").or_else(|| p.get("corners"))?.as_array()?;
+ if a.len() != 4 {
+ return None;
+ }
+ let mut q = [[0.0; 2]; 4];
+ for (i, v) in a.iter().enumerate() {
+ let c = v.as_array()?;
+ q[i] = [c.first()?.as_f64()?, c.get(1)?.as_f64()?];
+ }
+ Some(q)
+}
+
+/// The homography of the scale / rotate / skew / move params about the reference point.
+fn affine_params(p: &Value, r: [f64; 4]) -> Homography {
+ let [px, py] = reference_point(p, r);
+ let (sx, sy) = (f(p, "scaleX", 100.0) / 100.0, f(p, "scaleY", 100.0) / 100.0);
+ let a = f(p, "rotate", 0.0).to_radians();
+ let (kx, ky) = (f(p, "skewX", 0.0).to_radians().tan(), f(p, "skewY", 0.0).to_radians().tan());
+ let (dx, dy) = (f(p, "dx", f(p, "x", 0.0)), f(p, "dy", f(p, "y", 0.0)));
+ let t = |x: f64, y: f64| Homography([1.0, 0.0, x, 0.0, 1.0, y, 0.0, 0.0, 1.0]);
+ let (sa, ca) = a.sin_cos();
+ let rot = Homography([ca, -sa, 0.0, sa, ca, 0.0, 0.0, 0.0, 1.0]);
+ let skew = Homography([1.0, kx, 0.0, ky, 1.0, 0.0, 0.0, 0.0, 1.0]);
+ let scale = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]);
+ t(px + dx, py + dy).mul(&rot).mul(&skew).mul(&scale).mul(&t(-px, -py))
+}
+
+fn transform_selection(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "select.transformSelection";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let sel = d.doc.selection.as_ref().ok_or_else(|| EngineError::Other("no selection".into()))?;
+ let b = sel.content_bounds();
+ let rect = match p.get("rect").and_then(Value::as_array) {
+ Some(a) if a.len() == 4 => {
+ let v: Vec<f64> = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect();
+ [v[0], v[1], v[2], v[3]]
+ }
+ _ => [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64],
+ };
+ let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bilinear"));
+ let is_warp = ["warp", "style", "mesh", "grid"].iter().any(|k| p.get(*k).is_some());
+ if is_warp {
+ let r = Rect::new(rect[0].floor() as i32, rect[1].floor() as i32, rect[2].ceil() as i32, rect[3].ceil() as i32);
+ let w = crate::warp_cmds::warp_from_params(CMD, p, [r.x0 as f64, r.y0 as f64, r.x1 as f64, r.y1 as f64])?;
+ if w.is_identity() {
+ return Ok(json!({"changed": false}));
+ }
+ let selected = s.edit("Transform Selection", |doc, _| {
+ if let Some(sel) = &doc.selection {
+ doc.selection = Some(warp_mesh_gray(sel, &|x, y| w.map(x, y), interp)).filter(|s| !s.content_bounds().is_empty());
+ }
+ Ok(doc.selection.is_some())
+ })?;
+ return Ok(json!({"changed": true, "selected": selected, "bounds": bounds_json(s)}));
+ }
+ let h = if let Some(q) = quad(p) {
+ Homography::rect_to_quad(rect, q).ok_or_else(|| bad(CMD, "degenerate quad"))?
+ } else if let Some(m) = p.get("matrix").and_then(Value::as_array) {
+ let v: Vec<f64> = m.iter().filter_map(Value::as_f64).collect();
+ if v.len() != 6 {
+ return Err(bad(CMD, "matrix must be [a, b, c, d, e, f]"));
+ }
+ Homography([v[0], v[2], v[4], v[1], v[3], v[5], 0.0, 0.0, 1.0])
+ } else {
+ affine_params(p, rect)
+ };
+ if h.inverse().is_none() {
+ return Err(bad(CMD, "the transform collapses the selection"));
+ }
+ if h.0.iter().zip(Homography::IDENTITY.0).all(|(a, b)| (a - b).abs() < 1e-12) {
+ return Ok(json!({"changed": false, "selected": true}));
+ }
+ let selected = s.edit("Transform Selection", |doc, _| {
+ if let Some(sel) = &doc.selection {
+ doc.selection = Some(crate::transform_cmds::warp_gray(sel, &h, interp)).filter(|s| !s.content_bounds().is_empty());
+ }
+ Ok(doc.selection.is_some())
+ })?;
+ Ok(json!({"changed": true, "selected": selected, "bounds": bounds_json(s)}))
+}
+
+fn bounds_json(s: &Session) -> Value {
+ match s.active().and_then(|d| d.doc.selection.as_ref()).map(|s| s.content_bounds()) {
+ Some(r) => json!([r.x0, r.y0, r.width() as i32, r.height() as i32]),
+ None => Value::Null,
+ }
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "select.sky",
+ label: "Sky",
+ menu: &["Select"],
+ shortcut: None,
+ params: r##"{"mode":"replace|add|subtract|intersect"="replace","sampleAllLayers":bool=true,"threshold":0..100=50 (higher = stricter),"softness":0..100=50 (edge softness)} → {selected, changed, coverage (0–1 of the canvas), bounds [x,y,w,h]}"##,
+ enabled: has_doc,
+ run: select_sky,
+ journal: true,
+ },
+ CommandSpec {
+ id: "select.isolateLayers",
+ label: "Isolate Layers",
+ menu: &["Select"],
+ shortcut: None,
+ params: r##"{"on":bool? (default: toggle)} — Layers panel lists only the selected layers → {isolated, layers}"##,
+ enabled: has_layer,
+ run: isolate_layers,
+ journal: false,
+ },
+ CommandSpec {
+ id: "select.transformSelection",
+ label: "Transform Selection",
+ menu: &["Select"],
+ shortcut: None,
+ params: r##"{"rect":[x0,y0,x1,y1]? (frame; default = selection bounds),"quad"|"corners":[[x,y]×4]? (where the frame's corners go: distort/perspective),"matrix":[a,b,c,d,e,f]?,"scaleX":%=100,"scaleY":%=100,"rotate":deg=0,"skewX":deg=0,"skewY":deg=0,"dx":px=0,"dy":px=0,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center","style"|"mesh"|"grid"|"warp":… (warp, as edit.transform.warp),"interpolation":"bilinear|bicubic|nearest"="bilinear"}"##,
+ enabled: has_selection,
+ run: transform_selection,
+ journal: true,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sel_bounds(s: &Session) -> Option<Rect> {
+ s.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds())
+ }
+
+ fn landscape(depth: u64) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 160, "height": 100, "depth": depth})).unwrap();
+ s.edit("paint", |doc, active| {
+ let l = doc.layer_mut(active.unwrap()).unwrap();
+ let surf = l.surface_mut().unwrap();
+ let n = surf.channels();
+ for y in 0..100 {
+ for x in 0..160 {
+ let (cx, cy) = (112.0f32, 35.0f32);
+ let crown = ((x as f32 - cx).powi(2) + (y as f32 - cy).powi(2)).sqrt() < 18.0;
+ let nz = (((x * 7919 + y * 104_729) % 97) as f32 / 97.0 - 0.5) * 0.25;
+ let c = if crown {
+ [0.1 + nz * 0.5, 0.35 + nz, 0.1]
+ } else if y < 60 {
+ let t = y as f32 / 60.0;
+ [0.25 + 0.4 * t, 0.5 + 0.3 * t, 0.9 + 0.05 * t]
+ } else {
+ [0.35 + nz, 0.3 + nz, 0.15]
+ };
+ let mut px = vec![1.0f32; n];
+ px[..3].copy_from_slice(&c);
+ surf.write_pixel(x, y, &px);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+ }
+
+ #[test]
+ fn sky_selects_the_sky_at_every_depth() {
+ for depth in [8, 16, 32] {
+ let mut s = landscape(depth);
+ let r = s.execute("select.sky", json!({})).unwrap();
+ assert_eq!(r["changed"], json!(true), "{depth}");
+ let cov = r["coverage"].as_f64().unwrap();
+ assert!(cov > 0.45 && cov < 0.62, "depth {depth}: coverage {cov}");
+ let sel = s.active().unwrap().doc.selection.clone().unwrap();
+ assert!(sel.sample_channel(10, 10, 0) > 0.9, "{depth}");
+ assert!(sel.sample_channel(10, 90, 0) < 0.1, "{depth}");
+ assert!(sel.sample_channel(112, 35, 0) < 0.1, "{depth}: tree");
+ s.undo();
+ assert!(s.active().unwrap().doc.selection.is_none());
+ }
+ }
+
+ #[test]
+ fn sky_without_sky_changes_nothing() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();
+ s.execute("edit.fill", json!({"color": "#504020"})).ok();
+ let r = s.execute("select.sky", json!({})).unwrap();
+ assert_eq!(r["changed"], json!(false));
+ assert!(s.active().unwrap().doc.selection.is_none());
+ }
+
+ #[test]
+ fn isolate_layers_toggles() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let active = s.active().unwrap().active_layer.unwrap();
+ let r = s.execute("select.isolateLayers", json!({})).unwrap();
+ assert_eq!(r["isolated"], json!(true));
+ assert_eq!(r["layers"], json!([active.0]));
+ let d = s.active().unwrap();
+ let bg = d.doc.layers[0].id;
+ assert!(isolation_shows(&d.doc, &d.isolated_layers, active));
+ assert!(!isolation_shows(&d.doc, &d.isolated_layers, bg));
+ assert_eq!(crate::inspect::document(d)["isolatedLayers"], json!([active.0]));
+ let r = s.execute("select.isolateLayers", json!({})).unwrap();
+ assert_eq!(r["isolated"], json!(false));
+ assert!(s.active().unwrap().isolated_layers.is_empty());
+ }
+
+ fn rect_sel() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
+ s.execute("select.rect", json!({"x": 20, "y": 30, "width": 20, "height": 10})).unwrap();
+ s
+ }
+
+ #[test]
+ fn transform_selection_scales_rotates_and_moves() {
+ let mut s = rect_sel();
+ assert_eq!(sel_bounds(&s), Some(Rect::new(20, 30, 40, 40)));
+ let px0 = s.active().unwrap().doc.layers[0].surface().unwrap().read_region(Rect::new(0, 0, 100, 100));
+ s.execute("select.transformSelection", json!({"scaleX": 200, "scaleY": 200})).unwrap();
+ let b = sel_bounds(&s).unwrap();
+ assert!((b.x0 - 10).abs() <= 1 && (b.x1 - 50).abs() <= 1 && (b.y0 - 25).abs() <= 1 && (b.y1 - 45).abs() <= 1, "{b:?}");
+ // Pixels untouched.
+ assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().read_region(Rect::new(0, 0, 100, 100)), px0);
+ s.undo();
+ assert_eq!(sel_bounds(&s), Some(Rect::new(20, 30, 40, 40)));
+ s.execute("select.transformSelection", json!({"rotate": 90})).unwrap();
+ let b = sel_bounds(&s).unwrap();
+ assert!(b.width().abs_diff(10) <= 2 && b.height().abs_diff(20) <= 2, "{b:?}");
+ s.undo();
+ s.execute("select.transformSelection", json!({"dx": 30, "dy": -10, "reference": "topLeft"})).unwrap();
+ assert_eq!(sel_bounds(&s), Some(Rect::new(50, 20, 70, 30)));
+ }
+
+ #[test]
+ fn transform_selection_perspective_and_warp() {
+ let mut s = rect_sel();
+ s.execute("select.transformSelection", json!({"corners": [[25, 30], [35, 30], [45, 40], [15, 40]]})).unwrap();
+ let sel = s.active().unwrap().doc.selection.clone().unwrap();
+ assert!(sel.sample_channel(17, 39, 0) > 0.5 && sel.sample_channel(21, 31, 0) < 0.5);
+ s.undo();
+ let r = s.execute("select.transformSelection", json!({"style": "arc", "bend": 50})).unwrap();
+ assert_eq!(r["changed"], json!(true));
+ assert_ne!(sel_bounds(&s), Some(Rect::new(20, 30, 40, 40)));
+ assert!(s.execute("select.transformSelection", json!({"scaleX": 0})).is_err());
+ }
+
+ #[test]
+ fn transform_selection_needs_a_selection() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 10, "height": 10})).unwrap();
+ assert!(!s.is_enabled("select.transformSelection"));
+ }
+}
diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/slice_cmds.rs
new file mode 100644
index 000000000..5ba6d40c1
--- /dev/null
+++ b/crates/engine/src/slice_cmds.rs
@@ -0,0 +1,449 @@
+//! Web slices: the Slice tool (`slice.new`, Slices From Guides), the Slice Select tool (`slice.set`
+//! = Slice Options, promote, divide, delete), Layer › New Layer Based Slice, View › Lock Slices and
+//! View › Clear Slices.
+//!
+//! The document stores user and layer-based slices (`Document::slices`); auto slices are derived
+//! (`photocraft_doc::slices::resolve`). Layer-based slices follow their layer: after every
+//! command [`refresh`] re-fits them to the layer's bounds including layer effects, plus outsets,
+//! without a history step of their own (the change is implied by the edit that moved the layer).
+//! Slices are addressed by stored id (`"slice"`) or by their displayed number (`"number"`).
+
+use std::sync::Arc;
+
+use photocraft_doc::slices::{self, ResolvedSlice, Slice, SliceKind, SliceOrigin};
+use photocraft_doc::{Document, Layer, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, layer_param};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+// ---------- predicates ----------
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn unlocked(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if s.file_menu.slices_locked { Err("slices are locked (View › Lock Slices)".into()) } else { Ok(()) }
+}
+
+fn has_slices(s: &Session) -> std::result::Result<(), String> {
+ unlocked(s)?;
+ if s.active().is_some_and(|d| !d.doc.slices.is_empty()) { Ok(()) } else { Err("the document has no user or layer-based slices".into()) }
+}
+
+fn has_layer_for_slice(s: &Session) -> std::result::Result<(), String> {
+ unlocked(s)?;
+ let d = s.active().ok_or("no document open")?;
+ let id = d.active_layer.ok_or("no active layer")?;
+ let l = d.doc.layer(id).ok_or("no active layer")?;
+ if matches!(l.content, LayerContent::Adjustment(_)) {
+ return Err("adjustment layers have no bounds to slice".into());
+ }
+ if d.doc.layers.first().is_some_and(|b| b.id == id && b.name == "Background" && b.locks.transparency && b.locks.position) {
+ return Err("the Background layer can't have a layer-based slice".into());
+ }
+ if d.doc.slices.list.iter().any(|s| s.layer == Some(id)) {
+ return Err("the layer already has a layer-based slice".into());
+ }
+ Ok(())
+}
+
+// ---------- geometry ----------
+
+/// Bounds of a layer's pixels plus its layer effects (groups: the union of their children).
+pub fn layer_bounds(l: &Layer) -> Rect {
+ let own = match &l.content {
+ LayerContent::Group(g) => match &g.artboard {
+ Some(a) => a.rect,
+ None => g.children.iter().filter(|c| c.visible).map(layer_bounds).fold(Rect::EMPTY, |a, b| if a.is_empty() { b } else if b.is_empty() { a } else { a.union(&b) }),
+ },
+ _ => photocraft_doc::comps::position_bounds(l),
+ };
+ if own.is_empty() || !photocraft_compose::effects::has_effects(l) {
+ return own;
+ }
+ own.inflate(photocraft_compose::effects::margin(l))
+}
+
+fn layer_slice_rect(doc: &Document, s: &Slice) -> Option<Rect> {
+ let l = doc.layer(s.layer?)?;
+ let b = layer_bounds(l);
+ let [t, le, bo, r] = s.outsets;
+ Some(if b.is_empty() { b } else { Rect::new(b.x0 - le, b.y0 - t, b.x1 + r, b.y1 + bo) })
+}
+
+/// Re-fits layer-based slices of the active document to their layers; drops slices whose layer
+/// was deleted (as Photoshop does). Not a history step.
+pub(crate) fn refresh(s: &mut Session) {
+ let Some(st) = s.active_mut() else { return };
+ if !st.doc.slices.list.iter().any(|sl| sl.origin == SliceOrigin::Layer) {
+ return;
+ }
+ let doc = &st.doc;
+ let mut changes: Vec<(u32, Option<Rect>)> = Vec::new();
+ for sl in doc.slices.list.iter().filter(|sl| sl.origin == SliceOrigin::Layer) {
+ let r = layer_slice_rect(doc, sl);
+ if r != Some(sl.rect) {
+ changes.push((sl.id, r));
+ }
+ }
+ if changes.is_empty() {
+ return;
+ }
+ let doc = Arc::make_mut(&mut st.doc);
+ for (id, r) in changes {
+ match r {
+ Some(r) => {
+ if let Some(sl) = doc.slices.get_mut(id) {
+ sl.rect = r;
+ }
+ }
+ None => doc.slices.list.retain(|sl| sl.id != id),
+ }
+ }
+}
+
+// ---------- params ----------
+
+pub(crate) fn rect_param(p: &Value) -> Option<Rect> {
+ let f = |v: &Value| v.as_f64().filter(|x| x.is_finite()).map(|x| x.round() as i32);
+ if let Some(a) = p.get("rect").and_then(Value::as_array).filter(|a| a.len() == 4) {
+ let v: Vec<i32> = a.iter().filter_map(f).collect();
+ if v.len() == 4 && v[2] > 0 && v[3] > 0 {
+ return Some(Rect::new(v[0], v[1], v[0] + v[2], v[1] + v[3]));
+ }
+ return None;
+ }
+ let (x, y, w, h) = (f(p.get("x")?)?, f(p.get("y")?)?, f(p.get("width")?)?, f(p.get("height")?)?);
+ (w > 0 && h > 0).then(|| Rect::new(x, y, x + w, y + h))
+}
+
+fn hex_color(s: &str) -> Option<[u8; 4]> {
+ let s = s.trim_start_matches('#');
+ let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok();
+ match s.len() {
+ 6 => Some([255, b(0)?, b(2)?, b(4)?]),
+ _ => None,
+ }
+}
+
+/// Slice Options fields present in `p` applied to `sl`.
+fn apply_options(sl: &mut Slice, p: &Value, cmd: &str) -> Result<()> {
+ let text = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
+ if let Some(v) = text("name") {
+ sl.name = v;
+ }
+ if let Some(v) = text("kind").or_else(|| text("type")) {
+ sl.kind = SliceKind::from_id(&v).ok_or_else(|| bad(cmd, format!("unknown slice type `{v}` (image|noImage|table)")))?;
+ }
+ for (k, slot) in [("url", &mut sl.url), ("target", &mut sl.target), ("message", &mut sl.message), ("alt", &mut sl.alt), ("cellText", &mut sl.cell_text)] {
+ if let Some(v) = text(k) {
+ *slot = v;
+ }
+ }
+ if let Some(b) = p.get("cellTextIsHtml").and_then(Value::as_bool) {
+ sl.cell_text_is_html = b;
+ }
+ for (k, slot) in [("horizontalAlign", &mut sl.horizontal_align), ("verticalAlign", &mut sl.vertical_align)] {
+ if let Some(v) = p.get(k).and_then(Value::as_u64) {
+ *slot = v.min(4) as u32;
+ }
+ }
+ match p.get("background").and_then(Value::as_str) {
+ Some("none") | Some("") => sl.background = None,
+ Some(c) => sl.background = Some(hex_color(c).ok_or_else(|| bad(cmd, "background is \"none\" or \"#rrggbb\""))?),
+ None => {}
+ }
+ if let Some(a) = p.get("outsets").and_then(Value::as_array).filter(|a| a.len() == 4) {
+ for (i, v) in a.iter().enumerate() {
+ sl.outsets[i] = v.as_i64().unwrap_or(0).clamp(-10_000, 10_000) as i32;
+ }
+ }
+ if let Some(r) = rect_param(p) {
+ if sl.origin == SliceOrigin::Layer {
+ // Editing a layer-based slice's geometry promotes it to a user slice.
+ sl.origin = SliceOrigin::User;
+ sl.layer = None;
+ }
+ sl.rect = r;
+ }
+ Ok(())
+}
+
+/// The stored slice addressed by `"slice"` (id) or `"number"`; an auto slice's number promotes
+/// it to a user slice first when `promote` is set.
+fn target(s: &mut Session, p: &Value, cmd: &str, promote: bool) -> Result<u32> {
+ if let Some(id) = p.get("slice").and_then(Value::as_u64) {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ return d.doc.slices.get(id as u32).map(|sl| sl.id).ok_or_else(|| bad(cmd, format!("no slice with id {id}")));
+ }
+ let n = p.get("number").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "give \"slice\" (id) or \"number\""))? as usize;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let r = slices::resolve(&d.doc).into_iter().find(|r| r.number == n).ok_or_else(|| bad(cmd, format!("no slice number {n}")))?;
+ match r.id {
+ Some(id) => Ok(id),
+ None if promote => {
+ let rect = r.rect;
+ s.edit("Promote to User Slice", |doc, _| {
+ let id = doc.slices.next_id();
+ doc.slices.list.push(Slice { id, rect, ..Default::default() });
+ Ok(id)
+ })
+ }
+ None => Err(bad(cmd, format!("slice {n} is an auto slice"))),
+ }
+}
+
+pub fn resolved_json(doc: &Document, r: &ResolvedSlice) -> Value {
+ let s = r.id.and_then(|id| doc.slices.get(id));
+ json!({
+ "number": r.number,
+ "id": r.id,
+ "origin": r.origin.id(),
+ "name": r.name,
+ "rect": [r.rect.x0, r.rect.y0, r.rect.width(), r.rect.height()],
+ "kind": r.kind.id(),
+ "layer": s.and_then(|s| s.layer).map(|l| l.0),
+ "url": s.map_or("", |s| s.url.as_str()),
+ "target": s.map_or("", |s| s.target.as_str()),
+ "message": s.map_or("", |s| s.message.as_str()),
+ "alt": s.map_or("", |s| s.alt.as_str()),
+ "cellText": s.map_or("", |s| s.cell_text.as_str()),
+ "background": s.and_then(|s| s.background).map(|c| format!("#{:02x}{:02x}{:02x}", c[1], c[2], c[3])),
+ })
+}
+
+// ---------- commands ----------
+
+fn new_slice(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "slice.new";
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let rect = rect_param(p).ok_or_else(|| bad(cmd, "give \"rect\":[x,y,w,h] (or x, y, width, height)"))?.intersect(&d.doc.bounds());
+ if rect.is_empty() {
+ return Err(bad(cmd, "the slice is outside the canvas"));
+ }
+ let id = s.edit("Slice", |doc, _| {
+ let id = doc.slices.next_id();
+ let mut sl = Slice { id, rect, ..Default::default() };
+ apply_options(&mut sl, p, cmd)?;
+ sl.rect = rect;
+ doc.slices.list.push(sl);
+ Ok(id)
+ })?;
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let number = slices::resolve(doc).iter().find(|r| r.id == Some(id)).map(|r| r.number);
+ Ok(json!({"slice": id, "number": number}))
+}
+
+fn from_guides(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let b = d.doc.bounds();
+ let mut xs: Vec<i32> = vec![b.x0, b.x1];
+ let mut ys: Vec<i32> = vec![b.y0, b.y1];
+ xs.extend(d.doc.guides.vertical.iter().map(|g| (*g as f64).round() as i32).filter(|x| *x > b.x0 && *x < b.x1));
+ ys.extend(d.doc.guides.horizontal.iter().map(|g| (*g as f64).round() as i32).filter(|y| *y > b.y0 && *y < b.y1));
+ if xs.len() == 2 && ys.len() == 2 {
+ return Err(EngineError::Other("the document has no guides inside the canvas".into()));
+ }
+ xs.sort_unstable();
+ xs.dedup();
+ ys.sort_unstable();
+ ys.dedup();
+ let mut rects = Vec::new();
+ for yw in ys.windows(2) {
+ for xw in xs.windows(2) {
+ rects.push(Rect::new(xw[0], yw[0], xw[1], yw[1]));
+ }
+ }
+ let n = rects.len();
+ s.edit("Slices From Guides", |doc, _| {
+ // Photoshop replaces every existing slice.
+ doc.slices.list.clear();
+ for r in rects {
+ let id = doc.slices.next_id();
+ doc.slices.list.push(Slice { id, rect: r, ..Default::default() });
+ }
+ Ok(())
+ })?;
+ Ok(json!({"slices": n}))
+}
+
+fn set_slice(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "slice.set";
+ let id = target(s, p, cmd, true)?;
+ let coalesce_into_promote = s.active().is_some_and(|d| d.history.undo_label() == Some("Promote to User Slice")) && p.get("number").is_some();
+ let label = "Slice Options";
+ let run = |doc: &mut Document, _: &mut Option<LayerId>| -> Result<()> {
+ let sl = doc.slices.get_mut(id).ok_or_else(|| bad(cmd, "slice vanished"))?;
+ apply_options(sl, p, cmd)?;
+ Ok(())
+ };
+ if coalesce_into_promote {
+ // Promote + options are one user action: fold the options into the promote step.
+ let st = s.active_mut().ok_or(EngineError::NoDocument)?;
+ let mut doc = (*st.doc).clone();
+ let mut a = st.active_layer;
+ run(&mut doc, &mut a)?;
+ st.doc = Arc::new(doc);
+ st.revision += 1;
+ st.last_damage = None;
+ } else {
+ s.edit(label, run)?;
+ }
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let r = slices::resolve(&d.doc).into_iter().find(|r| r.id == Some(id)).ok_or_else(|| bad(cmd, "slice is off the canvas"))?;
+ Ok(resolved_json(&d.doc, &r))
+}
+
+fn promote(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "slice.promote";
+ let id = target(s, p, cmd, true)?;
+ // Layer-based slices promote too: they stop following their layer.
+ let is_layer = s.active().and_then(|d| d.doc.slices.get(id)).is_some_and(|sl| sl.origin == SliceOrigin::Layer);
+ if is_layer {
+ s.edit("Promote to User Slice", |doc, _| {
+ if let Some(sl) = doc.slices.get_mut(id) {
+ sl.origin = SliceOrigin::User;
+ sl.layer = None;
+ }
+ Ok(())
+ })?;
+ }
+ Ok(json!({"slice": id}))
+}
+
+fn ids_param(s: &mut Session, p: &Value, cmd: &str) -> Result<Vec<u32>> {
+ if let Some(a) = p.get("slices").and_then(Value::as_array) {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let ids: Vec<u32> = a.iter().filter_map(Value::as_u64).map(|v| v as u32).filter(|id| d.doc.slices.get(*id).is_some()).collect();
+ if ids.is_empty() {
+ return Err(bad(cmd, "none of the slices exist"));
+ }
+ return Ok(ids);
+ }
+ Ok(vec![target(s, p, cmd, false)?])
+}
+
+fn delete(s: &mut Session, p: &Value) -> Result<Value> {
+ let ids = ids_param(s, p, "slice.delete")?;
+ let n = ids.len();
+ s.edit("Delete Slice", |doc, _| {
+ doc.slices.list.retain(|sl| !ids.contains(&sl.id));
+ Ok(())
+ })?;
+ Ok(json!({"deleted": n}))
+}
+
+fn divide(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "slice.divide";
+ let id = target(s, p, cmd, true)?;
+ let down = p.get("horizontal").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1000) as i32;
+ let across = p.get("vertical").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1000) as i32;
+ if down == 1 && across == 1 {
+ return Err(bad(cmd, "give \"horizontal\" (slices down) and/or \"vertical\" (slices across) > 1"));
+ }
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let src = d.doc.slices.get(id).cloned().ok_or_else(|| bad(cmd, "no such slice"))?;
+ let r = src.rect;
+ if (r.width() as i32) < across || (r.height() as i32) < down {
+ return Err(bad(cmd, "the slice is too small to divide that many times"));
+ }
+ let n = (down * across) as usize;
+ let ids = s.edit("Divide Slice", |doc, _| {
+ let pos = doc.slices.list.iter().position(|sl| sl.id == id).unwrap_or(0);
+ doc.slices.list.retain(|sl| sl.id != id);
+ let mut ids = Vec::new();
+ let mut parts = Vec::new();
+ for j in 0..down {
+ for i in 0..across {
+ let x0 = r.x0 + (r.width() as i32 * i) / across;
+ let x1 = r.x0 + (r.width() as i32 * (i + 1)) / across;
+ let y0 = r.y0 + (r.height() as i32 * j) / down;
+ let y1 = r.y0 + (r.height() as i32 * (j + 1)) / down;
+ let nid = if ids.is_empty() { id } else { doc.slices.next_id().max(ids.iter().copied().max().unwrap_or(0) + 1) };
+ ids.push(nid);
+ // The first part keeps the original's options; the others start fresh.
+ let base = if parts.is_empty() { Slice { origin: SliceOrigin::User, layer: None, ..src.clone() } } else { Slice::default() };
+ parts.push(Slice { id: nid, rect: Rect::new(x0, y0, x1, y1), ..base });
+ }
+ }
+ for (k, sl) in parts.into_iter().enumerate() {
+ doc.slices.list.insert((pos + k).min(doc.slices.list.len()), sl);
+ }
+ Ok(ids)
+ })?;
+ Ok(json!({"slices": ids, "count": n}))
+}
+
+fn list(s: &mut Session) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let all: Vec<Value> = slices::resolve(&d.doc).iter().map(|r| resolved_json(&d.doc, r)).collect();
+ Ok(json!({"slices": all, "locked": s.file_menu.slices_locked}))
+}
+
+fn layer_based(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "layer.newLayerBasedSlice";
+ let layer = layer_param(s, p)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let l = d.doc.layer(layer).ok_or(EngineError::NoLayer(layer))?;
+ if d.doc.slices.list.iter().any(|sl| sl.layer == Some(layer)) {
+ return Err(bad(cmd, "the layer already has a layer-based slice"));
+ }
+ let rect = layer_bounds(l);
+ if rect.is_empty() {
+ return Err(EngineError::Other("Could not create a layer based slice because the layer is empty".into()));
+ }
+ let id = s.edit("New Layer Based Slice", |doc, _| {
+ let id = doc.slices.next_id();
+ let text = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
+ doc.slices.list.push(Slice { id, origin: SliceOrigin::Layer, layer: Some(layer), rect, name: text("name"), url: text("url"), alt: text("alt"), ..Default::default() });
+ Ok(id)
+ })?;
+ Ok(json!({"slice": id, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
+}
+
+fn lock(s: &mut Session, p: &Value) -> Result<Value> {
+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(!s.file_menu.slices_locked);
+ s.file_menu.slices_locked = on;
+ Ok(json!({"locked": on}))
+}
+
+fn clear(s: &mut Session) -> Result<Value> {
+ let n = s.active().map_or(0, |d| d.doc.slices.list.len());
+ s.edit("Clear Slices", |doc, _| {
+ doc.slices.list.clear();
+ Ok(())
+ })?;
+ Ok(json!({"cleared": n}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ vec![
+ spec!("slice.new", "Slice Tool", &[], r##"{"rect":[x,y,w,h] | "x","y","width","height", plus Slice Options ("name","kind":"image|noImage|table","url","target","message","alt","cellText","cellTextIsHtml","background":"none|#rrggbb")?} → {slice, number}"##, unlocked, new_slice),
+ spec!("slice.fromGuides", "Slices From Guides", &[], "{} (replaces every slice by the grid of the canvas guides) → {slices}", unlocked, |s, _| from_guides(s)),
+ spec!("slice.set", "Slice Options…", &[], r##"{"slice":id | "number":n (an auto slice is promoted), "name"?,"kind":"image|noImage|table"?,"url"?,"target"?,"message"?,"alt"?,"cellText"?,"cellTextIsHtml"?,"horizontalAlign":0..4?,"verticalAlign":0..4?,"background":"none|#rrggbb"?,"outsets":[t,l,b,r]? (layer slices),"rect":[x,y,w,h]? (move/resize; a layer slice becomes a user slice)} → the slice"##, unlocked, set_slice),
+ spec!("slice.promote", "Promote", &[], r##"{"slice":id | "number":n} (auto or layer-based → user slice) → {slice}"##, unlocked, promote),
+ spec!("slice.delete", "Delete Slice", &[], r##"{"slice":id | "number":n | "slices":[id…]} → {deleted}"##, has_slices, delete),
+ spec!("slice.divide", "Divide Slice…", &[], r##"{"slice":id | "number":n,"horizontal":n=1 (slices down),"vertical":n=1 (slices across)} → {slices}"##, unlocked, divide),
+ CommandSpec { id: "slice.list", label: "List Slices", menu: &[], shortcut: None, params: "{} → {slices:[{number,id,origin:auto|layer|user,name,rect:[x,y,w,h],kind,layer,url,alt,…}], locked}", enabled: has_doc, journal: false, run: |s, _| list(s) },
+ spec!("layer.newLayerBasedSlice", "New Layer Based Slice", &["Layer"], r##"{"layer":id?,"name":str?,"url":str?,"alt":str?} (follows the layer's bounds with effects) → {slice, rect}"##, has_layer_for_slice, layer_based),
+ spec!("view.lockSlices", "Lock Slices", &["View"], r##"{"on":bool? (default: toggle)} → {locked}"##, has_doc, lock),
+ spec!("view.clearSlices", "Clear Slices", &["View"], "{} (deletes every user and layer-based slice) → {cleared}", has_slices, |s, _| clear(s)),
+ ]
+}
+
+#[cfg(test)]
+#[path = "slice_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/slice_cmds/tests.rs b/crates/engine/src/slice_cmds/tests.rs
new file mode 100644
index 000000000..7e6c80326
--- /dev/null
+++ b/crates/engine/src/slice_cmds/tests.rs
@@ -0,0 +1,160 @@
+use super::*;
+use photocraft_doc::effects::Effect;
+
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 120, "height": 90, "depth": depth, "name": "site"})).unwrap();
+ s
+}
+
+fn doc(s: &Session) -> &Document {
+ &s.active().unwrap().doc
+}
+
+fn add_square(s: &mut Session, r: Rect) -> LayerId {
+ s.edit("sq", |doc, active| {
+ let fmt = doc.pixel_format();
+ let mut l = Layer::raster(doc.next_layer_name("Layer"), fmt);
+ l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
+ let id = doc.insert_above(None, l);
+ *active = Some(id);
+ Ok(id)
+ })
+ .unwrap()
+}
+
+#[test]
+fn user_slices_and_options() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let r = s.execute("slice.new", json!({"rect": [20, 10, 40, 20], "name": "logo", "url": "https://example.org", "alt": "Logo"})).unwrap();
+ let id = r["slice"].as_u64().unwrap() as u32;
+ assert_eq!(r["number"], json!(3), "top band, left cell, then the slice");
+ let l = s.execute("slice.list", json!({})).unwrap();
+ let all = l["slices"].as_array().unwrap();
+ assert_eq!(all.len(), 5);
+ let me = all.iter().find(|v| v["id"] == json!(id)).unwrap();
+ assert_eq!(me["name"], "logo");
+ assert_eq!(me["rect"], json!([20, 10, 40, 20]));
+ assert_eq!(me["origin"], "user");
+ assert!(all.iter().filter(|v| v["origin"] == "auto").count() == 4);
+ // Slice Options by number; then undo.
+ s.execute("slice.set", json!({"number": 3, "kind": "noImage", "cellText": "hi", "background": "#ff0000"})).unwrap();
+ let sl = doc(&s).slices.get(id).unwrap();
+ assert_eq!(sl.kind, SliceKind::NoImage);
+ assert_eq!(sl.background, Some([255, 255, 0, 0]));
+ assert!(s.undo());
+ assert_eq!(doc(&s).slices.get(id).unwrap().kind, SliceKind::Image);
+ assert!(s.execute("slice.set", json!({"slice": id, "kind": "bogus"})).is_err());
+ assert!(s.execute("slice.new", json!({"rect": [500, 500, 10, 10]})).is_err(), "outside the canvas");
+ }
+}
+
+#[test]
+fn promote_auto_slice_and_divide() {
+ let mut s = session(8);
+ s.execute("slice.new", json!({"rect": [0, 0, 60, 45]})).unwrap();
+ // An auto slice promoted through Slice Options keeps one history step.
+ let before = s.active().unwrap().history.past_len();
+ let r = s.execute("slice.set", json!({"number": 2, "name": "right"})).unwrap();
+ assert_eq!(r["origin"], "user");
+ assert_eq!(r["name"], "right");
+ assert_eq!(s.active().unwrap().history.past_len(), before + 1);
+ assert_eq!(doc(&s).slices.list.len(), 2);
+ let id = doc(&s).slices.list[0].id;
+ let r = s.execute("slice.divide", json!({"slice": id, "horizontal": 3, "vertical": 2})).unwrap();
+ assert_eq!(r["count"], 6);
+ assert_eq!(doc(&s).slices.list.len(), 7);
+ let total: u64 = doc(&s).slices.list.iter().take(6).map(|s| u64::from(s.rect.width()) * u64::from(s.rect.height())).sum();
+ assert_eq!(total, 60 * 45);
+ assert!(s.execute("slice.divide", json!({"slice": id})).is_err());
+}
+
+#[test]
+fn slices_from_guides_and_clear() {
+ let mut s = session(8);
+ s.edit("guides", |d, _| {
+ d.guides.vertical = vec![40.0, 80.0];
+ d.guides.horizontal = vec![30.0];
+ Ok(())
+ })
+ .unwrap();
+ s.slice_from_guides_check();
+ assert!(s.is_enabled("view.clearSlices"));
+ let r = s.execute("view.clearSlices", json!({})).unwrap();
+ assert_eq!(r["cleared"], 6);
+ assert!(doc(&s).slices.is_empty());
+ assert!(!s.is_enabled("view.clearSlices"));
+}
+
+impl Session {
+ fn slice_from_guides_check(&mut self) {
+ let r = self.execute("slice.fromGuides", json!({})).unwrap();
+ assert_eq!(r["slices"], 6);
+ let rects: Vec<Rect> = self.active().unwrap().doc.slices.list.iter().map(|s| s.rect).collect();
+ assert!(rects.contains(&Rect::new(40, 30, 80, 90)));
+ }
+}
+
+#[test]
+fn lock_slices_blocks_editing() {
+ let mut s = session(8);
+ s.execute("slice.new", json!({"rect": [0, 0, 10, 10]})).unwrap();
+ assert_eq!(s.execute("view.lockSlices", json!({})).unwrap()["locked"], true);
+ assert!(!s.is_enabled("slice.new"));
+ assert!(!s.is_enabled("view.clearSlices"));
+ assert!(s.execute("slice.new", json!({"rect": [0, 0, 10, 10]})).is_err());
+ s.execute("view.lockSlices", json!({"on": false})).unwrap();
+ assert!(s.is_enabled("slice.new"));
+}
+
+#[test]
+fn layer_based_slice_follows_the_layer_and_its_effects() {
+ for depth in [8, 16] {
+ let mut s = session(depth);
+ assert!(!s.is_enabled("layer.newLayerBasedSlice"), "Background layer");
+ let id = add_square(&mut s, Rect::new(10, 10, 30, 20));
+ let r = s.execute("layer.newLayerBasedSlice", json!({})).unwrap();
+ assert_eq!(r["rect"], json!([10, 10, 20, 10]));
+ assert!(!s.is_enabled("layer.newLayerBasedSlice"), "one per layer");
+ let sid = r["slice"].as_u64().unwrap() as u32;
+ // Moving the layer moves the slice.
+ s.execute("layer.translate", json!({"layer": id.0, "dx": 5, "dy": 7})).unwrap();
+ assert_eq!(doc(&s).slices.get(sid).unwrap().rect, Rect::new(15, 17, 35, 27));
+ // A drop shadow grows it.
+ s.edit("fx", |d, _| {
+ let l = d.layer_mut(id).unwrap();
+ l.effects.enabled = true;
+ l.effects.items.push(Effect::default_drop_shadow());
+ Ok(())
+ })
+ .unwrap();
+ s.execute("slice.list", json!({})).unwrap();
+ let grown = doc(&s).slices.get(sid).unwrap().rect;
+ assert!(grown.contains_rect(&Rect::new(15, 17, 35, 27)) && grown != Rect::new(15, 17, 35, 27), "{grown:?}");
+ // Deleting the layer deletes its slice.
+ s.execute("layer.delete", json!({"layer": id.0})).unwrap();
+ assert!(doc(&s).slices.get(sid).is_none());
+ }
+}
+
+#[test]
+fn slices_round_trip_through_psd_and_pcraft() {
+ let mut s = session(8);
+ add_square(&mut s, Rect::new(50, 40, 70, 60));
+ s.execute("layer.newLayerBasedSlice", json!({})).unwrap();
+ s.execute("slice.new", json!({"rect": [5, 5, 30, 20], "name": "hero", "url": "https://example.org", "alt": "Hero", "target": "_blank"})).unwrap();
+ let d = doc(&s).clone();
+ for ext in ["psd", "pcraft"] {
+ let bytes = photocraft_io::export(&d, &format!("x.{ext}"), &Default::default()).unwrap().bytes;
+ let back = photocraft_io::import(&format!("x.{ext}"), &bytes).unwrap().document;
+ assert_eq!(back.slices.list.len(), 2, "{ext}");
+ let hero = back.slices.list.iter().find(|s| s.name == "hero").unwrap();
+ assert_eq!((hero.url.as_str(), hero.alt.as_str(), hero.target.as_str()), ("https://example.org", "Hero", "_blank"));
+ assert_eq!(hero.rect, Rect::new(5, 5, 35, 25));
+ let ls = back.slices.list.iter().find(|s| s.origin == SliceOrigin::Layer).unwrap();
+ let layer = back.layer(ls.layer.unwrap()).unwrap();
+ assert_eq!(layer.name, "Layer 1", "{ext}: the slice still names its layer");
+ assert_eq!(ls.rect, Rect::new(50, 40, 70, 60));
+ }
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 4411679fd..dfa25cd27 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -435,3 +435,50 @@ fn moving_a_layer_moves_its_effects_reference_point() {
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
assert_eq!(l.effects.reference, Some((-191.0, 14.0)));
}
+
+#[test]
+fn marquee_feather_and_anti_aliased_ellipse() {
+ let sel_at = |s: &Session, x: i32, y: i32| {
+ let mut v = [0.0f32];
+ if let Some(m) = s.active().unwrap().doc.selection.as_ref() {
+ m.read_pixel(x, y, &mut v);
+ }
+ v[0]
+ };
+ // Hard rectangle: fully in or out.
+ let mut s = session_with_doc();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
+ assert_eq!(sel_at(&s, 10, 20), 1.0);
+ assert_eq!(sel_at(&s, 9, 20), 0.0);
+ // Feather softens only the new shape's edge: partial coverage across the boundary.
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20, "feather": 3})).unwrap();
+ let (inside, edge, outside) = (sel_at(&s, 20, 20), sel_at(&s, 10, 20), sel_at(&s, 8, 20));
+ assert!(inside > 0.95 && edge > 0.2 && edge < 0.8 && outside > 0.0 && outside < edge, "{inside} {edge} {outside}");
+ // Anti-aliased ellipse edges have partial coverage; aliased ones don't.
+ let partial = |s: &Session| (0..48).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| (0.01..0.99).contains(&sel_at(s, x, y))).count();
+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 40, "height": 30, "ellipse": true})).unwrap();
+ assert!(partial(&s) > 20);
+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 40, "height": 30, "ellipse": true, "antiAlias": false})).unwrap();
+ assert_eq!(partial(&s), 0);
+}
+
+#[test]
+fn file_new_resolution_and_background_color() {
+ let mut s = Session::new();
+ s.tools.background = [1.0, 0.0, 0.0, 1.0];
+ s.execute("file.new", json!({"width": 8, "height": 8, "resolution": 300, "background": "backgroundColor"})).unwrap();
+ assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0);
+ let p = px(&mut s, 2, 2);
+ assert!(p[0] > 0.99 && p[1] < 0.01, "{p:?}");
+}
+
+#[test]
+fn duplicating_the_background_unlocks_the_copy() {
+ let mut s = session_with_doc();
+ s.execute("layer.duplicate", json!({})).unwrap();
+ let st = s.active().unwrap();
+ let copy = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ assert_eq!(copy.name, "Background copy");
+ assert_eq!(copy.locks, photocraft_doc::Locks::default());
+ assert!(st.doc.layers[0].locks.transparency);
+}
diff --git a/crates/engine/src/type_spell_cmds.rs b/crates/engine/src/type_spell_cmds.rs
new file mode 100644
index 000000000..507a903a1
--- /dev/null
+++ b/crates/engine/src/type_spell_cmds.rs
@@ -0,0 +1,317 @@
+//! Edit › Check Spelling… and glyph insertion (Window › Glyphs).
+//!
+//! `edit.checkSpelling` checks type layers against the bundled English dictionary
+//! (`photocraft_text::spell`, SCOWL size 50) plus the user dictionary in the preferences
+//! (`userDictionary`). Headless, it lists misspellings with suggestions and changes, changes all,
+//! or adds words to the dictionary; the UI's dialog drives the same actions. Offsets are
+//! character indices.
+//!
+//! `type.insertText` inserts a string (a glyph) into a type layer at a character position or
+//! over a range.
+
+use std::collections::HashSet;
+
+use photocraft_doc::{Document, LayerContent, LayerId};
+use photocraft_text::spell::Dictionary;
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, layer_param};
+use crate::type_cmds::{refresh, replace_text};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn byte_at(text: &str, ci: usize) -> usize {
+ text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b)
+}
+
+fn char_at(text: &str, bi: usize) -> usize {
+ text[..bi.min(text.len())].chars().count()
+}
+
+/// Type layers top to bottom (Layers panel order), skipping fully locked ones.
+fn type_layers(doc: &Document) -> Vec<LayerId> {
+ doc.walk().into_iter().rev().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_)) && !l.locks.all).map(|(_, _, l)| l.id).collect()
+}
+
+fn has_type(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ if type_layers(&d.doc).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) }
+}
+
+fn text(doc: &Document, id: LayerId) -> Option<&str> {
+ match &doc.layer(id)?.content {
+ LayerContent::Text(t) => Some(&t.text),
+ _ => None,
+ }
+}
+
+/// The user dictionary plus `ignore` words, lowercased.
+fn accepted(s: &Session, p: &Value) -> HashSet<String> {
+ let mut set: HashSet<String> = s.prefs().user_dictionary.iter().map(|w| w.to_lowercase()).collect();
+ if let Some(a) = p.get("ignore").and_then(Value::as_array) {
+ set.extend(a.iter().filter_map(Value::as_str).map(str::to_lowercase));
+ }
+ set
+}
+
+fn layers_param(s: &Session, p: &Value) -> Vec<LayerId> {
+ let Some(st) = s.active() else { return Vec::new() };
+ let all = type_layers(&st.doc);
+ if p.get("allLayers").and_then(Value::as_bool) == Some(false) || p.get("layer").is_some() {
+ let active = layer_param(s, p).ok();
+ all.into_iter().filter(|id| Some(*id) == active).collect()
+ } else {
+ all
+ }
+}
+
+fn list(s: &Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let dict = Dictionary::english();
+ let ok = accepted(s, p);
+ let max = p.get("suggestions").and_then(Value::as_u64).unwrap_or(5) as usize;
+ let mut out = Vec::new();
+ for id in layers_param(s, p) {
+ let Some(t) = text(&st.doc, id) else { continue };
+ for m in dict.misspellings(t, &ok) {
+ out.push(json!({ "layer": id.0, "start": char_at(t, m.start), "end": char_at(t, m.end), "word": m.word, "suggestions": dict.suggest(&m.word, max) }));
+ }
+ }
+ Ok(json!({ "misspellings": out, "count": out.len() }))
+}
+
+/// Replaces one occurrence (verified to still be `word` when given).
+fn change(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.checkSpelling";
+ let id = LayerId(p.get("layer").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`change` needs `layer`"))?);
+ let start = p.get("start").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`change` needs `start`"))? as usize;
+ let end = p.get("end").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`change` needs `end`"))? as usize;
+ let to = p.get("replace").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`change` needs `replace`"))?.to_string();
+ let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let t = text(&doc, id).ok_or_else(|| bad(cmd, format!("layer {} is not a type layer", id.0)))?;
+ let (a, b) = (byte_at(t, start), byte_at(t, end.max(start)));
+ if let Some(w) = p.get("word").and_then(Value::as_str)
+ && &t[a..b] != w
+ {
+ return Err(bad(cmd, format!("the text at {start}..{end} is {:?}, not {w:?}", &t[a..b])));
+ }
+ s.edit("Check Spelling", |doc, _| {
+ let snapshot = doc.clone();
+ if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {
+ replace_text(t, a, b, &to);
+ refresh(&snapshot, t);
+ }
+ Ok(())
+ })?;
+ Ok(json!({ "changed": 1, "layer": id.0, "start": start, "end": start + to.chars().count() }))
+}
+
+/// Replaces every whole-word, case-sensitive occurrence of `word` in the checked layers.
+fn change_all(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "edit.checkSpelling";
+ let word = p.get("word").and_then(Value::as_str).filter(|w| !w.is_empty()).ok_or_else(|| bad(cmd, "`changeAll` needs `word`"))?.to_string();
+ let to = p.get("replace").and_then(Value::as_str).ok_or_else(|| bad(cmd, "`changeAll` needs `replace`"))?.to_string();
+ let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let plan: Vec<(LayerId, Vec<(usize, usize)>)> = layers_param(s, p)
+ .into_iter()
+ .filter_map(|id| {
+ let t = text(&doc, id)?;
+ let hits: Vec<(usize, usize)> = photocraft_text::spell::words(t).into_iter().filter(|(a, b)| t[*a..*b] == word).collect();
+ (!hits.is_empty()).then_some((id, hits))
+ })
+ .collect();
+ let count: usize = plan.iter().map(|(_, h)| h.len()).sum();
+ if count > 0 {
+ s.edit("Check Spelling", |doc, _| {
+ let snapshot = doc.clone();
+ for (id, hits) in &plan {
+ if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) {
+ for (a, b) in hits.iter().rev() {
+ replace_text(t, *a, *b, &to);
+ }
+ refresh(&snapshot, t);
+ }
+ }
+ Ok(())
+ })?;
+ }
+ Ok(json!({ "changed": count, "layers": plan.len() }))
+}
+
+fn add_word(s: &mut Session, p: &Value) -> Result<Value> {
+ let word = p.get("word").and_then(Value::as_str).map(str::trim).filter(|w| !w.is_empty() && !w.contains(char::is_whitespace)).ok_or_else(|| bad("edit.checkSpelling", "`add` needs a single `word`"))?.to_string();
+ let added = s.edit_prefs(|pr| {
+ if pr.user_dictionary.iter().any(|w| w.eq_ignore_ascii_case(&word)) {
+ false
+ } else {
+ pr.user_dictionary.push(word.clone());
+ pr.user_dictionary.sort_by_key(|w| w.to_lowercase());
+ true
+ }
+ });
+ Ok(json!({ "added": added, "word": word, "userDictionary": s.prefs().user_dictionary }))
+}
+
+fn remove_word(s: &mut Session, p: &Value) -> Result<Value> {
+ let word = p.get("word").and_then(Value::as_str).unwrap_or("").to_string();
+ let removed = s.edit_prefs(|pr| {
+ let n = pr.user_dictionary.len();
+ pr.user_dictionary.retain(|w| !w.eq_ignore_ascii_case(&word));
+ n != pr.user_dictionary.len()
+ });
+ Ok(json!({ "removed": removed, "userDictionary": s.prefs().user_dictionary }))
+}
+
+fn check_spelling(s: &mut Session, p: &Value) -> Result<Value> {
+ match p.get("action").and_then(Value::as_str).unwrap_or("list") {
+ "list" | "check" => list(s, p),
+ "change" => change(s, p),
+ "changeAll" => change_all(s, p),
+ "add" | "addToDictionary" => add_word(s, p),
+ "removeFromDictionary" => remove_word(s, p),
+ "suggest" => {
+ let w = p.get("word").and_then(Value::as_str).unwrap_or("");
+ let ok = accepted(s, p);
+ let d = Dictionary::english();
+ Ok(json!({ "word": w, "correct": d.check(w, &ok), "suggestions": d.suggest(w, p.get("suggestions").and_then(Value::as_u64).unwrap_or(5) as usize) }))
+ }
+ other => Err(bad("edit.checkSpelling", format!("unknown action {other:?}"))),
+ }
+}
+
+fn insert_text(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "type.insertText";
+ let id = layer_param(s, p)?;
+ let new = p.get("text").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad(cmd, "missing `text`"))?.to_string();
+ let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
+ let t = text(&doc, id).ok_or_else(|| bad(cmd, format!("layer {} is not a type layer", id.0)))?;
+ let n = t.chars().count();
+ let (a, b) = match (p.get("range").and_then(Value::as_array), p.get("at").and_then(Value::as_u64)) {
+ (Some(r), _) if r.len() == 2 => {
+ let x = r[0].as_u64().unwrap_or(0) as usize;
+ let y = r[1].as_u64().unwrap_or(x as u64) as usize;
+ (x.min(y).min(n), x.max(y).min(n))
+ }
+ (_, Some(at)) => (at as usize, at as usize),
+ _ => (n, n),
+ };
+ let (a, b) = (a.min(n), b.min(n));
+ let (ba, bb) = (byte_at(t, a), byte_at(t, b));
+ let label = p.get("label").and_then(Value::as_str).unwrap_or("Insert Glyph").to_string();
+ s.edit(&label, |doc, _| {
+ let snapshot = doc.clone();
+ if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {
+ replace_text(t, ba, bb, &new);
+ refresh(&snapshot, t);
+ }
+ Ok(())
+ })?;
+ let caret = a + new.chars().count();
+ Ok(json!({ "layer": id.0, "caret": caret }))
+}
+
+fn has_text_layer(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {
+ Some(LayerContent::Text(_)) => Ok(()),
+ _ => Err("the active layer is not a type layer".into()),
+ }
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "edit.checkSpelling",
+ label: "Check Spelling…",
+ menu: &["Edit"],
+ shortcut: None,
+ params: r#"{"action":"list|change|changeAll|addToDictionary|removeFromDictionary|suggest"="list","allLayers":bool=true,"layer":id? (check one layer),"ignore":[word]? (Ignore All for this check),"suggestions":n=5; change: "layer","start","end" (chars),"word"? (verified),"replace"; changeAll: "word","replace"; addToDictionary/removeFromDictionary/suggest: "word"} → list: {"misspellings":[{"layer","start","end","word","suggestions"}],"count"}"#,
+ enabled: has_type,
+ journal: true,
+ run: check_spelling,
+ },
+ CommandSpec {
+ id: "type.insertText",
+ label: "Insert Glyph",
+ menu: &[],
+ shortcut: None,
+ params: r#"{"layer":id?,"text":str,"at":char? (default: end of text),"range":[startChar,endChar]? (replaced),"label":str?} → {"layer","caret"}"#,
+ enabled: has_text_layer,
+ journal: true,
+ run: insert_text,
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn session(text: &str) -> (Session, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 300, "height": 100, "background": "white"})).unwrap();
+ let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": text, "size": 12})).unwrap();
+ (s, r["layer"].as_u64().unwrap())
+ }
+
+ fn text_of(s: &Session, id: u64) -> String {
+ text(&s.active().unwrap().doc, LayerId(id)).unwrap().to_string()
+ }
+
+ #[test]
+ fn lists_changes_and_learns_words() {
+ let (mut s, id) = session("Teh quick brwon fox, teh end. Photocraft");
+ let r = s.execute("edit.checkSpelling", json!({})).unwrap();
+ let words: Vec<&str> = r["misspellings"].as_array().unwrap().iter().map(|m| m["word"].as_str().unwrap()).collect();
+ assert_eq!(words, vec!["Teh", "brwon", "teh", "Photocraft"]);
+ let first = &r["misspellings"][0];
+ assert_eq!((first["start"].as_u64(), first["end"].as_u64()), (Some(0), Some(3)));
+ assert_eq!(first["suggestions"][0], "The");
+ // Change one occurrence (verified), then all of another.
+ s.execute("edit.checkSpelling", json!({"action": "change", "layer": id, "start": 0, "end": 3, "word": "Teh", "replace": "The"})).unwrap();
+ assert!(s.execute("edit.checkSpelling", json!({"action": "change", "layer": id, "start": 0, "end": 3, "word": "Teh", "replace": "X"})).is_err());
+ let r = s.execute("edit.checkSpelling", json!({"action": "changeAll", "word": "brwon", "replace": "brown"})).unwrap();
+ assert_eq!(r["changed"], 1);
+ assert_eq!(text_of(&s, id), "The quick brown fox, teh end. Photocraft");
+ // One undo step per change.
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(text_of(&s, id).contains("brwon"));
+ s.execute("edit.redo", json!({})).unwrap();
+ // Ignore All and Add to Dictionary.
+ let r = s.execute("edit.checkSpelling", json!({"ignore": ["teh"]})).unwrap();
+ assert_eq!(r["count"], 1);
+ s.execute("edit.checkSpelling", json!({"action": "addToDictionary", "word": "Photocraft"})).unwrap();
+ assert_eq!(s.prefs().user_dictionary, vec!["Photocraft".to_string()]);
+ let r = s.execute("edit.checkSpelling", json!({})).unwrap();
+ assert_eq!(r["count"], 1);
+ s.execute("edit.checkSpelling", json!({"action": "removeFromDictionary", "word": "photocraft"})).unwrap();
+ assert!(s.prefs().user_dictionary.is_empty());
+ assert!(s.execute("edit.checkSpelling", json!({"action": "bogus"})).is_err());
+ let r = s.execute("edit.checkSpelling", json!({"action": "suggest", "word": "recieve"})).unwrap();
+ assert_eq!(r["correct"], false);
+ }
+
+ #[test]
+ fn disabled_without_type() {
+ let mut s = Session::new();
+ assert!(!s.is_enabled("edit.checkSpelling"));
+ s.execute("file.new", json!({"width": 10, "height": 10})).unwrap();
+ assert!(!s.is_enabled("edit.checkSpelling"));
+ assert!(!s.is_enabled("type.insertText"));
+ }
+
+ #[test]
+ fn insert_glyph_at_caret_and_over_range() {
+ let (mut s, id) = session("ab");
+ s.execute("type.insertText", json!({"layer": id, "text": "→", "at": 1})).unwrap();
+ assert_eq!(text_of(&s, id), "a→b");
+ let r = s.execute("type.insertText", json!({"layer": id, "text": "€", "range": [0, 2]})).unwrap();
+ assert_eq!((text_of(&s, id).as_str(), r["caret"].as_u64()), ("€b", Some(1)));
+ s.execute("type.insertText", json!({"text": "!"})).unwrap();
+ assert_eq!(text_of(&s, id), "€b!");
+ assert!(s.execute("type.insertText", json!({"text": ""})).is_err());
+ }
+}
diff --git a/crates/engine/src/type_styles_cmds.rs b/crates/engine/src/type_styles_cmds.rs
new file mode 100644
index 000000000..bc8d38dd9
--- /dev/null
+++ b/crates/engine/src/type_styles_cmds.rs
@@ -0,0 +1,728 @@
+//! Character Styles and Paragraph Styles (Window › Character Styles / Paragraph Styles).
+//!
+//! `type.characterStyle.*` and `type.paragraphStyle.*`: new, duplicate, delete, rename, set
+//! (Style Options), apply, redefine (from the selected text), clear override and list. The style
+//! model is [`photocraft_doc::TextStyles`]; text runs keep fully resolved attributes plus a style
+//! reference, so whatever differs from the referenced styles is a local override ("+").
+//!
+//! Text targets: `layer` (one type layer) or `layers` (several), default the selected type
+//! layers; `range: [startChar, endChar]` restricts a single layer to part of its text.
+//! Changing a style's definition re-renders every type layer that uses it, keeping overrides.
+
+use std::collections::HashSet;
+
+use photocraft_doc::text::{CharStyle, ParagraphRun, ParagraphStyle, TextRun};
+use photocraft_doc::text_styles::{self as ts, CharacterStyleDef, ParagraphStyleDef, StyleAttrs};
+use photocraft_doc::{Document, LayerContent, LayerId, TextLayer, TextStyles};
+use serde_json::{Map, Value, json};
+
+use crate::commands::CommandSpec;
+use crate::type_cmds::{apply_char_props, apply_para_props, refresh};
+use crate::{EngineError, Result, Session};
+
+const FAMILY: &str = photocraft_text::fonts::DEFAULT_FAMILY;
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+fn text_of(doc: &Document, id: LayerId) -> Option<&TextLayer> {
+ match &doc.layer(id)?.content {
+ LayerContent::Text(t) => Some(t),
+ _ => None,
+ }
+}
+
+/// Type layers a style command acts on: `layer`, `layers`, else the selected type layers.
+fn targets(s: &Session, p: &Value) -> Vec<LayerId> {
+ let Some(st) = s.active() else { return Vec::new() };
+ let ids: Vec<LayerId> = if let Some(id) = p.get("layer").and_then(Value::as_u64) {
+ vec![LayerId(id)]
+ } else if let Some(a) = p.get("layers").and_then(Value::as_array) {
+ a.iter().filter_map(Value::as_u64).map(LayerId).collect()
+ } else {
+ st.selected_layers()
+ };
+ ids.into_iter().filter(|id| text_of(&st.doc, *id).is_some()).collect()
+}
+
+fn has_target(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if targets(s, &Value::Null).is_empty() { Err("select a type layer".into()) } else { Ok(()) }
+}
+
+fn byte_at(text: &str, ci: usize) -> usize {
+ text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b)
+}
+
+/// `range` in characters → bytes (whole text when absent).
+fn range_of(text: &str, p: &Value) -> (usize, usize) {
+ match p.get("range").and_then(Value::as_array) {
+ Some(r) if r.len() == 2 => {
+ let a = r[0].as_u64().unwrap_or(0) as usize;
+ let b = r[1].as_u64().unwrap_or(a as u64) as usize;
+ (byte_at(text, a.min(b)), byte_at(text, a.max(b)))
+ }
+ _ => (0, text.len()),
+ }
+}
+
+fn id_param(p: &Value) -> Option<u32> {
+ p.get("id").and_then(Value::as_u64).map(|v| v as u32)
+}
+
+// ---------- attribute parameters ----------
+
+/// A character style with every field changed from the default, to see which fields a set of
+/// Character-panel keys touches.
+fn perturbed_char() -> CharStyle {
+ use photocraft_doc::text::{Caps, FontFeature, FontVariation, Kerning};
+ CharStyle {
+ font_family: "\u{1}".into(),
+ font_style: "\u{1}".into(),
+ postscript_name: Some("\u{1}".into()),
+ weight: 1,
+ italic: true,
+ size_pt: -1.0,
+ color: photocraft_doc::Color::rgba(0.123, 0.456, 0.789, 0.5),
+ tracking: -12345.0,
+ leading_pt: Some(-1.0),
+ baseline_shift_pt: -1.0,
+ horizontal_scale: -1.0,
+ vertical_scale: -1.0,
+ underline: true,
+ strikethrough: true,
+ faux_bold: true,
+ faux_italic: true,
+ kerning: Kerning::Off,
+ caps: Caps::AllCaps,
+ ligatures: false,
+ discretionary_ligatures: true,
+ features: vec![FontFeature { tag: "\u{1}".into(), value: 9 }],
+ variations: vec![FontVariation { axis: "\u{1}".into(), value: -1.0 }],
+ language: Some("\u{1}".into()),
+ style_sheet: None,
+ }
+}
+
+fn perturbed_para() -> ParagraphStyle {
+ use photocraft_doc::text::{TextAlign, TextDirection};
+ ParagraphStyle {
+ align: TextAlign::JustifyAll,
+ first_line_indent_pt: -1.0,
+ start_indent_pt: -1.0,
+ end_indent_pt: -1.0,
+ space_before_pt: -1.0,
+ space_after_pt: -1.0,
+ auto_leading: -1.0,
+ direction: TextDirection::Rtl,
+ hyphenate: true,
+ style_sheet: None,
+ }
+}
+
+/// Fields set by Character/Paragraph-panel keys (`size`, `font`, `align`, …): the fields whose
+/// value is the same whatever they were before.
+fn touched<T: serde::Serialize + Default + Clone>(perturbed: T, apply: impl Fn(&mut T)) -> StyleAttrs {
+ let (mut a, mut b) = (T::default(), perturbed);
+ apply(&mut a);
+ apply(&mut b);
+ let obj = |x: &T| match serde_json::to_value(x) {
+ Ok(Value::Object(m)) => m,
+ _ => Map::new(),
+ };
+ let all_b = obj(&b);
+ obj(&a).into_iter().filter(|(k, v)| k != "style_sheet" && all_b.get(k) == Some(v)).collect()
+}
+
+/// Splits `attrs` into character and paragraph attribute sets. Keys may be model field names
+/// (`size_pt`, `align`: values as in `type.info`) or the Character/Paragraph panel keys of
+/// `type.setStyle` (`size`, `font`, `align`, …).
+fn parse_attrs(cmd: &str, v: &Value) -> Result<(StyleAttrs, StyleAttrs)> {
+ let Some(obj) = v.as_object() else {
+ return if v.is_null() { Ok((Map::new(), Map::new())) } else { Err(bad(cmd, "`attrs` must be an object")) };
+ };
+ let char_keys: HashSet<String> = ts::char_attrs(&CharStyle::default()).keys().cloned().collect();
+ let para_keys: HashSet<String> = ts::para_attrs(&ParagraphStyle::default()).keys().cloned().collect();
+ let (mut c, mut pa, mut friendly) = (Map::new(), Map::new(), Map::new());
+ for (k, x) in obj {
+ // Names shared by the model and the panels (`color`, `align`, `caps`, …) are read as
+ // model values when they parse as such, else as panel values ("#ff0000", "center").
+ let one: StyleAttrs = std::iter::once((k.clone(), x.clone())).collect();
+ if char_keys.contains(k) && ts::validate::<CharStyle>(&one).is_ok() {
+ c.insert(k.clone(), x.clone());
+ } else if para_keys.contains(k) && ts::validate::<ParagraphStyle>(&one).is_ok() {
+ pa.insert(k.clone(), x.clone());
+ } else {
+ friendly.insert(k.clone(), x.clone());
+ }
+ }
+ if !friendly.is_empty() {
+ let f = Value::Object(friendly.clone());
+ let fc = touched(perturbed_char(), |st| {
+ apply_char_props(st, &f);
+ });
+ let fp = touched(perturbed_para(), |st| {
+ apply_para_props(st, &f);
+ });
+ if fc.is_empty() && fp.is_empty() {
+ return Err(bad(cmd, format!("unknown style attributes: {}", friendly.keys().cloned().collect::<Vec<_>>().join(", "))));
+ }
+ c.extend(fc);
+ pa.extend(fp);
+ }
+ ts::validate::<CharStyle>(&c).map_err(|e| bad(cmd, e))?;
+ ts::validate::<ParagraphStyle>(&pa).map_err(|e| bad(cmd, e))?;
+ Ok((c, pa))
+}
+
+// ---------- restyling ----------
+
+/// What to do to the targeted text while re-resolving against new styles.
+#[derive(Clone, Copy, Default)]
+struct Op {
+ /// Set the character style of the range (`Some(None)` = "None").
+ set_char: Option<Option<u32>>,
+ /// Set the paragraph style of paragraphs touching the range (`Some(None)` = Basic).
+ set_para: Option<Option<u32>>,
+ /// Drop character overrides in the range.
+ clear_char: bool,
+ /// Drop paragraph overrides of paragraphs touching the range.
+ clear_para: bool,
+}
+
+/// Re-resolves every run and paragraph of `t` against `new` (keeping overrides made against
+/// `old`), applying `op` to bytes `a..b`. Returns whether anything changed.
+fn restyle(t: &mut TextLayer, old: &TextStyles, new: &TextStyles, range: Option<(usize, usize)>, op: Op) -> bool {
+ let before = (t.runs.clone(), t.paragraphs.clone());
+ let text = t.text.clone();
+ let (a, b) = range.unwrap_or((0, text.len()));
+ let whole = range.is_none();
+ // Paragraphs.
+ let old_paras = t.paragraph_runs();
+ let starts: Vec<usize> = old_paras.iter().scan(0, |acc, r| {
+ let s = *acc;
+ *acc += r.len;
+ Some(s)
+ }).collect();
+ let para_at = |off: usize| old_paras[starts.iter().rposition(|&s| s <= off).unwrap_or(0)].style.clone();
+ let mut paras: Vec<(std::ops::Range<usize>, ParagraphStyle, Option<u32>)> = Vec::new(); // range, new style, old ref
+ for pr in photocraft_text::layout::split_paragraphs(&text) {
+ let old_p = para_at(pr.start);
+ let touches = whole || (pr.start < b && pr.end > a) || (a == b && a >= pr.start && (a < pr.end || pr.end == text.len()));
+ let new_ref = match op.set_para {
+ Some(r) if touches => r,
+ _ => old_p.style_sheet,
+ };
+ let np = if op.clear_para && touches { new.resolve_para(new_ref) } else { new.restyle_para(old, &old_p, new_ref) };
+ paras.push((pr, np, old_p.style_sheet));
+ }
+ // Character runs, split at paragraph boundaries and the range edges.
+ let mut cuts: Vec<usize> = paras.iter().map(|p| p.0.start).collect();
+ cuts.extend([a, b, text.len()]);
+ let mut runs: Vec<(usize, CharStyle)> = Vec::new();
+ let mut at = 0;
+ for r in t.char_runs() {
+ let (rs, re) = (at, at + r.len);
+ at = re;
+ let mut edges: Vec<usize> = cuts.iter().copied().filter(|&c| c > rs && c < re).collect();
+ edges.sort_unstable();
+ edges.dedup();
+ let mut s0 = rs;
+ for e in edges.into_iter().chain(std::iter::once(re)) {
+ if e <= s0 && rs != re {
+ continue;
+ }
+ let pi = paras.iter().rposition(|p| p.0.start <= s0).unwrap_or(0);
+ let (old_pref, new_pref) = (paras[pi].2, paras[pi].1.style_sheet);
+ let inside = whole || (s0 >= a && e <= b && a < b);
+ let chr = match op.set_char {
+ Some(c) if inside => c,
+ _ => r.style.style_sheet,
+ };
+ let st = if op.clear_char && inside {
+ new.resolve_char(new_pref, chr, FAMILY)
+ } else {
+ new.restyle_char(old, &r.style, old_pref, new_pref, chr, FAMILY)
+ };
+ match runs.last_mut() {
+ Some(last) if last.1 == st => last.0 += e - s0,
+ _ => runs.push((e - s0, st)),
+ }
+ s0 = e;
+ }
+ }
+ let mut pruns: Vec<(usize, ParagraphStyle)> = Vec::new();
+ for (r, st, _) in paras {
+ match pruns.last_mut() {
+ Some(last) if last.1 == st => last.0 += r.len(),
+ _ => pruns.push((r.len(), st)),
+ }
+ }
+ if runs.is_empty() {
+ let first = t.char_runs().into_iter().next().map(|r| r.style).unwrap_or_default();
+ runs.push((0, new.restyle_char(old, &first, None, pruns.first().and_then(|p| p.1.style_sheet), op.set_char.unwrap_or(first.style_sheet), FAMILY)));
+ }
+ t.runs = runs.into_iter().map(|(len, style)| TextRun { len, style }).collect();
+ t.paragraphs = pruns.into_iter().map(|(len, style)| ParagraphRun { len, style }).collect();
+ t.sync_summary();
+ (t.runs.clone(), t.paragraphs.clone()) != before
+}
+
+/// Replaces the document's styles with `new` and re-resolves every type layer (as one history
+/// step), applying `op` to `target` (layer + optional byte range).
+fn commit(s: &mut Session, label: &str, new: TextStyles, target: &[Target], op: Op) -> Result<usize> {
+ s.edit(label, |doc, _| {
+ let old = doc.text_styles.clone();
+ doc.text_styles = new.clone();
+ let snapshot = doc.clone();
+ let ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();
+ let mut changed = 0;
+ for id in ids {
+ let tgt = target.iter().find(|(t, _)| *t == id);
+ let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) else { continue };
+ let did = match tgt {
+ Some((_, r)) => restyle(t, &old, &new, *r, op),
+ None => restyle(t, &old, &new, Some((0, 0)), Op::default()),
+ };
+ if did {
+ refresh(&snapshot, t);
+ changed += 1;
+ }
+ }
+ Ok(changed)
+ })
+}
+
+/// A type layer and an optional byte range in it.
+type Target = (LayerId, Option<(usize, usize)>);
+
+/// Target list with byte ranges (`range` applies only to a single layer).
+fn target_ranges(s: &Session, p: &Value) -> Result<Vec<Target>> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let ids = targets(s, p);
+ if ids.is_empty() {
+ return Err(EngineError::Other("no type layer to apply the style to".into()));
+ }
+ Ok(ids
+ .into_iter()
+ .map(|id| {
+ let r = (p.get("range").is_some() && p.get("layers").is_none()).then(|| text_of(&st.doc, id).map(|t| range_of(&t.text, p))).flatten();
+ (id, r)
+ })
+ .collect())
+}
+
+/// The run and paragraph at the start of the target (for new/redefine), with the layer and the
+/// run's byte range.
+fn sample(s: &Session, p: &Value) -> Option<(CharStyle, ParagraphStyle, LayerId, (usize, usize))> {
+ let st = s.active()?;
+ let id = *targets(s, p).first()?;
+ let t = text_of(&st.doc, id)?;
+ let (a, _) = range_of(&t.text, p);
+ let mut at = 0;
+ let mut run = None;
+ for r in t.char_runs() {
+ let (s0, e0) = (at, at + r.len);
+ at = e0;
+ if a < e0 || e0 == t.text.len() {
+ run = Some((r.style, (s0, e0)));
+ break;
+ }
+ }
+ let (run, span) = run?;
+ let mut at = 0;
+ let paras = t.paragraph_runs();
+ let para = paras.iter().find(|r| {
+ let hit = a < at + r.len || at + r.len == t.text.len();
+ at += r.len;
+ hit
+ })?;
+ Some((run, para.style.clone(), id, span))
+}
+
+/// Character / paragraph style state of the target: (char id, char override, para id, para
+/// override), over the whole target (mixed ids → None).
+fn current(s: &Session, p: &Value) -> Option<Value> {
+ let st = s.active()?;
+ let styles = &st.doc.text_styles;
+ let tr = target_ranges(s, p).ok()?;
+ let (mut chars, mut paras) = (Vec::new(), Vec::new());
+ let (mut c_over, mut p_over) = (false, false);
+ for (id, r) in &tr {
+ let t = text_of(&st.doc, *id)?;
+ let (a, b) = r.unwrap_or((0, t.text.len()));
+ let pr = t.paragraph_runs();
+ let mut at = 0;
+ let mut para_spans = Vec::new();
+ for x in &pr {
+ let (s0, e0) = (at, at + x.len);
+ at = e0;
+ if (s0 < b && e0 > a) || (a == b && a >= s0 && (a < e0 || e0 == t.text.len())) || t.text.is_empty() {
+ paras.push(x.style.style_sheet.unwrap_or(0));
+ p_over |= !styles.para_overrides(&x.style).is_empty();
+ }
+ para_spans.push((s0, e0, x.style.style_sheet));
+ }
+ let mut at = 0;
+ for x in t.char_runs() {
+ let (s0, e0) = (at, at + x.len);
+ at = e0;
+ if (s0 < b && e0 > a) || (a == b && a >= s0 && a <= e0) || t.text.is_empty() {
+ let pref = para_spans.iter().rev().find(|p| p.0 <= s0).and_then(|p| p.2);
+ chars.push(x.style.style_sheet.unwrap_or(0));
+ c_over |= !styles.char_overrides(&x.style, pref, FAMILY).is_empty();
+ }
+ }
+ }
+ let one = |v: &Vec<u32>| (!v.is_empty() && v.iter().all(|x| *x == v[0])).then(|| v[0]);
+ Some(json!({ "character": one(&chars), "characterOverride": c_over, "paragraph": one(&paras), "paragraphOverride": p_over }))
+}
+
+// ---------- commands ----------
+
+fn styles(s: &Session) -> Result<TextStyles> {
+ Ok(s.active().ok_or(EngineError::NoDocument)?.doc.text_styles.clone())
+}
+
+fn char_json(d: &CharacterStyleDef, styles: &TextStyles) -> Value {
+ json!({ "id": d.id, "name": d.name, "attrs": d.attrs, "resolved": styles.resolve_char(None, Some(d.id), FAMILY) })
+}
+
+fn para_json(d: &ParagraphStyleDef, styles: &TextStyles) -> Value {
+ json!({ "id": d.id, "name": d.name, "paragraphAttrs": d.para_attrs, "characterAttrs": d.char_attrs, "resolved": { "paragraph": styles.resolve_para(Some(d.id)), "character": styles.resolve_char(Some(d.id), None, FAMILY) } })
+}
+
+fn list(s: &Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let st = styles(s)?;
+ let cur = current(s, p);
+ Ok(if paragraph {
+ let mut v = vec![para_json(&st.basic, &st)];
+ v.extend(st.paragraph.iter().map(|d| para_json(d, &st)));
+ json!({ "styles": v, "current": cur })
+ } else {
+ let mut v = vec![json!({ "id": 0, "name": ts::NO_CHARACTER_STYLE, "attrs": {} })];
+ v.extend(st.character.iter().map(|d| char_json(d, &st)));
+ json!({ "styles": v, "current": cur })
+ })
+}
+
+fn new_style(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.new" } else { "type.characterStyle.new" };
+ let mut st = styles(s)?;
+ let (mut ca, mut pa) = parse_attrs(cmd, p.get("attrs").unwrap_or(&Value::Null))?;
+ // With a type layer targeted, the style starts from the text's formatting (as Photoshop).
+ let from_text = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true);
+ if from_text && let Some((run, para, _, _)) = sample(s, p) {
+ if paragraph {
+ let base_c = st.resolve_char(None, None, FAMILY);
+ let mut c = ts::diff_attrs(&CharStyle { style_sheet: None, ..run }, &base_c);
+ c.extend(ca);
+ ca = c;
+ let mut pp = ts::diff_attrs(&para, &st.resolve_para(None));
+ pp.extend(pa);
+ pa = pp;
+ } else {
+ let base_c = st.resolve_char(para.style_sheet, None, FAMILY);
+ let mut c = ts::diff_attrs(&run, &base_c);
+ c.extend(ca);
+ ca = c;
+ }
+ }
+ let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| st.unique_name(paragraph, if paragraph { "Paragraph Style" } else { "Character Style" }));
+ let id = if paragraph {
+ let id = st.next_para_id();
+ st.paragraph.push(ParagraphStyleDef { id, name: name.clone(), para_attrs: pa, char_attrs: ca });
+ id
+ } else {
+ let id = st.next_char_id();
+ st.character.push(CharacterStyleDef { id, name: name.clone(), attrs: ca });
+ id
+ };
+ let apply = p.get("apply").and_then(Value::as_bool).unwrap_or(false);
+ let (target, op) = if apply {
+ let op = if paragraph { Op { set_para: Some(Some(id)), ..Op::default() } } else { Op { set_char: Some(Some(id)), ..Op::default() } };
+ (target_ranges(s, p)?, op)
+ } else {
+ (Vec::new(), Op::default())
+ };
+ commit(s, if paragraph { "New Paragraph Style" } else { "New Character Style" }, st, &target, op)?;
+ Ok(json!({ "id": id, "name": name }))
+}
+
+fn lookup_id(cmd: &str, st: &TextStyles, p: &Value, paragraph: bool, allow_default: bool) -> Result<u32> {
+ let id = id_param(p).ok_or_else(|| bad(cmd, "missing `id`"))?;
+ let ok = if paragraph { st.para_style(id).is_some() } else { st.char_style(id).is_some() };
+ if !(ok || (allow_default && id == 0)) {
+ return Err(bad(cmd, format!("no style with id {id}")));
+ }
+ if id == 0 && !allow_default {
+ return Err(bad(cmd, if paragraph { "Basic Paragraph can't be changed this way" } else { "\"None\" is not a style" }));
+ }
+ Ok(id)
+}
+
+fn duplicate(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.duplicate" } else { "type.characterStyle.duplicate" };
+ let mut st = styles(s)?;
+ let id = lookup_id(cmd, &st, p, paragraph, paragraph)?;
+ let (new_id, name) = if paragraph {
+ let src = st.para_style(id).cloned().unwrap_or_default();
+ let name = format!("{} copy", src.name);
+ let nid = st.next_para_id();
+ let pos = st.paragraph.iter().position(|d| d.id == id).map_or(0, |i| i + 1);
+ st.paragraph.insert(pos, ParagraphStyleDef { id: nid, name: name.clone(), ..src });
+ (nid, name)
+ } else {
+ let src = st.char_style(id).cloned().unwrap_or_default();
+ let name = format!("{} copy", src.name);
+ let nid = st.next_char_id();
+ let pos = st.character.iter().position(|d| d.id == id).map_or(0, |i| i + 1);
+ st.character.insert(pos, CharacterStyleDef { id: nid, name: name.clone(), ..src });
+ (nid, name)
+ };
+ commit(s, "Duplicate Style", st, &[], Op::default())?;
+ Ok(json!({ "id": new_id, "name": name }))
+}
+
+fn delete(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.delete" } else { "type.characterStyle.delete" };
+ let st = styles(s)?;
+ let id = lookup_id(cmd, &st, p, paragraph, false)?;
+ // Text keeps its look: references are dropped and the attributes become overrides.
+ let mut n = 0;
+ s.edit("Delete Style", |doc, _| {
+ if paragraph {
+ doc.text_styles.paragraph.retain(|d| d.id != id);
+ } else {
+ doc.text_styles.character.retain(|d| d.id != id);
+ }
+ let snapshot = doc.clone();
+ let ids: Vec<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ for lid in ids {
+ let Some(LayerContent::Text(t)) = doc.layer_mut(lid).map(|l| &mut l.content) else { continue };
+ let mut hit = false;
+ if paragraph {
+ for r in &mut t.paragraphs {
+ if r.style.style_sheet == Some(id) {
+ r.style.style_sheet = None;
+ hit = true;
+ }
+ }
+ } else {
+ for r in &mut t.runs {
+ if r.style.style_sheet == Some(id) {
+ r.style.style_sheet = None;
+ hit = true;
+ }
+ }
+ }
+ if hit {
+ refresh(&snapshot, t);
+ n += 1;
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({ "deleted": id, "layers": n }))
+}
+
+fn rename(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.rename" } else { "type.characterStyle.rename" };
+ let mut st = styles(s)?;
+ let id = lookup_id(cmd, &st, p, paragraph, false)?;
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `name`"))?.to_string();
+ if paragraph {
+ if let Some(d) = st.para_style_mut(id) {
+ d.name = name.clone();
+ }
+ } else if let Some(d) = st.char_style_mut(id) {
+ d.name = name.clone();
+ }
+ commit(s, "Rename Style", st, &[], Op::default())?;
+ Ok(json!({ "id": id, "name": name }))
+}
+
+fn set_options(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.set" } else { "type.characterStyle.set" };
+ let mut st = styles(s)?;
+ let id = lookup_id(cmd, &st, p, paragraph, paragraph)?;
+ let (ca, pa) = parse_attrs(cmd, p.get("attrs").unwrap_or(&Value::Null))?;
+ let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false);
+ let clear: Vec<String> = p.get("clear").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
+ let merge = |dst: &mut StyleAttrs, src: StyleAttrs| {
+ if replace {
+ dst.clear();
+ }
+ dst.extend(src);
+ for k in &clear {
+ dst.remove(k);
+ }
+ };
+ if paragraph {
+ let d = st.para_style_mut(id).ok_or_else(|| bad(cmd, "no such style"))?;
+ merge(&mut d.char_attrs, ca);
+ if replace {
+ d.para_attrs.clear();
+ }
+ d.para_attrs.extend(pa);
+ for k in &clear {
+ d.para_attrs.remove(k);
+ }
+ if let Some(n) = name.filter(|_| id != 0) {
+ d.name = n;
+ }
+ } else {
+ if !pa.is_empty() {
+ return Err(bad(cmd, "character styles have no paragraph attributes"));
+ }
+ let d = st.char_style_mut(id).ok_or_else(|| bad(cmd, "no such style"))?;
+ merge(&mut d.attrs, ca);
+ if let Some(n) = name {
+ d.name = n;
+ }
+ }
+ let layers = commit(s, "Style Options", st, &[], Op::default())?;
+ let mut v = list(s, &json!({}), paragraph)?;
+ v["layers"] = json!(layers);
+ v["id"] = json!(id);
+ Ok(v)
+}
+
+fn apply(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.apply" } else { "type.characterStyle.apply" };
+ let st = styles(s)?;
+ let id = match p.get("id") {
+ None | Some(Value::Null) => 0,
+ Some(_) => lookup_id(cmd, &st, p, paragraph, true)?,
+ };
+ let target = target_ranges(s, p)?;
+ let clear = p.get("clearOverrides").and_then(Value::as_bool).unwrap_or(false);
+ let r = Some(id).filter(|i| *i != 0);
+ let op = if paragraph { Op { set_para: Some(r), clear_para: clear, clear_char: clear, ..Op::default() } } else { Op { set_char: Some(r), clear_char: clear, ..Op::default() } };
+ let n = commit(s, if paragraph { "Apply Paragraph Style" } else { "Apply Character Style" }, st, &target, op)?;
+ Ok(json!({ "id": id, "layers": n, "current": current(s, p) }))
+}
+
+fn clear_override(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let st = styles(s)?;
+ let target = target_ranges(s, p)?;
+ let op = if paragraph { Op { clear_para: true, clear_char: true, ..Op::default() } } else { Op { clear_char: true, ..Op::default() } };
+ let n = commit(s, "Clear Override", st, &target, op)?;
+ Ok(json!({ "layers": n, "current": current(s, p) }))
+}
+
+fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {
+ let cmd = if paragraph { "type.paragraphStyle.redefine" } else { "type.characterStyle.redefine" };
+ let mut st = styles(s)?;
+ let (run, para, layer, span) = sample(s, p).ok_or_else(|| bad(cmd, "select type to redefine the style from"))?;
+ let id = match id_param(p) {
+ Some(_) => lookup_id(cmd, &st, p, paragraph, paragraph)?,
+ None if paragraph => para.style_sheet.unwrap_or(0),
+ None => run.style_sheet.ok_or_else(|| bad(cmd, "the selected text has no character style"))?,
+ };
+ if paragraph {
+ let char_keys: HashSet<String> = run.style_sheet.and_then(|c| st.char_style(c)).map(|d| d.attrs.keys().cloned().collect()).unwrap_or_default();
+ let c_over: StyleAttrs = st.char_overrides(&run, Some(id).filter(|i| *i != 0), FAMILY).into_iter().filter(|(k, _)| !char_keys.contains(k)).collect();
+ let base_para = st.resolve_para(Some(id));
+ let p_over = ts::diff_attrs(&para, &base_para);
+ let d = st.para_style_mut(id).ok_or_else(|| bad(cmd, "no such style"))?;
+ d.char_attrs.extend(c_over);
+ d.para_attrs.extend(p_over);
+ } else {
+ let over = st.char_overrides(&CharStyle { style_sheet: Some(id), ..run }, para.style_sheet, FAMILY);
+ let d = st.char_style_mut(id).ok_or_else(|| bad(cmd, "no such style"))?;
+ d.attrs.extend(over);
+ }
+ // The sampled run gets the style (its overrides are now part of it); others follow.
+ let target = [(layer, Some(span))];
+ let op = if paragraph { Op { set_para: Some(Some(id).filter(|i| *i != 0)), ..Op::default() } } else { Op { set_char: Some(Some(id)), ..Op::default() } };
+ let n = commit(s, if paragraph { "Redefine Paragraph Style" } else { "Redefine Character Style" }, st, &target, op)?;
+ Ok(json!({ "id": id, "layers": n, "current": current(s, p) }))
+}
+
+macro_rules! target_doc {
+ () => {
+ r#""layer":id? | "layers":[id]? (default: the selected type layers),"range":[startChar,endChar]? (one layer; default all text)"#
+ };
+}
+macro_rules! attrs_doc {
+ () => {
+ r##""attrs":{model fields as in type.info ("size_pt":36,"font_family":"Inter","align":"Center",…) or Character/Paragraph panel keys as in type.setStyle ("size":36,"font":"Inter","color":"#rrggbb","align":"center",…)}"##
+ };
+}
+
+macro_rules! style_specs {
+ ($paragraph:expr, $prefix:literal, $noun:literal) => {
+ vec![
+ CommandSpec {
+ id: concat!($prefix, ".new"),
+ label: concat!("New ", $noun, " Style"),
+ menu: &[],
+ shortcut: None,
+ params: concat!(r#"{"name":str?,"#, attrs_doc!(), r#"?,"fromSelection":bool=true (start from the targeted text's formatting),"apply":bool=false,"#, target_doc!(), r#"} → {"id","name"}"#),
+ enabled: has_doc,
+ journal: true,
+ run: |s, p| new_style(s, p, $paragraph),
+ },
+ CommandSpec { id: concat!($prefix, ".duplicate"), label: "Duplicate Style", menu: &[], shortcut: None, params: r#"{"id":u32}"#, enabled: has_doc, journal: true, run: |s, p| duplicate(s, p, $paragraph) },
+ CommandSpec { id: concat!($prefix, ".delete"), label: "Delete Style", menu: &[], shortcut: None, params: r#"{"id":u32} (text keeps its formatting as overrides)"#, enabled: has_doc, journal: true, run: |s, p| delete(s, p, $paragraph) },
+ CommandSpec { id: concat!($prefix, ".rename"), label: "Rename Style", menu: &[], shortcut: None, params: r#"{"id":u32,"name":str}"#, enabled: has_doc, journal: true, run: |s, p| rename(s, p, $paragraph) },
+ CommandSpec {
+ id: concat!($prefix, ".set"),
+ label: concat!($noun, " Style Options"),
+ menu: &[],
+ shortcut: None,
+ params: concat!(r#"{"id":u32 (paragraph: 0 = Basic Paragraph),"name":str?,"#, attrs_doc!(), r#","replace":bool=false (drop attributes not given),"clear":[field]?} (text using the style updates, overrides kept)"#),
+ enabled: has_doc,
+ journal: true,
+ run: |s, p| set_options(s, p, $paragraph),
+ },
+ CommandSpec {
+ id: concat!($prefix, ".apply"),
+ label: concat!("Apply ", $noun, " Style"),
+ menu: &[],
+ shortcut: None,
+ params: concat!(r#"{"id":u32|0|null (0/null: None / Basic Paragraph),"clearOverrides":bool=false (Alt-click),"#, target_doc!(), "}"),
+ enabled: has_target,
+ journal: true,
+ run: |s, p| apply(s, p, $paragraph),
+ },
+ CommandSpec {
+ id: concat!($prefix, ".redefine"),
+ label: concat!("Redefine ", $noun, " Style"),
+ menu: &[],
+ shortcut: None,
+ params: concat!(r#"{"id":u32? (default: the targeted text's style),"#, target_doc!(), "} (the style takes the formatting of the start of the targeted text)"),
+ enabled: has_target,
+ journal: true,
+ run: |s, p| redefine(s, p, $paragraph),
+ },
+ CommandSpec { id: concat!($prefix, ".clearOverride"), label: "Clear Override", menu: &[], shortcut: None, params: concat!("{", target_doc!(), "}"), enabled: has_target, journal: true, run: |s, p| clear_override(s, p, $paragraph) },
+ CommandSpec {
+ id: concat!($prefix, ".list"),
+ label: concat!("List ", $noun, " Styles"),
+ menu: &[],
+ shortcut: None,
+ params: concat!("{", target_doc!(), r#"} → {"styles":[{"id","name",attributes,"resolved"}],"current":{"character":id|null (mixed),"characterOverride":bool,"paragraph":id|null,"paragraphOverride":bool}}"#),
+ enabled: has_doc,
+ journal: false,
+ run: |s, p| list(s, p, $paragraph),
+ },
+ ]
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ let mut v = style_specs!(false, "type.characterStyle", "Character");
+ v.extend(style_specs!(true, "type.paragraphStyle", "Paragraph"));
+ v
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/type_styles_cmds/tests.rs b/crates/engine/src/type_styles_cmds/tests.rs
new file mode 100644
index 000000000..2b4a5f4a7
--- /dev/null
+++ b/crates/engine/src/type_styles_cmds/tests.rs
@@ -0,0 +1,170 @@
+use super::*;
+
+fn session(text: &str) -> (Session, u64) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 400, "height": 200, "background": "transparent"})).unwrap();
+ let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": text, "size": 12})).unwrap();
+ (s, r["layer"].as_u64().unwrap())
+}
+
+fn layer(s: &Session, id: u64) -> TextLayer {
+ text_of(&s.active().unwrap().doc, LayerId(id)).unwrap().clone()
+}
+
+fn run_at(t: &TextLayer, ci: usize) -> CharStyle {
+ let b = byte_at(&t.text, ci);
+ let mut at = 0;
+ for r in t.char_runs() {
+ if b < at + r.len {
+ return r.style;
+ }
+ at += r.len;
+ }
+ t.char_runs().last().unwrap().style.clone()
+}
+
+#[test]
+fn character_style_lifecycle() {
+ let (mut s, id) = session("Hello world");
+ let r = s.execute("type.characterStyle.new", json!({"attrs": {"size": 30, "underline": true}, "fromSelection": false})).unwrap();
+ let cs = r["id"].as_u64().unwrap();
+ assert_eq!(r["name"], "Character Style 1");
+ let l = s.execute("type.characterStyle.list", json!({})).unwrap();
+ assert_eq!(l["styles"][0]["name"], "None");
+ assert_eq!(l["styles"][1]["attrs"], json!({"size_pt": 30.0, "underline": true}));
+
+ // Apply to "world": its runs take the style; "Hello " keeps None.
+ s.execute("type.characterStyle.apply", json!({"id": cs, "layer": id, "range": [6, 11]})).unwrap();
+ let t = layer(&s, id);
+ let w = run_at(&t, 7);
+ assert_eq!((w.size_pt, w.underline, w.style_sheet), (30.0, true, Some(cs as u32)));
+ assert_eq!(run_at(&t, 0).style_sheet, None);
+ let cur = s.execute("type.characterStyle.list", json!({"layer": id, "range": [6, 11]})).unwrap()["current"].clone();
+ assert_eq!((cur["character"].as_u64(), cur["characterOverride"].as_bool()), (Some(cs), Some(false)));
+
+ // A local change is an override ("+"); redefining the style changes other text too.
+ s.execute("type.setStyle", json!({"layer": id, "range": [6, 8], "italic": true})).unwrap();
+ let cur = s.execute("type.characterStyle.list", json!({"layer": id, "range": [6, 8]})).unwrap()["current"].clone();
+ assert_eq!(cur["characterOverride"], true);
+ s.execute("type.characterStyle.set", json!({"id": cs, "attrs": {"size_pt": 40.0}})).unwrap();
+ let t = layer(&s, id);
+ assert_eq!((run_at(&t, 6).size_pt, run_at(&t, 6).italic), (40.0, true));
+ assert_eq!((run_at(&t, 9).size_pt, run_at(&t, 9).italic), (40.0, false));
+ assert_eq!(run_at(&t, 0).size_pt, 12.0);
+
+ // Clear Override drops the italic but keeps the style.
+ s.execute("type.characterStyle.clearOverride", json!({"layer": id, "range": [6, 11]})).unwrap();
+ let t = layer(&s, id);
+ assert!(!run_at(&t, 6).italic);
+ assert_eq!(run_at(&t, 6).style_sheet, Some(cs as u32));
+
+ // Rename, duplicate, delete (text keeps its look).
+ s.execute("type.characterStyle.rename", json!({"id": cs, "name": "Emphasis"})).unwrap();
+ let d = s.execute("type.characterStyle.duplicate", json!({"id": cs})).unwrap();
+ assert_eq!(d["name"], "Emphasis copy");
+ s.execute("type.characterStyle.delete", json!({"id": cs})).unwrap();
+ let t = layer(&s, id);
+ assert_eq!((run_at(&t, 7).size_pt, run_at(&t, 7).style_sheet), (40.0, None));
+ let l = s.execute("type.characterStyle.list", json!({})).unwrap();
+ assert_eq!(l["styles"].as_array().unwrap().len(), 2);
+
+ // Each command is one undo step.
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(run_at(&layer(&s, id), 7).style_sheet, Some(cs as u32));
+}
+
+#[test]
+fn new_style_from_selection_and_redefine() {
+ let (mut s, id) = session("Title");
+ s.execute("type.setStyle", json!({"layer": id, "size": 48, "color": "#ff0000"})).unwrap();
+ let r = s.execute("type.characterStyle.new", json!({"layer": id, "apply": true})).unwrap();
+ let cs = r["id"].as_u64().unwrap() as u32;
+ let st = s.active().unwrap().doc.text_styles.char_style(cs).unwrap().clone();
+ assert_eq!(st.attrs.get("size_pt"), Some(&json!(48.0)));
+ assert_eq!(run_at(&layer(&s, id), 0).style_sheet, Some(cs));
+ // Change the text, then redefine the style from it: no override remains.
+ s.execute("type.setStyle", json!({"layer": id, "size": 60})).unwrap();
+ s.execute("type.characterStyle.redefine", json!({"layer": id})).unwrap();
+ let cur = s.execute("type.characterStyle.list", json!({"layer": id})).unwrap()["current"].clone();
+ assert_eq!((cur["character"].as_u64(), cur["characterOverride"].as_bool()), (Some(u64::from(cs)), Some(false)));
+ assert_eq!(s.active().unwrap().doc.text_styles.char_style(cs).unwrap().attrs.get("size_pt"), Some(&json!(60.0)));
+}
+
+#[test]
+fn paragraph_styles_and_basic_paragraph() {
+ let (mut s, id) = session("One\nTwo");
+ // A fresh layer is Basic Paragraph with no paragraph override.
+ let cur = s.execute("type.paragraphStyle.list", json!({"layer": id})).unwrap()["current"].clone();
+ assert_eq!((cur["paragraph"].as_u64(), cur["paragraphOverride"].as_bool()), (Some(0), Some(false)));
+ let r = s.execute("type.paragraphStyle.new", json!({"name": "Head", "fromSelection": false, "attrs": {"align": "center", "size": 24, "weight": 700}})).unwrap();
+ let ps = r["id"].as_u64().unwrap() as u32;
+ s.execute("type.paragraphStyle.apply", json!({"id": ps, "layer": id, "range": [0, 1]})).unwrap();
+ let t = layer(&s, id);
+ let p = t.paragraph_runs();
+ assert_eq!(p[0].style.style_sheet, Some(ps));
+ assert_eq!(p[0].style.align, photocraft_doc::text::TextAlign::Center);
+ assert_eq!(p.last().unwrap().style.style_sheet, None);
+ // The first paragraph's characters are on the style's basis.
+ assert_eq!((run_at(&t, 0).size_pt, run_at(&t, 0).weight), (24.0, 700));
+ assert_eq!(run_at(&t, 5).size_pt, 12.0);
+ // Redefining Basic Paragraph moves the second paragraph only.
+ s.execute("type.paragraphStyle.set", json!({"id": 0, "attrs": {"spaceBefore": 6}})).unwrap();
+ let t = layer(&s, id);
+ let p = t.paragraph_runs();
+ assert_eq!(p.last().unwrap().style.space_before_pt, 6.0);
+ assert_eq!(p[0].style.space_before_pt, 6.0, "Head inherits Basic Paragraph for unset attributes");
+ // Basic Paragraph can't be deleted or renamed; bad ids and attributes are rejected.
+ assert!(s.execute("type.paragraphStyle.delete", json!({"id": 0})).is_err());
+ assert!(s.execute("type.paragraphStyle.rename", json!({"id": 0, "name": "x"})).is_err());
+ assert!(s.execute("type.characterStyle.apply", json!({"id": 99})).is_err());
+ assert!(s.execute("type.characterStyle.new", json!({"attrs": {"bogus": 1}})).is_err());
+ assert!(s.execute("type.characterStyle.new", json!({"attrs": {"size_pt": "big"}})).is_err());
+ // Delete keeps the look.
+ s.execute("type.paragraphStyle.delete", json!({"id": ps})).unwrap();
+ let t = layer(&s, id);
+ assert_eq!(t.paragraph_runs()[0].style.align, photocraft_doc::text::TextAlign::Center);
+ assert_eq!(t.paragraph_runs()[0].style.style_sheet, None);
+}
+
+#[test]
+fn styles_survive_typing_and_save() {
+ let (mut s, id) = session("ab");
+ let r = s.execute("type.characterStyle.new", json!({"attrs": {"size": 20}, "fromSelection": false})).unwrap();
+ let cs = r["id"].as_u64().unwrap() as u32;
+ s.execute("type.characterStyle.apply", json!({"id": cs, "layer": id})).unwrap();
+ // Typed text inherits the run (and its style reference).
+ s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 2, "text": "cd"}})).unwrap();
+ let t = layer(&s, id);
+ assert_eq!(run_at(&t, 3).style_sheet, Some(cs));
+ // .pcraft round trip keeps the styles and references.
+ let doc = s.active().unwrap().doc.clone();
+ let bytes = photocraft_format::save_to_bytes(&doc, &photocraft_format::SaveOptions::default()).unwrap();
+ let back = photocraft_format::load_from_bytes(&bytes).unwrap();
+ assert_eq!(back.text_styles, doc.text_styles);
+ let LayerContent::Text(t2) = &back.walk().into_iter().find(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).unwrap().2.content else { panic!() };
+ assert_eq!(run_at(t2, 0).style_sheet, Some(cs));
+}
+
+#[test]
+fn disabled_states() {
+ let mut s = Session::new();
+ assert!(!s.is_enabled("type.characterStyle.new"));
+ s.execute("file.new", json!({"width": 10, "height": 10})).unwrap();
+ assert!(s.is_enabled("type.characterStyle.new"));
+ assert!(!s.is_enabled("type.characterStyle.apply"));
+ assert!(s.execute("type.characterStyle.list", json!({})).unwrap()["current"].is_null());
+}
+
+#[test]
+fn shared_attribute_names_accept_both_spellings() {
+ let (mut s, _) = session("x");
+ let r = s.execute("type.characterStyle.new", json!({"fromSelection": false, "attrs": {"color": "#ff0000", "caps": "all", "kerning": "Off"}})).unwrap();
+ let id = r["id"].as_u64().unwrap() as u32;
+ let st = s.active().unwrap().doc.text_styles.resolve_char(None, Some(id), FAMILY);
+ assert_eq!(st.color.to_rgb(), [1.0, 0.0, 0.0]);
+ assert_eq!(st.caps, photocraft_doc::text::Caps::AllCaps);
+ assert_eq!(st.kerning, photocraft_doc::text::Kerning::Off);
+ let r = s.execute("type.paragraphStyle.new", json!({"fromSelection": false, "attrs": {"align": "Center", "direction": "rtl"}})).unwrap();
+ let p = s.active().unwrap().doc.text_styles.resolve_para(Some(r["id"].as_u64().unwrap() as u32));
+ assert_eq!((p.align, p.direction), (photocraft_doc::text::TextAlign::Center, photocraft_doc::text::TextDirection::Rtl));
+}
diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs
new file mode 100644
index 000000000..94500587e
--- /dev/null
+++ b/crates/engine/src/vp_cmds.rs
@@ -0,0 +1,243 @@
+//! Filter › Vanishing Point: perspective planes (drawn, or torn off an edge of another plane),
+//! pasting an image onto a plane and the perspective clone stamp, as one replayable command
+//! ([`photocraft_algo::vanishing`]). The edit lands on the active pixel layer, or on a new layer
+//! with `"newLayer": true` (Photoshop's advice for non-destructive Vanishing Point work).
+
+use photocraft_algo::vanishing::{Edge, Scene, VpPlane, clone_stroke, paste};
+use photocraft_doc::{Document, Layer, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+pub const VP: &str = "filter.vanishingPoint";
+
+fn bad(msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: VP.into(), msg: msg.into() }
+}
+
+fn pt(v: &Value) -> Option<[f64; 2]> {
+ Some([v.get(0)?.as_f64()?, v.get(1)?.as_f64()?])
+}
+
+/// Builds the scene from `"planes"`.
+pub fn scene(p: &Value, canvas: Rect) -> Result<Scene> {
+ let planes = p.get("planes").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(|| bad("pass `planes`: [{\"corners\":[[x,y]×4]}, {\"from\":0,\"edge\":\"top\",\"angle\":90}]"))?;
+ let center = [(canvas.x0 + canvas.x1) as f64 / 2.0, (canvas.y0 + canvas.y1) as f64 / 2.0];
+ let corners = |v: &Value| -> Option<[[f64; 2]; 4]> {
+ let a = v.get("corners")?.as_array()?;
+ Some([pt(a.first()?)?, pt(a.get(1)?)?, pt(a.get(2)?)?, pt(a.get(3)?)?])
+ };
+ let first = corners(&planes[0]).ok_or_else(|| bad("the first plane needs four `corners`"))?;
+ let focal = p.get("focalLength").and_then(Value::as_f64).filter(|f| *f > 0.0);
+ let mut sc = Scene::new(VpPlane { corners: first }, center, focal, canvas.width().max(canvas.height()) as f64);
+ for (i, pl) in planes.iter().enumerate().skip(1) {
+ if let Some(c) = corners(pl) {
+ sc.planes.push(VpPlane { corners: c });
+ continue;
+ }
+ let from = pl.get("from").and_then(Value::as_u64).map(|v| v as usize).filter(|f| *f < sc.planes.len()).ok_or_else(|| bad(format!("plane {i}: `corners` or `from` (an earlier plane)")))?;
+ let edge = match pl.get("edge").and_then(Value::as_str).unwrap_or("top") {
+ "top" => Edge::Top,
+ "right" => Edge::Right,
+ "bottom" => Edge::Bottom,
+ "left" => Edge::Left,
+ e => return Err(bad(format!("plane {i}: unknown edge `{e}`"))),
+ };
+ let angle = pl.get("angle").and_then(Value::as_f64).unwrap_or(90.0);
+ let depth = pl.get("depth").and_then(Value::as_f64).unwrap_or(1.0);
+ sc.tear_off(from, edge, angle, depth).ok_or_else(|| bad(format!("plane {i} would lie behind the camera")))?;
+ }
+ if sc.planes.iter().any(|p| p.homography().is_none()) {
+ return Err(bad("a plane is degenerate"));
+ }
+ Ok(sc)
+}
+
+fn has_layer(s: &Session) -> std::result::Result<(), String> {
+ let d = s.active().ok_or("no document open")?;
+ match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) {
+ Some(LayerContent::Raster(_)) => Ok(()),
+ Some(other) => Err(format!("Vanishing Point needs a pixel layer (active layer is a {} layer)", other.kind_name())),
+ None => Err("no active layer".into()),
+ }
+}
+
+/// Composites `top` over `dst` (premultiplied source-over), same format.
+fn over(dst: &mut Surface, top: &Surface) {
+ let b = top.content_bounds();
+ if b.is_empty() {
+ return;
+ }
+ let top = if top.format() == dst.format() { top.clone() } else { top.convert(dst.format()) };
+ let fmt = dst.format();
+ let n = fmt.channels();
+ let (t, mut d) = (top.read_region(b), dst.read_region(b));
+ for (tp, dp) in t.chunks_exact(n).zip(d.chunks_exact_mut(n)) {
+ if !fmt.alpha {
+ dp.copy_from_slice(tp);
+ continue;
+ }
+ let (ta, da) = (tp[n - 1], dp[n - 1]);
+ let oa = ta + da * (1.0 - ta);
+ for c in 0..n - 1 {
+ dp[c] = if oa > 0.0 { (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa } else { 0.0 };
+ }
+ dp[n - 1] = oa;
+ }
+ dst.write_region(b, &d);
+}
+
+fn vanishing_point(s: &mut Session, p: &Value) -> Result<Value> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let canvas = st.doc.bounds();
+ let sc = scene(p, canvas)?;
+ // Paste sources resolved up front (layer pixels or the clipboard).
+ let mut pastes: Vec<(usize, Surface, Rect, [f64; 2], f64)> = Vec::new();
+ for (k, item) in p.get("paste").and_then(Value::as_array).cloned().unwrap_or_default().iter().enumerate() {
+ let plane = item.get("plane").and_then(Value::as_u64).unwrap_or(0) as usize;
+ if plane >= sc.planes.len() {
+ return Err(bad(format!("paste {k}: no plane {plane}")));
+ }
+ let (surf, rect) = match item.get("layer").and_then(Value::as_u64) {
+ Some(l) => {
+ let sf = st.doc.layer(LayerId(l)).and_then(Layer::surface).ok_or(EngineError::NoLayer(LayerId(l)))?;
+ (sf.clone(), sf.content_bounds())
+ }
+ None => {
+ let clip = s.clipboard.as_ref().ok_or_else(|| bad(format!("paste {k}: nothing on the clipboard (or pass `layer`)")))?;
+ (clip.surface.clone(), clip.surface.content_bounds())
+ }
+ };
+ let at = item.get("at").and_then(pt).unwrap_or([0.25, 0.25]);
+ let width = item.get("width").and_then(Value::as_f64).unwrap_or(0.5).clamp(0.01, 10.0);
+ pastes.push((plane, surf, rect, at, width));
+ }
+ let clones: Vec<Value> = p.get("clone").and_then(Value::as_array).cloned().unwrap_or_default();
+ let new_layer = p.get("newLayer").and_then(Value::as_bool).unwrap_or(false);
+ let mut dabs = 0usize;
+ let target = s.edit("Vanishing Point", |doc: &mut Document, active| {
+ let id = if new_layer {
+ let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format());
+ let nid = doc.insert_above(*active, l);
+ *active = Some(nid);
+ nid
+ } else {
+ active.ok_or_else(|| EngineError::Other("no active layer".into()))?
+ };
+ // A new layer clones from the visible image; otherwise from the layer itself.
+ let base: Option<Surface> = new_layer.then(|| crate::file_cmds::flattened(doc, doc.pixel_format()));
+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ if l.locks.all || l.locks.pixels {
+ return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));
+ }
+ let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Vanishing Point needs a pixel layer".into()))?;
+ for (plane, src, rect, at, width) in &pastes {
+ if let Some(out) = paste(&sc, *plane, src, *rect, *at, *width) {
+ over(surf, &out);
+ }
+ }
+ for (k, c) in clones.iter().enumerate() {
+ let source = c.get("source").and_then(pt).ok_or_else(|| bad(format!("clone {k}: `source` [x,y]")))?;
+ let points: Vec<[f64; 2]> = c.get("points").and_then(Value::as_array).map(|a| a.iter().filter_map(pt).collect()).unwrap_or_default();
+ let size = c.get("size").and_then(Value::as_f64).unwrap_or(40.0).clamp(1.0, 2000.0);
+ let hardness = c.get("hardness").and_then(Value::as_f64).unwrap_or(50.0).clamp(0.0, 100.0) / 100.0;
+ let opacity = (c.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) / 100.0) as f32;
+ // Sample from the original pixels (merged with what's been pasted).
+ let mut work = match &base {
+ Some(b) => {
+ let mut w = b.clone();
+ over(&mut w, surf);
+ w
+ }
+ None => surf.clone(),
+ };
+ let before = work.clone();
+ dabs += clone_stroke(&sc, &mut work, source, &points, size, hardness, opacity);
+ // Copy back only what the stroke changed.
+ let b = work.content_bounds().union(&before.content_bounds());
+ if !b.is_empty() {
+ let (nw, ow) = (work.read_region(b), before.read_region(b));
+ let n = surf.format().channels();
+ let mut cur = surf.read_region(b);
+ for i in 0..cur.len() / n {
+ if nw[i * n..(i + 1) * n] != ow[i * n..(i + 1) * n] {
+ cur[i * n..(i + 1) * n].copy_from_slice(&nw[i * n..(i + 1) * n]);
+ }
+ }
+ surf.write_region(b, &cur);
+ }
+ }
+ surf.prune();
+ Ok(id)
+ })?;
+ let planes: Vec<Value> = sc.planes.iter().enumerate().map(|(i, pl)| {
+ let (lu, lv) = sc.lifted(i).lengths();
+ json!({"corners": pl.corners, "aspect": lu / lv})
+ }).collect();
+ Ok(json!({"layer": target.0, "focal": sc.focal, "planes": planes, "pasted": pastes.len(), "dabs": dabs}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: VP,
+ label: "Vanishing Point…",
+ menu: &["Filter"],
+ shortcut: Some("Cmd+Alt+V"),
+ params: r##"{"planes":[{"corners":[[x,y]×4]} | {"from":plane,"edge":"top|right|bottom|left","angle":deg=90,"depth":1}],"focalLength":px=0,"paste":[{"plane":0,"layer":id? (else the clipboard),"at":[u,v]=[0.25,0.25],"width":0..1=0.5}],"clone":[{"source":[x,y],"points":[[x,y]],"size":px=40,"hardness":0..100=50,"opacity":0..100=100}],"newLayer":bool=false}"##,
+ enabled: has_layer,
+ run: vanishing_point,
+ journal: true,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn planes_paste_and_clone() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "floor"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#404040"})).unwrap();
+ let floor = s.active().unwrap().active_layer.unwrap();
+ // A trapezoid "floor" receding to the top.
+ let planes = json!([{"corners": [[120, 120], [280, 120], [360, 280], [40, 280]]}, {"from": 0, "edge": "top", "angle": 90}]);
+ s.execute("layer.new.layer", json!({"name": "sticker"})).unwrap();
+ s.edit("sticker", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 20), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let sticker = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.select", json!({"layer": floor.0})).unwrap();
+ let r = s.execute(VP, json!({"planes": planes, "paste": [{"plane": 0, "layer": sticker.0, "at": [0.3, 0.4], "width": 0.4}]})).unwrap();
+ assert_eq!(r["planes"].as_array().unwrap().len(), 2);
+ assert!(r["focal"].as_f64().unwrap() > 50.0, "{r}");
+ let l = s.active().unwrap().doc.layer(floor).unwrap().surface().unwrap().clone();
+ // The paste covers the plane's middle and not its far corner.
+ let h = VpPlane { corners: [[120.0, 120.0], [280.0, 120.0], [360.0, 280.0], [40.0, 280.0]] }.homography().unwrap();
+ let (x, y) = h.apply(0.5, 0.41);
+ assert!(l.rgba(x as i32, y as i32)[0] > 0.9, "{:?}", l.rgba(x as i32, y as i32));
+ assert!(l.rgba(130, 125)[0] < 0.5);
+ s.undo();
+ // Clone: copy the bright stripe painted near the bottom to the top of the floor.
+ s.edit("stripe", |doc, _| {
+ doc.layer_mut(floor).unwrap().surface_mut().unwrap().fill_rect(Rect::new(180, 250, 220, 265), &[0.0, 1.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layer.select", json!({"layer": floor.0})).unwrap();
+ let r = s.execute(VP, json!({"planes": planes, "clone": [{"source": [200, 257], "points": [[200, 160], [205, 160]], "size": 12, "hardness": 80}]})).unwrap();
+ assert!(r["dabs"].as_u64().unwrap() >= 1, "{r}");
+ let l = s.active().unwrap().doc.layer(floor).unwrap().surface().unwrap();
+ assert!(l.rgba(200, 160)[1] > 0.8, "{:?}", l.rgba(200, 160));
+ assert!(s.execute(VP, json!({})).is_err());
+ assert!(s.execute(VP, json!({"planes": [{"corners": [[0, 0], [1, 1]]}]})).is_err());
+ let r = s.execute(VP, json!({"planes": planes, "newLayer": true})).unwrap();
+ assert_ne!(r["layer"].as_u64().unwrap(), floor.0);
+ }
+}
diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs
new file mode 100644
index 000000000..f95ca4b29
--- /dev/null
+++ b/crates/engine/src/web_cmds.rs
@@ -0,0 +1,1109 @@
+//! File › Export › Save for Web (Legacy), File › Export › Export Preferences, the Quick Export
+//! pipeline that honours them, and File › Generate › Image Assets (Photoshop's Generator).
+//!
+//! Save for Web optimises the flattened (optionally resized, sRGB-converted) image as GIF,
+//! PNG-8, PNG-24, JPEG or WBMP, per slice, into a folder with an optional HTML table; without an
+//! output it only reports the optimised size (the dialog's 2-Up/4-Up annotations). Colour
+//! reduction and dithering reuse `algo::quantize`; GIF/WBMP/progressive JPEG writers live in
+//! `codecs::web`.
+//!
+//! Image Assets implements the naming grammar of Adobe's public Generator documentation: a
+//! layer or group named `foo.png`, `200% [email protected], 48x48 icons/foo.png8`, `photo.jpg80%`,
+//! `?x100 thumb.gif` is exported into `<document>-assets/` whenever the document is saved while
+//! the feature is on; a `default` layer (`default 50% low/ + 200% @2x`) adds variants.
+
+use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind};
+use photocraft_doc::slices::{self, ResolvedSlice, SliceKind};
+use photocraft_doc::{DocId, Document, LayerContent, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::file_cmds::{join, native_doc, stem, write_file};
+use crate::{EngineError, Result, Session};
+
+fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
+}
+fn other(e: impl std::fmt::Display) -> EngineError {
+ EngineError::Other(e.to_string())
+}
+
+// ---------- settings ----------
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum WebFormat {
+ Gif,
+ Png8,
+ Png24,
+ Jpeg,
+ Wbmp,
+}
+
+impl WebFormat {
+ pub fn from_id(s: &str) -> Option<Self> {
+ Some(match s.to_ascii_lowercase().as_str() {
+ "gif" => WebFormat::Gif,
+ "png8" | "png-8" => WebFormat::Png8,
+ "png24" | "png-24" | "png" | "png32" => WebFormat::Png24,
+ "jpeg" | "jpg" => WebFormat::Jpeg,
+ "wbmp" => WebFormat::Wbmp,
+ _ => return None,
+ })
+ }
+ pub fn ext(self) -> &'static str {
+ match self {
+ WebFormat::Gif => "gif",
+ WebFormat::Png8 | WebFormat::Png24 => "png",
+ WebFormat::Jpeg => "jpg",
+ WebFormat::Wbmp => "wbmp",
+ }
+ }
+ pub fn indexed(self) -> bool {
+ matches!(self, WebFormat::Gif | WebFormat::Png8)
+ }
+}
+
+/// Which metadata Save for Web embeds (JPEG only, like Photoshop's legacy exporter).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum WebMetadata {
+ None,
+ Copyright,
+ CopyrightAndContact,
+ All,
+}
+
+/// One optimisation preset (the right-hand side of the Save for Web dialog).
+#[derive(Clone, Debug, PartialEq)]
+pub struct WebSettings {
+ pub format: WebFormat,
+ pub palette: PaletteKind,
+ pub colors: usize,
+ pub dither: Dither,
+ /// 0..=1.
+ pub dither_amount: f32,
+ pub transparency: bool,
+ /// Edge / background colour (0..=1 RGB); None = no matte (hard alpha threshold).
+ pub matte: Option<[f32; 3]>,
+ pub interlaced: bool,
+ /// Web Snap: palette entries within this distance (0..=1 of the channel range) snap to the
+ /// web-safe cube.
+ pub web_snap: f32,
+ /// JPEG quality 0..=100.
+ pub quality: u8,
+ pub progressive: bool,
+ pub optimized: bool,
+ pub embed_icc: bool,
+ pub metadata: WebMetadata,
+ pub convert_to_srgb: bool,
+}
+
+impl Default for WebSettings {
+ fn default() -> Self {
+ WebSettings {
+ format: WebFormat::Png24,
+ palette: PaletteKind::Selective,
+ colors: 256,
+ dither: Dither::Diffusion,
+ dither_amount: 0.88,
+ transparency: true,
+ matte: Some([1.0, 1.0, 1.0]),
+ interlaced: false,
+ web_snap: 0.0,
+ quality: 60,
+ progressive: false,
+ optimized: true,
+ embed_icc: false,
+ metadata: WebMetadata::Copyright,
+ convert_to_srgb: true,
+ }
+ }
+}
+
+fn hex3(s: &str) -> Option<[f32; 3]> {
+ let s = s.trim_start_matches('#');
+ let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| f32::from(v) / 255.0);
+ (s.len() == 6).then_some(())?;
+ Some([b(0)?, b(2)?, b(4)?])
+}
+
+impl WebSettings {
+ /// Settings from command parameters (missing keys keep the defaults; Photoshop's preset
+ /// names such as "GIF 128 Dithered" or "JPEG High" are accepted as `"preset"`).
+ pub fn from_params(p: &Value, cmd: &str) -> Result<Self> {
+ let mut st = WebSettings::default();
+ if let Some(preset) = p.get("preset").and_then(Value::as_str) {
+ st = preset_settings(preset).ok_or_else(|| bad(cmd, format!("unknown preset `{preset}`")))?;
+ }
+ let s = |k: &str| p.get(k).and_then(Value::as_str);
+ if let Some(f) = s("format") {
+ st.format = WebFormat::from_id(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}` (gif|png8|png24|jpeg|wbmp)")))?;
+ }
+ if let Some(k) = s("palette") {
+ st.palette = match k {
+ "restrictive" | "web" => PaletteKind::Web,
+ k => PaletteKind::from_id(k).ok_or_else(|| bad(cmd, format!("unknown palette `{k}` (perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform)")))?,
+ };
+ }
+ if let Some(n) = p.get("colors").and_then(Value::as_u64) {
+ st.colors = (n as usize).clamp(2, 256);
+ }
+ if let Some(d) = s("dither") {
+ st.dither = match d {
+ "none" | "noDither" => Dither::None,
+ "diffusion" => Dither::Diffusion,
+ "pattern" => Dither::Pattern,
+ "noise" => Dither::Noise,
+ d => return Err(bad(cmd, format!("unknown dither `{d}` (none|diffusion|pattern|noise)"))),
+ };
+ }
+ if let Some(a) = p.get("ditherAmount").and_then(Value::as_f64) {
+ st.dither_amount = (a as f32 / 100.0).clamp(0.0, 1.0);
+ }
+ if let Some(b) = p.get("transparency").and_then(Value::as_bool) {
+ st.transparency = b;
+ }
+ match s("matte") {
+ Some("none") => st.matte = None,
+ Some(c) => st.matte = Some(hex3(c).ok_or_else(|| bad(cmd, "matte is \"none\" or \"#rrggbb\""))?),
+ None => {}
+ }
+ for (k, slot) in [("interlaced", &mut st.interlaced), ("progressive", &mut st.progressive), ("optimized", &mut st.optimized), ("embedIcc", &mut st.embed_icc), ("convertToSrgb", &mut st.convert_to_srgb)] {
+ if let Some(b) = p.get(k).and_then(Value::as_bool) {
+ *slot = b;
+ }
+ }
+ if let Some(w) = p.get("webSnap").and_then(Value::as_f64) {
+ st.web_snap = (w as f32 / 100.0).clamp(0.0, 1.0);
+ }
+ if let Some(q) = p.get("quality").and_then(Value::as_f64) {
+ st.quality = q.clamp(0.0, 100.0).round() as u8;
+ }
+ if let Some(m) = s("metadata") {
+ st.metadata = match m {
+ "none" => WebMetadata::None,
+ "copyright" => WebMetadata::Copyright,
+ "copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact,
+ "all" | "allExceptCameraInfo" => WebMetadata::All,
+ m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|all)"))),
+ };
+ }
+ Ok(st)
+ }
+}
+
+impl WebSettings {
+ /// The settings as command parameters (the inverse of [`WebSettings::from_params`]).
+ pub fn to_params(&self) -> Value {
+ let format = match self.format {
+ WebFormat::Gif => "gif",
+ WebFormat::Png8 => "png8",
+ WebFormat::Png24 => "png24",
+ WebFormat::Jpeg => "jpeg",
+ WebFormat::Wbmp => "wbmp",
+ };
+ let palette = match self.palette {
+ PaletteKind::Exact => "exact",
+ PaletteKind::SystemMac => "systemMac",
+ PaletteKind::SystemWindows => "systemWindows",
+ PaletteKind::Web => "restrictive",
+ PaletteKind::Uniform => "uniform",
+ PaletteKind::Perceptual => "perceptual",
+ PaletteKind::Selective => "selective",
+ PaletteKind::Adaptive => "adaptive",
+ };
+ let dither = match self.dither {
+ Dither::None => "none",
+ Dither::Diffusion => "diffusion",
+ Dither::Pattern => "pattern",
+ Dither::Noise => "noise",
+ };
+ let metadata = match self.metadata {
+ WebMetadata::None => "none",
+ WebMetadata::Copyright => "copyright",
+ WebMetadata::CopyrightAndContact => "copyrightAndContact",
+ WebMetadata::All => "all",
+ };
+ let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2])));
+ json!({"format": format, "palette": palette, "colors": self.colors, "dither": dither, "ditherAmount": (self.dither_amount * 100.0).round(), "transparency": self.transparency, "matte": matte, "interlaced": self.interlaced, "webSnap": (self.web_snap * 100.0).round(), "quality": self.quality, "progressive": self.progressive, "optimized": self.optimized, "embedIcc": self.embed_icc, "metadata": metadata, "convertToSrgb": self.convert_to_srgb})
+ }
+}
+
+/// Save for Web's named presets.
+pub const PRESETS: [&str; 12] = ["GIF 128 Dithered", "GIF 128 No Dither", "GIF 32 Dithered", "GIF 32 No Dither", "GIF 64 Dithered", "GIF 64 No Dither", "GIF Restrictive", "JPEG High", "JPEG Low", "JPEG Medium", "PNG-24", "PNG-8 128 Dithered"];
+
+pub fn preset_settings(name: &str) -> Option<WebSettings> {
+ let d = WebSettings::default();
+ let gif = |colors: usize, dither: bool| WebSettings { format: WebFormat::Gif, colors, dither: if dither { Dither::Diffusion } else { Dither::None }, ..WebSettings::default() };
+ Some(match name {
+ "GIF 128 Dithered" => gif(128, true),
+ "GIF 128 No Dither" => gif(128, false),
+ "GIF 32 Dithered" => gif(32, true),
+ "GIF 32 No Dither" => gif(32, false),
+ "GIF 64 Dithered" => gif(64, true),
+ "GIF 64 No Dither" => gif(64, false),
+ "GIF Restrictive" => WebSettings { palette: PaletteKind::Web, ..gif(256, true) },
+ "JPEG High" => WebSettings { format: WebFormat::Jpeg, quality: 60, ..d },
+ "JPEG Low" => WebSettings { format: WebFormat::Jpeg, quality: 10, ..d },
+ "JPEG Medium" => WebSettings { format: WebFormat::Jpeg, quality: 30, ..d },
+ "JPEG Maximum" => WebSettings { format: WebFormat::Jpeg, quality: 100, ..d },
+ "JPEG Very High" => WebSettings { format: WebFormat::Jpeg, quality: 80, ..d },
+ "PNG-24" => WebSettings { format: WebFormat::Png24, ..d },
+ "PNG-8 128 Dithered" => WebSettings { format: WebFormat::Png8, colors: 128, ..d },
+ _ => return None,
+ })
+}
+
+// ---------- the image ----------
+
+/// The document as Save for Web sees it: RGB (converted to sRGB unless told otherwise), resized
+/// by `"width"`/`"height"`/`"percent"`, flattened. Returns the document and the scale factors.
+pub fn web_document(doc: &Document, p: &Value, st: &WebSettings) -> Result<(Document, f64, f64)> {
+ let mut tmp = Session::new();
+ tmp.add_document(doc.clone(), None);
+ let mode = doc.mode;
+ if mode != photocraft_color::ColorMode::Rgb {
+ tmp.execute("image.mode.rgb", json!({}))?;
+ }
+ if st.convert_to_srgb && doc.icc_profile.is_some() {
+ // Documents without a profile are treated as sRGB already.
+ tmp.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "perceptual"}))?;
+ }
+ let (w0, h0) = (f64::from(doc.size.width), f64::from(doc.size.height));
+ let pct = p.get("percent").and_then(Value::as_f64).filter(|v| *v > 0.0);
+ let w = p.get("width").and_then(Value::as_f64).filter(|v| *v > 0.0);
+ let h = p.get("height").and_then(Value::as_f64).filter(|v| *v > 0.0);
+ let (nw, nh) = match (pct, w, h) {
+ (Some(pc), _, _) => (w0 * pc / 100.0, h0 * pc / 100.0),
+ (_, Some(w), Some(h)) => (w, h),
+ (_, Some(w), None) => (w, h0 * w / w0),
+ (_, None, Some(h)) => (w0 * h / h0, h),
+ _ => (w0, h0),
+ };
+ let (nw, nh) = (nw.round().max(1.0), nh.round().max(1.0));
+ if (nw - w0).abs() >= 1.0 || (nh - h0).abs() >= 1.0 {
+ let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic");
+ tmp.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?;
+ }
+ let out = (*tmp.active().ok_or(EngineError::NoDocument)?.doc).clone();
+ Ok((out, nw / w0, nh / h0))
+}
+
+/// An optimised image.
+#[derive(Clone, Debug)]
+pub struct Optimized {
+ pub bytes: Vec<u8>,
+ pub ext: &'static str,
+ pub width: u32,
+ pub height: u32,
+ /// Colours in the palette (indexed formats).
+ pub colors: Option<usize>,
+ /// What the optimised file looks like, straight RGBA8 (for the dialog's previews).
+ pub preview: Vec<u8>,
+}
+
+fn to8(v: f32) -> u8 {
+ (v.clamp(0.0, 1.0) * 255.0).round() as u8
+}
+
+/// XMP to embed for the metadata choice.
+pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option<String> {
+ let xmp = doc.metadata.xmp.as_deref()?;
+ match m {
+ WebMetadata::None => None,
+ WebMetadata::All => Some(xmp.to_string()),
+ WebMetadata::Copyright | WebMetadata::CopyrightAndContact => {
+ let info = crate::file_cmds::read_file_info(Some(xmp));
+ let mut keep = serde_json::Map::new();
+ let mut keys = vec!["copyright", "copyrightStatus", "copyrightUrl"];
+ if m == WebMetadata::CopyrightAndContact {
+ keys.extend(["author", "authorTitle"]);
+ }
+ for k in keys {
+ if let Some(v) = info.get(k).filter(|v| v.as_str().is_some_and(|s| !s.is_empty()) || v.is_array()) {
+ keep.insert(k.into(), v.clone());
+ }
+ }
+ (!keep.is_empty()).then(|| crate::file_cmds::write_file_info(None, &Value::Object(keep)))
+ }
+ }
+}
+
+/// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what
+/// the file looks like (the dialog's panes); exports skip it.
+#[allow(clippy::too_many_arguments)]
+pub fn optimize(px: &[[f32; 4]], bw: usize, rect: Rect, st: &WebSettings, icc: Option<&[u8]>, xmp: Option<&str>, dpi: f32, preview: bool) -> Result<Optimized> {
+ let (w, h) = (rect.width() as usize, rect.height() as usize);
+ if w == 0 || h == 0 {
+ return Err(other("empty slice"));
+ }
+ let row = |y: i32| {
+ let o = y as usize * bw;
+ &px[o + rect.x0 as usize..o + rect.x1 as usize]
+ };
+ let region = || (rect.y0..rect.y1).flat_map(row);
+ let matte = st.matte.unwrap_or([1.0, 1.0, 1.0]);
+ let over = |p: &[f32; 4]| -> [f32; 4] { [p[0] * p[3] + matte[0] * (1.0 - p[3]), p[1] * p[3] + matte[1] * (1.0 - p[3]), p[2] * p[3] + matte[2] * (1.0 - p[3]), 1.0] };
+ let (ww, hh) = (w as u32, h as u32);
+ let e = |e: photocraft_codecs::CodecError| other(e);
+ let mut look: Vec<u8> = Vec::new();
+ let (bytes, colors) = match st.format {
+ WebFormat::Png24 => {
+ let alpha = st.transparency && region().any(|p| p[3] < 1.0);
+ let k = if alpha { 4 } else { 3 };
+ let mut data = Vec::with_capacity(w * h * k);
+ for p in region() {
+ let q = if alpha { *p } else { over(p) };
+ data.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2]), to8(q[3])][..k]);
+ }
+ if preview {
+ look = if alpha { data.clone() } else { data.chunks_exact(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect() };
+ }
+ let layout = if alpha { photocraft_codecs::ChannelLayout::Rgba } else { photocraft_codecs::ChannelLayout::Rgb };
+ let meta = photocraft_codecs::Metadata { dpi: Some((dpi, dpi)), xmp: xmp.map(str::to_string), ..Default::default() };
+ let img = photocraft_codecs::Image::from_u8(ww, hh, layout, data).map_err(e)?.with_icc(icc.map(<[u8]>::to_vec)).with_meta(meta);
+ let opts = photocraft_codecs::EncodeOptions { png_interlaced: st.interlaced, embed_icc: icc.is_some(), embed_metadata: xmp.is_some(), ..Default::default() };
+ (photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &opts).map_err(e)?, None)
+ }
+ WebFormat::Jpeg => {
+ let mut rgb = Vec::with_capacity(w * h * 3);
+ for p in region() {
+ let q = over(p);
+ rgb.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2])]);
+ }
+ // Save for Web's 0–100 quality → encoder 1–100.
+ let q = st.quality.max(1);
+ let bytes = photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), xmp).map_err(e)?;
+ if preview {
+ // The preview shows the compression artefacts.
+ look = match photocraft_codecs::decode(&bytes) {
+ Ok(img) => img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec(),
+ Err(_) => rgb.chunks_exact(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect(),
+ };
+ }
+ (bytes, None)
+ }
+ WebFormat::Wbmp => {
+ let mut gray: Vec<f32> = region()
+ .map(|p| {
+ let q = over(p);
+ 0.299 * q[0] + 0.587 * q[1] + 0.114 * q[2]
+ })
+ .collect();
+ let method = match st.dither {
+ Dither::None => quantize::BitmapMethod::Threshold,
+ Dither::Pattern => quantize::BitmapMethod::Pattern,
+ _ => quantize::BitmapMethod::Diffusion,
+ };
+ quantize::to_bitmap(&mut gray, w, method);
+ let white: Vec<bool> = gray.iter().map(|v| *v > 0.5).collect();
+ if preview {
+ look = white.iter().flat_map(|b| if *b { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect();
+ }
+ (photocraft_codecs::web::encode_wbmp(ww, hh, &white).map_err(e)?, Some(2))
+ }
+ WebFormat::Gif | WebFormat::Png8 => {
+ let transparent = st.transparency && region().any(|p| p[3] < 0.5);
+ // Partially transparent edges blend with the matte; with transparency off everything does.
+ let mut work: Vec<[f32; 4]> = region()
+ .map(|p| {
+ if st.transparency && p[3] < 0.5 {
+ [0.0, 0.0, 0.0, 0.0]
+ } else if st.transparency && st.matte.is_none() {
+ [p[0], p[1], p[2], 1.0]
+ } else {
+ over(p)
+ }
+ })
+ .collect();
+ let room = if transparent { st.colors.saturating_sub(1).max(2) } else { st.colors };
+ // Large images: build adaptive palettes from an even ~1 MP sample (Exact needs all).
+ let n_opaque = work.iter().filter(|p| p[3] >= 0.5).count();
+ let step = if n_opaque > 1 << 20 && st.palette != PaletteKind::Exact { n_opaque / (1 << 20) + 1 } else { 1 };
+ let mut src: Vec<[f32; 4]> = work.iter().filter(|p| p[3] >= 0.5).step_by(step).copied().collect();
+ if src.is_empty() {
+ src = work.clone();
+ }
+ let mut pal = quantize::build_palette(&src, st.palette, room, Forced::None).map_err(other)?;
+ drop(src);
+ if st.web_snap > 0.0 {
+ let tol = (st.web_snap * 255.0) as u8;
+ for c in &mut pal {
+ let snap = c.map(|x| ((f32::from(x) / 51.0).round() * 51.0) as u8);
+ if c.iter().zip(snap).all(|(a, b)| a.abs_diff(b) <= tol) {
+ *c = snap;
+ }
+ }
+ }
+ if transparent {
+ pal.truncate(255);
+ }
+ let t = transparent.then(|| {
+ pal.push(pal[0]);
+ pal.len() - 1
+ });
+ let idx = quantize_rows(&mut work, w, &pal, st.dither, st.dither_amount, t);
+ if preview {
+ look = idx.iter().flat_map(|k| {
+ let c = pal[*k as usize];
+ [c[0], c[1], c[2], if Some(*k as usize) == t { 0 } else { 255 }]
+ }).collect();
+ }
+ let tt = t.map(|v| v as u8);
+ let bytes = if st.format == WebFormat::Gif {
+ photocraft_codecs::web::encode_gif_indexed(ww, hh, &idx, &pal, tt, st.interlaced).map_err(e)?
+ } else {
+ photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt).map_err(e)?
+ };
+ (bytes, Some(pal.len()))
+ }
+ };
+ Ok(Optimized { bytes, ext: st.format.ext(), width: ww, height: hh, colors, preview: look })
+}
+
+/// Nearest palette entry through a lazily filled 6-bit-per-channel inverse colour map: each
+/// 4×4×4 cell is resolved once (by its centre), so large images cost a table lookup per pixel
+/// instead of a palette scan. `t` (the transparent index) is never returned.
+struct InverseMap<'a> {
+ pal: &'a [[u8; 3]],
+ t: Option<usize>,
+ lut: Vec<u16>,
+}
+
+impl<'a> InverseMap<'a> {
+ fn new(pal: &'a [[u8; 3]], t: Option<usize>) -> Self {
+ InverseMap { pal, t, lut: vec![u16::MAX; 1 << 18] }
+ }
+ #[inline]
+ fn get(&mut self, c: [f32; 3]) -> usize {
+ let q = c.map(|v| ((v.clamp(0.0, 1.0) * 255.0).round() as usize) >> 2);
+ let key = q[0] << 12 | q[1] << 6 | q[2];
+ let v = self.lut[key];
+ if v != u16::MAX {
+ return usize::from(v);
+ }
+ let center = q.map(|v| (v * 4 + 2) as f32);
+ let mut best = (f32::MAX, 0usize);
+ for (i, e) in self.pal.iter().enumerate() {
+ if Some(i) == self.t {
+ continue;
+ }
+ let d: f32 = (0..3).map(|k| (center[k] - f32::from(e[k])).powi(2)).sum();
+ if d < best.0 {
+ best = (d, i);
+ }
+ }
+ self.lut[key] = best.1 as u16;
+ best.1
+ }
+}
+
+fn hash01(x: usize, y: usize) -> f32 {
+ let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x2545_f491;
+ h ^= h >> 13;
+ h = h.wrapping_mul(0x5bd1_e995);
+ h ^= h >> 15;
+ (h & 0xffff) as f32 / 65535.0
+}
+
+/// Palette mapping with dithering (Floyd–Steinberg diffusion, 8×8 Bayer pattern, noise), like
+/// `algo::quantize::quantize` but through [`InverseMap`]. `y0` keeps patterns continuous across
+/// bands. Pixels with alpha < ½ take index `t`.
+fn quantize_band(px: &mut [[f32; 4]], w: usize, y0: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option<usize>) -> Vec<u8> {
+ let h = px.len() / w.max(1);
+ let mut map = InverseMap::new(pal, t);
+ let mut idx = vec![0u8; px.len()];
+ let opaque_n = pal.len() - usize::from(t.is_some());
+ let spread = (1.0 / (opaque_n as f32).cbrt().max(1.0)).min(0.5) * amount.clamp(0.0, 1.0);
+ let a = amount.clamp(0.0, 1.0);
+ let mut cur = vec![[0.0f32; 3]; if dither == Dither::Diffusion { w + 2 } else { 0 }];
+ let mut next = cur.clone();
+ for y in 0..h {
+ if dither == Dither::Diffusion {
+ std::mem::swap(&mut cur, &mut next);
+ next.iter_mut().for_each(|e| *e = [0.0; 3]);
+ }
+ for x in 0..w {
+ let i = y * w + x;
+ let p = px[i];
+ if p[3] < 0.5
+ && let Some(t) = t
+ {
+ idx[i] = t as u8;
+ continue;
+ }
+ let mut c = [p[0], p[1], p[2]];
+ match dither {
+ Dither::None => {}
+ Dither::Diffusion => (0..3).for_each(|k| c[k] += cur[x + 1][k]),
+ Dither::Pattern => {
+ let d = quantize::bayer8(x, y0 + y) * spread;
+ c = c.map(|v| v + d);
+ }
+ Dither::Noise => {
+ let d = (hash01(x, y0 + y) - 0.5) * spread;
+ c = c.map(|v| v + d);
+ }
+ }
+ let c = c.map(|v| v.clamp(0.0, 1.0));
+ let k = map.get(c);
+ idx[i] = k as u8;
+ if dither == Dither::Diffusion {
+ let e = pal[k].map(|v| f32::from(v) / 255.0);
+ let d: [f32; 3] = std::array::from_fn(|q| (c[q] - e[q]) * a);
+ for q in 0..3 {
+ cur[x + 2][q] += d[q] * 7.0 / 16.0;
+ next[x][q] += d[q] * 3.0 / 16.0;
+ next[x + 1][q] += d[q] * 5.0 / 16.0;
+ next[x + 2][q] += d[q] / 16.0;
+ }
+ }
+ }
+ }
+ idx
+}
+
+/// [`quantize_band`] over the whole image, in parallel bands of 64 rows when the dither is
+/// position-independent. Error diffusion carries error down the image, so it stays sequential.
+fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option<usize>) -> Vec<u8> {
+ let h = px.len() / w.max(1);
+ if dither == Dither::Diffusion || h < 128 || cfg!(target_arch = "wasm32") {
+ return quantize_band(px, w, 0, pal, dither, amount, t);
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ let band = w * 64;
+ let mut idx = vec![0u8; px.len()];
+ px.par_chunks_mut(band).zip(idx.par_chunks_mut(band)).enumerate().for_each(|(i, (p, out))| out.copy_from_slice(&quantize_band(p, w, i * 64, pal, dither, amount, t)));
+ idx
+ }
+ #[cfg(target_arch = "wasm32")]
+ unreachable!()
+}
+
+/// A file-name-safe slice name.
+fn slice_file(name: &str) -> String {
+ let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect();
+ if s.is_empty() { "slice".into() } else { s }
+}
+
+fn html_escape(s: &str) -> String {
+ s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+}
+
+fn scale_rect(r: Rect, sx: f64, sy: f64) -> Rect {
+ Rect::new((f64::from(r.x0) * sx).round() as i32, (f64::from(r.y0) * sy).round() as i32, (f64::from(r.x1) * sx).round() as i32, (f64::from(r.y1) * sy).round() as i32)
+}
+
+/// The HTML table for `cells` (rect, td body) over a `w`×`h` image: one column per distinct x
+/// edge, one row per y edge, colspan/rowspan per slice, and a spacer row fixing column widths.
+fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spacer: Option<&str>) -> String {
+ let mut xs: Vec<i32> = cells.iter().flat_map(|(r, _, _)| [r.x0, r.x1]).collect();
+ let mut ys: Vec<i32> = cells.iter().flat_map(|(r, _, _)| [r.y0, r.y1]).collect();
+ xs.sort_unstable();
+ xs.dedup();
+ ys.sort_unstable();
+ ys.dedup();
+ let col = |x: i32| xs.iter().position(|v| *v == x).unwrap_or(0);
+ let row = |y: i32| ys.iter().position(|v| *v == y).unwrap_or(0);
+ let (nc, nr) = (xs.len().saturating_sub(1), ys.len().saturating_sub(1));
+ let mut taken = vec![false; nc * nr];
+ let mut by_row: Vec<Vec<(usize, String)>> = vec![Vec::new(); nr];
+ for (r, attrs, body) in cells {
+ let (c0, c1, r0, r1) = (col(r.x0), col(r.x1), row(r.y0), row(r.y1));
+ if (r0..r1).any(|j| (c0..c1).any(|i| taken[j * nc + i])) {
+ continue; // overlapped by an earlier slice
+ }
+ for j in r0..r1 {
+ for i in c0..c1 {
+ taken[j * nc + i] = true;
+ }
+ }
+ let mut td = String::from("\t\t<td");
+ if c1 - c0 > 1 {
+ td.push_str(&format!(" colspan=\"{}\"", c1 - c0));
+ }
+ if r1 - r0 > 1 {
+ td.push_str(&format!(" rowspan=\"{}\"", r1 - r0));
+ }
+ td.push_str(attrs);
+ td.push('>');
+ td.push_str(body);
+ td.push_str("</td>\n");
+ by_row[r0].push((c0, td));
+ }
+ let mut s = format!(
+ "<html>\n<head>\n<title>{t}</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n</head>\n<body bgcolor=\"#FFFFFF\" leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\">\n<!-- Save for Web Slices ({t}) -->\n<table id=\"Table_01\" width=\"{w}\" height=\"{h}\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n",
+ t = html_escape(title)
+ );
+ for (j, mut tds) in by_row.into_iter().enumerate() {
+ tds.sort_by_key(|(c, _)| *c);
+ s.push_str("\t<tr>\n");
+ for (_, td) in tds {
+ s.push_str(&td);
+ }
+ if let Some(sp) = spacer {
+ s.push_str(&format!("\t\t<td>\n\t\t\t<img src=\"{sp}\" width=\"1\" height=\"{}\" alt=\"\"></td>\n", ys[j + 1] - ys[j]));
+ }
+ s.push_str("\t</tr>\n");
+ }
+ if let Some(sp) = spacer {
+ s.push_str("\t<tr>\n");
+ for i in 0..nc {
+ s.push_str(&format!("\t\t<td>\n\t\t\t<img src=\"{sp}\" width=\"{}\" height=\"1\" alt=\"\"></td>\n", xs[i + 1] - xs[i]));
+ }
+ s.push_str("\t\t<td></td>\n\t</tr>\n");
+ }
+ s.push_str("</table>\n<!-- End Save for Web Slices -->\n</body>\n</html>\n");
+ s
+}
+
+/// File › Export › Save for Web (Legacy).
+fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.saveForWebLegacy";
+ let st = WebSettings::from_params(p, cmd)?;
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let (wdoc, sx, sy) = web_document(&doc, p, &st)?;
+ let buf = photocraft_compose::flatten(&wdoc);
+ let bw = wdoc.size.width as usize;
+ let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice());
+ let xmp = web_xmp(&doc, st.metadata);
+ let dpi = wdoc.resolution_dpi;
+ let all = slices::resolve(&doc);
+ let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all");
+ let numbers: Option<Vec<u64>> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect());
+ let chosen: Vec<&ResolvedSlice> = all
+ .iter()
+ .filter(|r| match (&numbers, pick) {
+ (Some(n), _) => n.contains(&(r.number as u64)),
+ (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto,
+ _ => true,
+ })
+ .collect();
+ let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty());
+ let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty());
+ s.file_menu.last_web = Some(p.clone());
+ // Estimate only (the dialog's annotations): the whole image, or each chosen slice.
+ if single.is_none() && dir.is_none() {
+ let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
+ return Ok(json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors}));
+ }
+ if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) {
+ let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
+ write_file(path, &o.bytes)?;
+ crate::automate_cmds::fire_event(s, "export");
+ return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors}));
+ }
+ let dir = dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default();
+ let html = p.get("html").and_then(Value::as_bool).unwrap_or(false);
+ let images = p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images").to_string();
+ let base = single.map(stem).unwrap_or_else(|| slices::base_name(&doc));
+ let mut files = Vec::new();
+ let mut cells: Vec<(Rect, String, String)> = Vec::new();
+ let mut total = 0usize;
+ for r in &chosen {
+ let rect = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds());
+ if rect.is_empty() {
+ continue;
+ }
+ let stored = r.id.and_then(|id| doc.slices.get(id));
+ if r.kind == SliceKind::NoImage {
+ let text = stored.map(|s| if s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }).unwrap_or_default();
+ let bg = stored.and_then(|s| s.background).map(|c| format!(" bgcolor=\"#{:02X}{:02X}{:02X}\"", c[1], c[2], c[3])).unwrap_or_default();
+ cells.push((rect, bg, text));
+ continue;
+ }
+ let o = optimize(&buf.px, bw, rect, &st, icc, xmp.as_deref(), dpi, false)?;
+ let name = format!("{}.{}", slice_file(&r.name), o.ext);
+ let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") };
+ let out = join(&dir, &rel);
+ write_file(&out, &o.bytes)?;
+ total += o.bytes.len();
+ files.push(out);
+ let alt = stored.map_or(String::new(), |s| html_escape(&s.alt));
+ let img = format!("\n\t\t\t<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{alt}\">", html_escape(&rel), rect.width(), rect.height());
+ let body = match stored.filter(|s| !s.url.is_empty()) {
+ Some(s) => {
+ let target = if s.target.is_empty() { String::new() } else { format!(" target=\"{}\"", html_escape(&s.target)) };
+ format!("\n\t\t\t<a href=\"{}\"{target}>{img}</a>", html_escape(&s.url))
+ }
+ None => img,
+ };
+ cells.push((rect, String::new(), body));
+ }
+ let mut html_path = None;
+ if html {
+ let grid = cells.len() > 1;
+ let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") });
+ if let Some(sp) = &spacer {
+ let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?;
+ write_file(&join(&dir, sp), &gif)?;
+ }
+ let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref());
+ let hp = join(&dir, &format!("{base}.html"));
+ write_file(&hp, page.as_bytes())?;
+ html_path = Some(hp);
+ }
+ crate::automate_cmds::fire_event(s, "export");
+ Ok(json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height}))
+}
+
+// ---------- Export Preferences / Quick Export ----------
+
+fn export_preferences(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.exportPreferences";
+ let mut values = serde_json::Map::new();
+ for (k, key) in [("quickExportFormat", "export.quickExportFormat"), ("quickExportLocation", "export.quickExportLocation"), ("jpegQuality", "export.jpegQuality"), ("metadata", "export.metadata"), ("convertToSrgb", "export.convertToSrgb")] {
+ if let Some(v) = p.get(k) {
+ values.insert(key.into(), v.clone());
+ }
+ }
+ if !values.is_empty() {
+ s.execute("prefs.set", json!({"values": values})).map_err(|e| bad(cmd, e.to_string()))?;
+ }
+ Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)}))
+}
+
+/// File › Export › Quick Export as <format>: the format, quality, metadata, colour space and
+/// location from Export Preferences. `path` overrides the location ("ask" needs one).
+fn quick_export(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "file.export.quickExport";
+ let prefs = s.prefs().export.clone();
+ let fmt = serde_json::to_value(prefs.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into());
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) {
+ Some(v) => v.to_string(),
+ None => {
+ let same = serde_json::to_value(prefs.quick_export_location).ok().and_then(|v| v.as_str().map(str::to_string)).is_some_and(|v| v == "sameFolder");
+ match (&d.path, same) {
+ (Some(dp), true) => {
+ let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();
+ join(&dir, &format!("{}.{fmt}", stem(dp)))
+ }
+ _ => return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")),
+ }
+ }
+ };
+ let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
+ let mut q = json!({"metadata": if metadata == "all" { "all" } else if metadata == "none" { "none" } else { "copyright" }, "convertToSrgb": prefs.convert_to_srgb, "transparency": true});
+ let o = q.as_object_mut().unwrap_or_else(|| unreachable!());
+ match fmt.as_str() {
+ "jpg" => {
+ o.insert("format".into(), json!("jpeg"));
+ o.insert("quality".into(), json!(prefs.jpeg_quality.min(100)));
+ }
+ "gif" => {
+ o.insert("format".into(), json!("gif"));
+ }
+ "webp" => {
+ // WebP has no legacy Save for Web optimiser: write it through the regular exporter.
+ let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?;
+ let warnings = crate::file_cmds::save_doc(&wdoc, &path, None)?;
+ crate::automate_cmds::fire_event(s, "export");
+ return Ok(json!({"path": path, "format": fmt, "warnings": warnings}));
+ }
+ _ => {
+ o.insert("format".into(), json!("png24"));
+ }
+ }
+ let st = WebSettings::from_params(&q, cmd)?;
+ let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?;
+ let buf = photocraft_compose::flatten(&wdoc);
+ let xmp = web_xmp(&doc, st.metadata);
+ let opt = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, wdoc.icc_profile.as_deref().map(|v| v.as_slice()), xmp.as_deref(), wdoc.resolution_dpi, false)?;
+ write_file(&path, &opt.bytes)?;
+ crate::automate_cmds::fire_event(s, "export");
+ Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len()}))
+}
+
+// ---------- Generate › Image Assets ----------
+
+/// One asset requested by a layer name.
+#[derive(Clone, Debug, PartialEq)]
+pub struct AssetSpec {
+ /// Relative output path (folders allowed), extension included.
+ pub file: String,
+ /// png8 | png24 | png32 | jpg | gif | webp
+ pub format: String,
+ /// JPEG quality 1..=100.
+ pub quality: Option<u8>,
+ /// Uniform scale (1.0 = 100 %).
+ pub scale: Option<f64>,
+ /// Target width / height in px (`?` = keep aspect).
+ pub width: Option<f64>,
+ pub height: Option<f64>,
+}
+
+/// A `default` layer variant: size plus a folder (`low/`) or name suffix (`@2x`).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct AssetDefault {
+ pub scale: Option<f64>,
+ pub width: Option<f64>,
+ pub height: Option<f64>,
+ pub folder: String,
+ pub suffix: String,
+}
+
+fn unit_px(tok: &str, dpi: f64) -> Option<Option<f64>> {
+ if tok == "?" {
+ return Some(None);
+ }
+ let (num, k) = if let Some(n) = tok.strip_suffix("px") {
+ (n, 1.0)
+ } else if let Some(n) = tok.strip_suffix("in") {
+ (n, dpi)
+ } else if let Some(n) = tok.strip_suffix("cm") {
+ (n, dpi / 2.54)
+ } else if let Some(n) = tok.strip_suffix("mm") {
+ (n, dpi / 25.4)
+ } else {
+ (tok, 1.0)
+ };
+ num.trim().parse::<f64>().ok().filter(|v| *v > 0.0).map(|v| Some(v * k))
+}
+
+/// `200%` or `WxH` (units px/in/cm/mm, `?` wildcard) at the start of `item`; returns the size and
+/// the rest.
+fn parse_size(item: &str, dpi: f64) -> (Option<f64>, Option<f64>, Option<f64>, &str) {
+ let item = item.trim();
+ let (first, rest) = item.split_once(char::is_whitespace).map_or((item, ""), |(a, b)| (a, b.trim()));
+ if let Some(pc) = first.strip_suffix('%').and_then(|n| n.parse::<f64>().ok()).filter(|v| *v > 0.0) {
+ return (Some(pc / 100.0), None, None, rest);
+ }
+ // "100x50", "2in x 1in", "?x100"
+ if let Some((w, h)) = first.split_once(['x', 'X']).filter(|(w, h)| !w.is_empty() && !h.is_empty())
+ && let (Some(w), Some(h)) = (unit_px(w, dpi), unit_px(h, dpi))
+ {
+ return (None, w, h, rest);
+ }
+ // Spaced form "2in x 1in name.png": three tokens.
+ let toks: Vec<&str> = item.split_whitespace().collect();
+ if toks.len() >= 4
+ && toks[1].eq_ignore_ascii_case("x")
+ && let (Some(w), Some(h)) = (unit_px(toks[0], dpi), unit_px(toks[2], dpi))
+ {
+ let pos = item.find(toks[3]).unwrap_or(item.len());
+ return (None, w, h, &item[pos..]);
+ }
+ (None, None, None, item)
+}
+
+/// Parses a layer name into its asset specs (empty when it names no asset).
+pub fn parse_asset_name(name: &str, dpi: f64) -> Vec<AssetSpec> {
+ let mut out = Vec::new();
+ for item in name.split([',', '+']) {
+ let (scale, width, height, rest) = parse_size(item, dpi);
+ let file = rest.trim();
+ let Some((stem_part, ext)) = file.rsplit_once('.') else { continue };
+ if stem_part.is_empty() {
+ continue;
+ }
+ let ext_l = ext.to_ascii_lowercase();
+ let (format, quality, out_ext) = if let Some(q) = ext_l.strip_prefix("jpeg").or_else(|| ext_l.strip_prefix("jpg")) {
+ let q = q.trim();
+ let quality = if q.is_empty() {
+ None
+ } else if let Some(pc) = q.strip_suffix('%') {
+ pc.parse::<u32>().ok().map(|v| v.clamp(1, 100) as u8)
+ } else {
+ // 1–10 scale.
+ q.parse::<u32>().ok().map(|v| (v.clamp(1, 10) * 10) as u8)
+ };
+ if !q.is_empty() && quality.is_none() {
+ continue;
+ }
+ ("jpg".to_string(), quality, if ext_l.starts_with("jpeg") { "jpeg" } else { "jpg" })
+ } else {
+ match ext_l.as_str() {
+ "png" | "png32" => ("png32".to_string(), None, "png"),
+ "png24" => ("png24".to_string(), None, "png"),
+ "png8" => ("png8".to_string(), None, "png"),
+ "gif" => ("gif".to_string(), None, "gif"),
+ "webp" => ("webp".to_string(), None, "webp"),
+ _ => continue,
+ }
+ };
+ out.push(AssetSpec { file: format!("{stem_part}.{out_ext}"), format, quality, scale, width, height });
+ }
+ out
+}
+
+/// Parses a `default …` layer name into its variants.
+pub fn parse_defaults(name: &str, dpi: f64) -> Option<Vec<AssetDefault>> {
+ let rest = name.trim().strip_prefix("default")?;
+ if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
+ return None;
+ }
+ let mut v = Vec::new();
+ for item in rest.split([',', '+']) {
+ let (scale, width, height, tail) = parse_size(item, dpi);
+ let tail = tail.trim();
+ let (folder, suffix) = match tail.rfind('/') {
+ Some(i) => (tail[..=i].to_string(), tail[i + 1..].to_string()),
+ None => (String::new(), tail.to_string()),
+ };
+ if scale.is_none() && width.is_none() && height.is_none() && folder.is_empty() && suffix.is_empty() {
+ continue;
+ }
+ v.push(AssetDefault { scale, width, height, folder, suffix });
+ }
+ Some(v)
+}
+
+fn asset_settings(spec: &AssetSpec) -> WebSettings {
+ let base = WebSettings { transparency: true, matte: None, metadata: WebMetadata::None, ..WebSettings::default() };
+ match spec.format.as_str() {
+ "jpg" => WebSettings { format: WebFormat::Jpeg, quality: spec.quality.unwrap_or(90), matte: Some([1.0, 1.0, 1.0]), ..base },
+ "png8" => WebSettings { format: WebFormat::Png8, dither: Dither::None, ..base },
+ "png24" => WebSettings { format: WebFormat::Png24, transparency: false, matte: Some([1.0, 1.0, 1.0]), ..base },
+ "gif" => WebSettings { format: WebFormat::Gif, dither: Dither::None, ..base },
+ _ => WebSettings { format: WebFormat::Png24, ..base },
+ }
+}
+
+/// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors).
+pub fn generate_assets(doc: &Document, dir: &str) -> (Vec<String>, Vec<Value>) {
+ let dpi = f64::from(doc.resolution_dpi.max(1.0));
+ let mut defaults: Option<Vec<AssetDefault>> = None;
+ let mut jobs: Vec<(LayerId, AssetSpec)> = Vec::new();
+ for (_, _, l) in doc.walk() {
+ if let Some(d) = parse_defaults(&l.name, dpi) {
+ defaults = Some(d);
+ continue;
+ }
+ if matches!(l.content, LayerContent::Adjustment(_)) {
+ continue;
+ }
+ for spec in parse_asset_name(&l.name, dpi) {
+ jobs.push((l.id, spec));
+ }
+ }
+ let variants: Vec<AssetDefault> = match defaults {
+ Some(d) if !d.is_empty() => d,
+ _ => vec![AssetDefault::default()],
+ };
+ let mut files = Vec::new();
+ let mut errors = Vec::new();
+ for (id, spec) in &jobs {
+ for v in &variants {
+ let r = (|| -> Result<String> {
+ let mut one = crate::layer_menu_cmds::layer_document(doc, *id)?;
+ one.metadata = Default::default();
+ let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height));
+ // The layer's own size spec wins; default variants scale on top of it.
+ let mut k = spec.scale.unwrap_or(1.0);
+ let (mut tw, mut th) = (w0 * k, h0 * k);
+ match (spec.width, spec.height) {
+ (Some(w), Some(h)) => (tw, th) = (w, h),
+ (Some(w), None) => (tw, th) = (w, h0 * w / w0),
+ (None, Some(h)) => (tw, th) = (w0 * h / h0, h),
+ _ => {}
+ }
+ k = v.scale.unwrap_or(1.0);
+ tw *= k;
+ th *= k;
+ match (v.width, v.height) {
+ (Some(w), Some(h)) => (tw, th) = (w, h),
+ (Some(w), None) => (tw, th) = (w, th * w / tw),
+ (None, Some(h)) => (tw, th) = (tw * h / th, h),
+ _ => {}
+ }
+ let st = asset_settings(spec);
+ let p = json!({"width": tw.round().max(1.0), "height": th.round().max(1.0)});
+ let (wdoc, _, _) = web_document(&one, &p, &WebSettings { convert_to_srgb: true, ..st.clone() })?;
+ let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png"));
+ let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix);
+ let out = join(dir, &rel);
+ if spec.format == "webp" {
+ crate::file_cmds::save_doc(&wdoc, &out, None)?;
+ return Ok(out);
+ }
+ let buf = photocraft_compose::flatten(&wdoc);
+ let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, wdoc.resolution_dpi, false)?;
+ write_file(&out, &o.bytes)?;
+ Ok(out)
+ })();
+ match r {
+ Ok(f) => files.push(f),
+ Err(e) => errors.push(json!({"asset": spec.file, "error": e.to_string()})),
+ }
+ }
+ }
+ (files, errors)
+}
+
+/// `<document folder>/<document name>-assets`.
+pub fn assets_dir(doc_path: &str) -> String {
+ let p = std::path::Path::new(doc_path);
+ let dir = p.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();
+ join(&dir, &format!("{}-assets", stem(doc_path)))
+}
+
+fn image_assets(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let id: DocId = d.doc.id;
+ let was = s.file_menu.image_assets.contains(&id);
+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(!was);
+ if on {
+ if !was {
+ s.file_menu.image_assets.push(id);
+ }
+ } else {
+ s.file_menu.image_assets.retain(|x| *x != id);
+ }
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let dir = p.get("dir").and_then(Value::as_str).map(str::to_string).or_else(|| d.path.as_deref().map(assets_dir));
+ if !on {
+ return Ok(json!({"enabled": false}));
+ }
+ match dir {
+ Some(dir) if !cfg!(target_arch = "wasm32") => {
+ let (files, errors) = generate_assets(&d.doc, &dir);
+ Ok(json!({"enabled": true, "dir": dir, "files": files, "errors": errors}))
+ }
+ _ => Ok(json!({"enabled": true, "dir": null, "files": [], "note": "assets are written when the document is saved"})),
+ }
+}
+
+/// After a save: regenerate the document's image assets when Generate › Image Assets is on.
+pub fn on_saved(s: &Session, index: usize) -> Option<Value> {
+ let d = s.documents().get(index)?;
+ if !s.file_menu.image_assets.contains(&d.doc.id) || cfg!(target_arch = "wasm32") {
+ return None;
+ }
+ let dir = assets_dir(d.path.as_deref()?);
+ let (files, errors) = generate_assets(&d.doc, &dir);
+ Some(json!({"dir": dir, "files": files, "errors": errors}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ macro_rules! spec {
+ ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => {
+ CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }
+ };
+ }
+ fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+ }
+ vec![
+ spec!(
+ "file.export.saveForWebLegacy",
+ "Save for Web (Legacy)…",
+ &["File", "Export"],
+ Some("Cmd+Alt+Shift+S"),
+ r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="#ffffff","interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|all"="copyright","convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"html":bool=false,"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors} estimate; else {files, html, bytes}"##,
+ has_doc,
+ save_for_web
+ ),
+ spec!("file.export.exportPreferences", "Export Preferences…", &["File", "Export"], None, r##"{"quickExportFormat":"png|jpg|gif|webp"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##, |_| Ok(()), export_preferences),
+ spec!("file.export.quickExport", "Quick Export", &[], None, r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes}"##, native_doc, quick_export),
+ spec!("file.generate.imageAssets", "Image Assets", &["File", "Generate"], None, r##"{"on":bool? (default: toggle),"dir":folder? (default <document>-assets next to the file)} → {enabled, files, errors}; layers named like "foo.png", "200% [email protected]", "48x48 icons/a.png8", "photo.jpg80%" are exported, now and after each save"##, has_doc, image_assets),
+ ]
+}
+
+#[cfg(test)]
+#[path = "web_cmds/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs
new file mode 100644
index 000000000..a33e7a508
--- /dev/null
+++ b/crates/engine/src/web_cmds/tests.rs
@@ -0,0 +1,219 @@
+use super::*;
+use photocraft_doc::{Layer, LayerContent};
+
+fn tmp(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("photocraft-web-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d.to_string_lossy().into_owned()
+}
+
+/// A 64×48 document: white background, a red square with soft (half-transparent) edges on a
+/// transparent layer, and a gradient band.
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth, "name": "web.psd", "background": "transparent"})).unwrap();
+ s.edit("paint", |doc, active| {
+ let fmt = doc.pixel_format();
+ let mut l = Layer::raster("Logo", fmt);
+ let surf = l.surface_mut().unwrap();
+ surf.fill_rect(Rect::new(8, 8, 32, 32), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
+ surf.fill_rect(Rect::new(32, 8, 34, 32), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 0.4]));
+ for x in 0..64 {
+ surf.fill_rect(Rect::new(x, 36, x + 1, 48), &photocraft_raster::from_rgba(&fmt, [x as f32 / 63.0, 0.5, 1.0 - x as f32 / 63.0, 1.0]));
+ }
+ let id = doc.insert_above(None, l);
+ *active = Some(id);
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+fn decode(path: &str) -> photocraft_codecs::Image {
+ photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap()
+}
+
+#[test]
+fn estimates_every_format_at_every_depth() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let mut sizes = Vec::new();
+ for f in ["gif", "png8", "png24", "jpeg", "wbmp"] {
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": f, "colors": 16})).unwrap();
+ assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(64), Some(48)), "{f}");
+ assert!(r["bytes"].as_u64().unwrap() > 20, "{f}");
+ if f == "gif" || f == "png8" {
+ assert!(r["colors"].as_u64().unwrap() <= 16);
+ }
+ sizes.push(r["bytes"].as_u64().unwrap());
+ }
+ assert_eq!(sizes[4], 4 + 8 * 48, "WBMP: header plus 1 bit per pixel");
+ }
+ let mut s = session(8);
+ assert!(s.execute("file.export.saveForWebLegacy", json!({"format": "tiff"})).is_err());
+ let r = s.execute("file.export.saveForWebLegacy", json!({"preset": "JPEG Low", "percent": 50})).unwrap();
+ assert_eq!(r["format"], "jpg");
+ assert_eq!(r["width"], 32);
+}
+
+#[test]
+fn gif_and_png8_keep_transparency_and_palette() {
+ let dir = tmp("gif");
+ let mut s = session(8);
+ let gif = format!("{dir}/a.gif");
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "gif", "colors": 8, "dither": "none", "path": gif})).unwrap();
+ assert_eq!(r["files"][0], json!(gif));
+ let img = decode(&gif).convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8);
+ let px = |x: usize, y: usize| img.data()[(y * 64 + x) * 4..(y * 64 + x) * 4 + 4].to_vec();
+ assert_eq!(px(0, 0)[3], 0, "transparent background");
+ assert_eq!(px(16, 16), vec![255, 0, 0, 255]);
+ // The 40 % edge is under ½: transparent, as Photoshop's hard GIF transparency.
+ assert_eq!(px(33, 16)[3], 0);
+ let mut colors: Vec<Vec<u8>> = (0..64 * 48).map(|i| img.data()[i * 4..i * 4 + 4].to_vec()).filter(|p| p[3] > 0).collect();
+ colors.sort();
+ colors.dedup();
+ assert!(colors.len() <= 7, "8 colours including the transparent one, got {}", colors.len());
+ // Transparency off: everything over the matte.
+ let png8 = format!("{dir}/a.png");
+ s.execute("file.export.saveForWebLegacy", json!({"format": "png8", "transparency": false, "matte": "#00ff00", "path": png8})).unwrap();
+ let img = decode(&png8).convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8);
+ assert_eq!(&img.data()[..4], &[0, 255, 0, 255]);
+}
+
+#[test]
+fn jpeg_quality_progressive_and_metadata() {
+ let dir = tmp("jpeg");
+ let mut s = session(16);
+ s.execute("file.fileInfo", json!({"copyright": "© Example", "author": "A. Person", "description": "secret notes"})).unwrap();
+ let lo = format!("{dir}/lo.jpg");
+ let hi = format!("{dir}/hi.jpg");
+ s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "quality": 10, "path": lo, "metadata": "none"})).unwrap();
+ s.execute("file.export.saveForWebLegacy", json!({"format": "jpeg", "quality": 95, "progressive": true, "path": hi, "metadata": "copyright"})).unwrap();
+ let (a, b) = (std::fs::read(&lo).unwrap(), std::fs::read(&hi).unwrap());
+ assert!(a.len() < b.len());
+ assert!(b.windows(2).any(|w| w == [0xFF, 0xC2]), "progressive");
+ let xmp = decode(&hi).meta.xmp.unwrap_or_default();
+ assert!(xmp.contains("Example"), "copyright kept");
+ assert!(!xmp.contains("secret"), "description dropped");
+ assert!(decode(&lo).meta.xmp.is_none());
+}
+
+#[test]
+fn slices_export_with_html_table() {
+ let dir = tmp("slices");
+ let mut s = session(8);
+ s.execute("slice.new", json!({"rect": [8, 8, 24, 24], "name": "logo", "url": "https://example.org/", "alt": "Logo"})).unwrap();
+ s.execute("slice.new", json!({"rect": [40, 0, 24, 20], "kind": "noImage", "cellText": "Hello & bye"})).unwrap();
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true})).unwrap();
+ let files: Vec<String> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
+ let n = photocraft_doc::slices::resolve(&s.active().unwrap().doc).len();
+ assert_eq!(files.len(), n - 1, "every slice but the no-image one");
+ let logo = files.iter().find(|f| f.ends_with("images/logo.png")).unwrap();
+ assert_eq!(decode(logo).dimensions(), (24, 24));
+ let html = std::fs::read_to_string(r["html"].as_str().unwrap()).unwrap();
+ assert!(html.contains("<a href=\"https://example.org/\">"));
+ assert!(html.contains("alt=\"Logo\""));
+ assert!(html.contains("Hello &amp; bye"));
+ assert!(html.contains("images/spacer.gif"));
+ assert!(std::path::Path::new(&format!("{dir}/images/spacer.gif")).is_file());
+ // Total area of the exported slices plus the text cell is the canvas.
+ let area: u64 = files.iter().map(|f| {
+ let (w, h) = decode(f).dimensions();
+ u64::from(w) * u64::from(h)
+ }).sum();
+ assert_eq!(area + 24 * 20, 64 * 48);
+ // Scaled export scales slices.
+ let dir2 = tmp("slices2");
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "gif", "dir": dir2, "percent": 50, "slices": "user"})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), 1);
+ assert_eq!(decode(r["files"][0].as_str().unwrap()).dimensions(), (12, 12));
+}
+
+#[test]
+fn export_preferences_drive_quick_export() {
+ let dir = tmp("quick");
+ let mut s = session(8);
+ let r = s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg", "jpegQuality": 40, "quickExportLocation": "sameFolder"})).unwrap();
+ assert_eq!(r["values"]["quickExportFormat"], "jpg");
+ assert!(s.execute("file.export.exportPreferences", json!({"quickExportFormat": "bmp"})).is_err());
+ // Unsaved document: a path is needed.
+ assert!(s.execute("file.export.quickExport", json!({})).is_err());
+ s.active_mut().unwrap().path = Some(format!("{dir}/web.psd"));
+ let r = s.execute("file.export.quickExport", json!({})).unwrap();
+ assert_eq!(r["path"], json!(format!("{dir}/web.jpg")));
+ assert_eq!(decode(&format!("{dir}/web.jpg")).dimensions(), (64, 48));
+ s.execute("file.export.exportPreferences", json!({"quickExportFormat": "gif"})).unwrap();
+ let r = s.execute("file.export.quickExport", json!({"path": format!("{dir}/x.gif")})).unwrap();
+ assert_eq!(r["format"], "gif");
+ assert!(std::fs::read(format!("{dir}/x.gif")).unwrap().starts_with(b"GIF89a"));
+ s.execute("prefs.reset", json!({"path": "export"})).unwrap();
+}
+
+#[test]
+fn generator_naming_grammar() {
+ let a = parse_asset_name("200% [email protected], 48x48 icons/bar.png8 + photo.jpg8", 72.0);
+ assert_eq!(a.len(), 3);
+ assert_eq!((a[0].file.as_str(), a[0].format.as_str(), a[0].scale), ("[email protected]", "png32", Some(2.0)));
+ assert_eq!((a[1].file.as_str(), a[1].format.as_str(), a[1].width, a[1].height), ("icons/bar.png", "png8", Some(48.0), Some(48.0)));
+ assert_eq!((a[2].file.as_str(), a[2].quality), ("photo.jpg", Some(80)));
+ let b = parse_asset_name("?x100 thumb.jpg50%", 72.0);
+ assert_eq!((b[0].width, b[0].height, b[0].quality), (None, Some(100.0), Some(50)));
+ let c = parse_asset_name("1in x 2cm label.gif", 300.0);
+ assert_eq!(c[0].width, Some(300.0));
+ assert!((c[0].height.unwrap() - 236.22).abs() < 0.01);
+ assert!(parse_asset_name("Layer 1", 72.0).is_empty());
+ assert!(parse_asset_name("notes.txt", 72.0).is_empty());
+ assert!(parse_asset_name("x.jpgq", 72.0).is_empty());
+ let d = parse_defaults("default 50% low/ + 200% @2x", 72.0).unwrap();
+ assert_eq!(d, vec![AssetDefault { scale: Some(0.5), folder: "low/".into(), ..Default::default() }, AssetDefault { scale: Some(2.0), suffix: "@2x".into(), ..Default::default() }]);
+ assert!(parse_defaults("defaults are nice", 72.0).is_none());
+}
+
+#[test]
+fn image_assets_are_generated_now_and_on_save() {
+ let dir = tmp("assets");
+ let mut s = session(8);
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.renameLayer", json!({"layer": id.0, "name": "logo.png, 50% small/logo.gif, logo.jpg80%"})).unwrap();
+ let r = s.execute("file.generate.imageAssets", json!({"dir": dir})).unwrap();
+ assert_eq!(r["enabled"], true);
+ assert_eq!(r["files"].as_array().unwrap().len(), 3, "{r}");
+ // Trimmed to the layer's pixels (x 0..64, y 8..48).
+ assert_eq!(decode(&format!("{dir}/logo.png")).dimensions(), (64, 40));
+ assert_eq!(decode(&format!("{dir}/small/logo.gif")).dimensions(), (32, 20));
+ assert_eq!(decode(&format!("{dir}/logo.jpg")).dimensions(), (64, 40));
+ // On save: written to <name>-assets next to the file.
+ let saved = format!("{dir}/doc.psd");
+ s.active_mut().unwrap().path = Some(saved.clone());
+ let r = crate::automate_cmds::document_saved(&mut s, 0).unwrap();
+ assert_eq!(r["dir"], json!(format!("{dir}/doc-assets")));
+ assert!(std::path::Path::new(&format!("{dir}/doc-assets/logo.png")).is_file());
+ // Off: nothing on save.
+ assert_eq!(s.execute("file.generate.imageAssets", json!({})).unwrap()["enabled"], false);
+ assert!(crate::automate_cmds::document_saved(&mut s, 0).is_none());
+ // A default layer adds variants.
+ let s2 = session(8);
+ let doc = s2.active().unwrap().doc.clone();
+ let mut d = (*doc).clone();
+ d.layers.push(Layer::new("default 200% @2x", LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None })));
+ let lid = d.layers[1].id;
+ d.layer_mut(lid).unwrap().name = "icon.png".into();
+ let (files, errors) = generate_assets(&d, &dir);
+ assert!(errors.is_empty(), "{errors:?}");
+ assert_eq!(files, vec![format!("{dir}/[email protected]")]);
+ assert_eq!(decode(&files[0]).dimensions(), (128, 80));
+}
+
+#[test]
+fn web_settings_from_params() {
+ let st = WebSettings::from_params(&json!({"preset": "GIF 32 No Dither", "matte": "none", "webSnap": 50}), "x").unwrap();
+ assert_eq!((st.format, st.colors, st.dither, st.matte), (WebFormat::Gif, 32, Dither::None, None));
+ assert!((st.web_snap - 0.5).abs() < 1e-6);
+ assert!(WebSettings::from_params(&json!({"preset": "Nope"}), "x").is_err());
+ assert!(WebSettings::from_params(&json!({"palette": "weird"}), "x").is_err());
+ for p in PRESETS {
+ let st = preset_settings(p).unwrap();
+ assert_eq!(WebSettings::from_params(&st.to_params(), "x").unwrap(), st, "{p} round-trips through params");
+ }
+}
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index ca420ce5c..86289cc9b 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -201,6 +201,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {
surface: surface_m(&fc.surface, sink),
}),
link_group: l.link_group,
+ excluded_channels: l.excluded_channels,
}
}
@@ -275,6 +276,10 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {
layer_comps: d.layer_comps.iter().map(|c| comp_m(c, sink)).collect(),
last_applied_comp: d.last_applied_comp,
last_document_state: d.last_document_state.as_ref().map(|c| comp_m(c, sink)),
+ measurement: d.measurement.clone(),
+ notes: d.notes.clone(),
+ text_styles: d.text_styles.clone(),
+ slices: d.slices.clone(),
}
}
@@ -544,6 +549,7 @@ impl Loader<'_> {
psd_id: m.psd_id,
fill_cache,
link_group: m.link_group,
+ excluded_channels: m.excluded_channels,
})
}
@@ -591,6 +597,17 @@ impl Loader<'_> {
}
let layer_comps = m.layer_comps.iter().map(|c| self.comp(c)).collect::<Result<Vec<_>>>()?;
let last_document_state = m.last_document_state.as_ref().map(|c| self.comp(c)).transpose()?;
+ // Layer-based slices follow their layer through id remapping; a dangling one becomes a
+ // user slice (its rect stays where it was).
+ let mut slices = m.slices.clone();
+ for sl in &mut slices.list {
+ if let Some(l) = sl.layer {
+ sl.layer = self.id_map.get(&l.0).copied();
+ if sl.layer.is_none() && sl.origin == photocraft_doc::SliceOrigin::Layer {
+ sl.origin = photocraft_doc::SliceOrigin::User;
+ }
+ }
+ }
let id = if self.preserve_ids {
self.max_id = self.max_id.max(m.id);
DocId(m.id)
@@ -621,6 +638,10 @@ impl Loader<'_> {
layer_comps,
last_applied_comp: m.last_applied_comp,
last_document_state,
+ measurement: m.measurement.clone(),
+ notes: m.notes.clone(),
+ text_styles: m.text_styles.clone(),
+ slices,
})
}
diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs
index 40e85f5d2..c2d3b0760 100644
--- a/crates/format/src/manifest.rs
+++ b/crates/format/src/manifest.rs
@@ -76,6 +76,18 @@ pub struct DocM {
pub last_applied_comp: Option<u32>,
#[serde(default)]
pub last_document_state: Option<LayerCompM>,
+ /// Image › Analysis: measurement scale, count groups, ruler.
+ #[serde(default)]
+ pub measurement: photocraft_doc::Measurement,
+ /// Note tool annotations.
+ #[serde(default)]
+ pub notes: Vec<photocraft_doc::Note>,
+ /// Character and paragraph styles.
+ #[serde(default)]
+ pub text_styles: photocraft_doc::TextStyles,
+ /// Web slices (user and layer-based; layer ids are remapped on load).
+ #[serde(default, skip_serializing_if = "photocraft_doc::Slices::is_empty")]
+ pub slices: photocraft_doc::Slices,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -191,6 +203,9 @@ pub struct LayerM {
/// Link Layers group (`None` = not linked).
#[serde(default)]
pub link_group: Option<u64>,
+ /// Advanced Blending channels left out (bit per colour channel; 0 = all blend).
+ #[serde(default, skip_serializing_if = "is_zero_u32")]
+ pub excluded_channels: u32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -322,3 +337,7 @@ mod channel_tests {
assert_eq!(c.indicates, photocraft_doc::ColorIndicates::MaskedAreas);
}
}
+
+fn is_zero_u32(v: &u32) -> bool {
+ *v == 0
+}
diff --git a/crates/format/tests/analysis.rs b/crates/format/tests/analysis.rs
new file mode 100644
index 000000000..d4e0bffd3
--- /dev/null
+++ b/crates/format/tests/analysis.rs
@@ -0,0 +1,25 @@
+//! Image › Analysis data and notes survive a `.pcraft` round trip; old manifests default them.
+
+use photocraft_color::{Color, ColorMode, SampleType};
+use photocraft_doc::{CountGroup, Document, MeasurementScale, Note, Ruler, Size};
+use photocraft_format::*;
+
+#[test]
+fn measurement_and_notes_roundtrip_and_default_when_absent() {
+ let mut doc = Document::new("a", Size::new(40, 30), ColorMode::Rgb, SampleType::U16);
+ doc.measurement.scale = MeasurementScale { pixel_length: 72.0, logical_length: 1.0, units: "inches".into() };
+ doc.measurement.count_groups = vec![CountGroup { name: "Cells".into(), color: Color::rgb(0.0, 0.5, 1.0), marker_size: 3, label_size: 12, visible: true, points: vec![[1.0, 2.0], [5.5, 6.5]] }];
+ doc.measurement.ruler = Some(Ruler { start: [1.0, 1.0], end: [30.0, 20.0], protractor: Some([1.0, 25.0]) });
+ doc.notes = vec![Note { author: "A".into(), text: "Fix the sky\nplease".into(), position: [10.0, 12.0], popup: [10.0, 30.0, 200.0, 150.0], open: true, ..Default::default() }];
+ let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap();
+ let back = load_from_bytes(&bytes).unwrap();
+ assert_eq!(back.measurement, doc.measurement);
+ assert_eq!(back.notes, doc.notes);
+
+ let m = read_manifest(&bytes).unwrap();
+ let mut v = serde_json::to_value(&m.document).unwrap();
+ v.as_object_mut().unwrap().remove("measurement");
+ v.as_object_mut().unwrap().remove("notes");
+ let old: photocraft_format::manifest::DocM = serde_json::from_value(v).unwrap();
+ assert!(old.measurement.is_empty() && old.notes.is_empty());
+}
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index 5650dce09..a0731620f 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -44,6 +44,10 @@ const F_GATE: u32 = 256u; // effect paint: coverage only inside the layer
const F_REL: u32 = 512u; // effect paint: coverage relative to the layer's alpha
const F_STROKE_OUT: u32 = 1024u; // effect paint: outside stroke band
const F_FIRST: u32 = 2048u; // outside strokes: nothing accumulated yet
+const F_CHANNELS: u32 = 4096u; // lerp: per-channel weights in p0 (channel restrictions)
+const F_ADD_DIFF: u32 = 16384u; // lerp: A + (B - C) premultiplied (clips on pass-through groups)
+const F_TEXT_GAMMA: u32 = 8192u; // blend / atop / fx merge: type layer, mix coverage at gamma 1.45
+const TEXT_GAMMA: f32 = 1.45;
@group(0) @binding(0) var<uniform> chunk: Chunk;
@group(0) @binding(1) var<uniform> op: Op;
@@ -104,13 +108,16 @@ fn gray(c: vec3<f32>) -> f32 { return 0.299 * c.r + 0.587 * c.g + 0.114 * c.b; }
const M_NORMAL: i32 = 1;
const M_DISSOLVE: i32 = 2;
+// Backdrop extremes within EDGE of 0 / 1 count as exact (psblend::EDGE): composited values that
+// should be 1 come out a rounding step below it, which would flip Color Burn's corner case.
+const EDGE: f32 = 1e-4;
fn color_burn(cb: f32, cs: f32) -> f32 {
- if (cb >= 1.0) { return 1.0; }
+ if (cb >= 1.0 - EDGE) { return 1.0; }
if (cs <= 0.0) { return 0.0; }
return 1.0 - min((1.0 - cb) / cs, 1.0);
}
fn color_dodge(cb: f32, cs: f32) -> f32 {
- if (cb <= 0.0) { return 0.0; }
+ if (cb <= EDGE) { return 0.0; }
if (cs >= 1.0) { return 1.0; }
return min(cb / (1.0 - cs), 1.0);
}
@@ -133,11 +140,11 @@ fn vivid_light_ps(cb: f32, cs: f32) -> f32 {
}
fn vivid_light_generic(cb: f32, cs: f32) -> f32 {
if (cs <= 0.5) {
- if (cb >= 1.0) { return 1.0; }
+ if (cb >= 1.0 - EDGE) { return 1.0; }
if (cs <= 0.0) { return 0.0; }
return 1.0 - min((1.0 - cb) / (2.0 * cs), 1.0);
}
- if (cb <= 0.0) { return 0.0; }
+ if (cb <= EDGE) { return 0.0; }
if (cs >= 1.0) { return 1.0; }
return min(cb / (2.0 * (1.0 - cs)), 1.0);
}
@@ -226,6 +233,20 @@ fn composite(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32) -> vec4<f32> {
return vec4(rgb, ao);
}
+// `psblend::composite_gamma`: coverage mixed in a gamma space (type layers, gamma 1.45).
+fn composite_g(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32, gamma_on: bool) -> vec4<f32> {
+ if (!gamma_on) { return composite(mode, b, s, opacity); }
+ let ab = b.a;
+ let as_ = s.a * opacity;
+ if (as_ <= 0.0) { return b; }
+ let bl = blend_rgb(mode, b.rgb, s.rgb);
+ let ao = as_ + ab * (1.0 - as_);
+ if (ao <= 0.0) { return vec4(0.0); }
+ let g = TEXT_GAMMA;
+ let pw = (1.0 - as_) * ab * pow(max(b.rgb, vec3(0.0)), vec3(g)) + (1.0 - ab) * as_ * pow(max(s.rgb, vec3(0.0)), vec3(g)) + as_ * ab * pow(max(bl, vec3(0.0)), vec3(g));
+ return vec4(pow(pw / ao, vec3(1.0 / g)), ao);
+}
+
fn dissolve_noise(d: vec2<i32>) -> f32 {
var h = (bitcast<u32>(d.x) * 0x8da6b343u) ^ (bitcast<u32>(d.y) * 0xd8163841u) ^ 0x9e3779b9u;
h = h ^ (h >> 15u);
@@ -550,7 +571,7 @@ fn fs_blend(in: VOut) -> @location(0) vec4<f32> {
s.a = select(0.0, 1.0, dissolve_noise(doc_px(p)) < s.a * op.opacity);
return composite(M_NORMAL, b, s, 1.0);
}
- return composite(op.mode, b, s, op.opacity);
+ return composite_g(op.mode, b, s, op.opacity, (op.flags & F_TEXT_GAMMA) != 0u);
}
// composite_atop(base = A, src = B): blend as if the base were opaque, keep its alpha.
@@ -560,7 +581,7 @@ fn fs_atop(in: VOut) -> @location(0) vec4<f32> {
let base = textureLoad(tex_a, p, 0);
if (base.a <= 0.0) { return base; }
let s = textureLoad(tex_b, p, 0);
- let r = composite(op.mode, vec4(base.rgb, 1.0), s, op.opacity);
+ let r = composite_g(op.mode, vec4(base.rgb, 1.0), s, op.opacity, (op.flags & F_TEXT_GAMMA) != 0u);
return vec4(r.rgb, base.a);
}
@@ -592,6 +613,17 @@ fn fs_lerp(in: VOut) -> @location(0) vec4<f32> {
let p = local(in.pos);
let a = textureLoad(tex_a, p, 0);
let b = textureLoad(tex_b, p, 0);
+ if ((op.flags & F_CHANNELS) != 0u) {
+ return a + (b - a) * op.p0;
+ }
+ if ((op.flags & F_ADD_DIFF) != 0u) {
+ // compose: pass-through group + (with clipped − without), premultiplied.
+ let c = textureLoad(tex_c, p, 0);
+ var pm = vec4(a.rgb * a.a, a.a) + vec4(b.rgb * b.a, b.a) - vec4(c.rgb * c.a, c.a);
+ let al = clamp(pm.a, 0.0, 1.0);
+ if (al <= 0.0) { return vec4(0.0); }
+ return vec4(clamp(pm.rgb / al, vec3(0.0), vec3(1.0)), al);
+ }
let k = op.opacity * mask_value(doc_px(p));
return a + (b - a) * k;
}
@@ -761,7 +793,7 @@ fn fs_fxmerge(in: VOut) -> @location(0) vec4<f32> {
var w = textureLoad(tex_a, p, 0);
let l = textureLoad(tex_b, p, 0);
let c = textureLoad(tex_c, p, 0);
- if (l.a > 0.0) { w = composite(op.mode, w, l, 1.0); }
+ if (l.a > 0.0) { w = composite_g(op.mode, w, l, 1.0, (op.flags & F_TEXT_GAMMA) != 0u); }
let atop = (op.flags & F_ATOP) != 0u;
var before = c;
if (atop) { before = vec4(c.rgb, 1.0); }
@@ -851,8 +883,8 @@ fn fs_mfinish(in: VOut) -> @location(0) vec4<f32> {
return mout(v);
}
-// Bevel height profile from A = dist_inside, B = dist_outside: p0 = (style (0 outer, 1 emboss,
-// 2 inner), size); the smooth (quarter sine) rounding comes from LUT row 0.
+// Chiselled bevel height from A = dist_inside, B = dist_outside (`effects::bevel_chisel_h`):
+// p0 = (paint (0 outer, 1 both / emboss, 2 inner), size).
@fragment
fn fs_mbevelh(in: VOut) -> @location(0) vec4<f32> {
let p = local(in.pos);
@@ -871,7 +903,7 @@ fn fs_mbevelh(in: VOut) -> @location(0) vec4<f32> {
}
default: { h = clamp(din / size, 0.0, 1.0); }
}
- return mout(lut(0, h));
+ return mout(h);
}
// Bevel shading of the blurred height map A over shape S (`layer_tex`): p0 = light vector,
@@ -889,7 +921,8 @@ fn fs_mbevelshade(in: VOut) -> @location(0) vec4<f32> {
let s = textureLoad(layer_tex, p, 0).r;
var region = s;
if (op.p1.y > 0.5) {
- region = (1.0 - s) * select(0.0, 1.0, textureLoad(tex_a, p, 0).r > 0.0);
+ // Outside parts paint at full strength wherever the shape isn't opaque (edge pixels too).
+ region = select(0.0, 1.0, s < 1.0 - INSIDE_EPS && textureLoad(tex_a, p, 0).r > 0.0);
}
let k = shade - se;
var v = 0.0;
diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs
index 0a4525a85..3fa68d63c 100644
--- a/crates/gpu/src/fx.rs
+++ b/crates/gpu/src/fx.rs
@@ -24,7 +24,8 @@ use std::hash::{Hash, Hasher};
use std::sync::Arc;
use photocraft_compose::effects::FieldKind;
-use photocraft_doc::{BevelStyle, Contour, Effect, GlobalLight, GlowSource, GlowTechnique, Layer, LayerContent};
+use photocraft_compose::effects::BevelPaint;
+use photocraft_doc::{BevelTechnique, Contour, Effect, GlobalLight, GlowSource, GlowTechnique, Layer, LayerContent};
use photocraft_geom::{Rect, TileCoord};
use photocraft_raster::{Surface, Tile};
@@ -189,7 +190,14 @@ impl B {
self.push(stage(Kernel::MDilate, Some(src), Some(dist), [r, 0.0, 0.0, 0.0], 0))
}
fn blur(&mut self, src: In, size: f32) -> In {
- let Some((r, w)) = blur_kernel(size) else { return src };
+ let Some(k) = blur_kernel(size) else { return src };
+ self.conv(src, k)
+ }
+ /// Separable convolution with a symmetric kernel `(radius, weights)` (two `MBlur` passes).
+ fn conv(&mut self, src: In, (r, w): (i32, Vec<f32>)) -> In {
+ if r <= 0 {
+ return src;
+ }
let w = Arc::new(w);
let mut h = stage(Kernel::MBlur, Some(src), None, [0.0, r as f32, 0.0, 0.0], r);
h.lut = Some(w.clone());
@@ -199,7 +207,9 @@ impl B {
self.push(v)
}
fn finish(&mut self, a: In, b: Option<In>, invert: bool, contour: &Contour, times_shape: bool, out: usize) {
- let lut = contour_lut(contour);
+ self.finish_lut(a, b, invert, contour_lut(contour), times_shape, out);
+ }
+ fn finish_lut(&mut self, a: In, b: Option<In>, invert: bool, lut: Option<Vec<f32>>, times_shape: bool, out: usize) {
let flag = |v: bool| f32::from(u8::from(v));
let mut s = stage(Kernel::MFinish, Some(a), b, [flag(b.is_some()), flag(invert), flag(lut.is_some()), flag(times_shape)], 0);
s.lut = lut.map(Arc::new);
@@ -217,17 +227,14 @@ fn reach_for(w: f32) -> i32 {
w.clamp(0.0, photocraft_compose::effects::MAX_REACH).ceil() as i32 + 2
}
-/// `compose::effects::blur`'s kernel: (radius, normalised weights), or None below sigma 0.2.
+/// `compose::effects::blur`'s kernel (a tent of the effect size): (radius, normalised weights),
+/// or None when it is the identity.
pub(crate) fn blur_kernel(size: f32) -> Option<(i32, Vec<f32>)> {
- // compose::effects::sigma_for
- let sigma = size * 0.4;
- if sigma < 0.2 || !sigma.is_finite() {
+ if !size.is_finite() {
return None;
}
- let r = (sigma * 3.0).ceil() as i64;
- let kernel: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
- let sum: f32 = kernel.iter().sum();
- Some((r as i32, kernel.iter().map(|k| k / sum).collect()))
+ let k = photocraft_compose::effects::tent_kernel(size);
+ (k.0 > 0).then_some(k)
}
fn contour_lut(c: &Contour) -> Option<Vec<f32>> {
@@ -243,11 +250,6 @@ fn offset(angle: f32, distance: f32) -> (f32, f32) {
((-a.cos() * distance).round(), (a.sin() * distance).round())
}
-fn sine_lut() -> Arc<Vec<f32>> {
- static L: std::sync::OnceLock<Arc<Vec<f32>>> = std::sync::OnceLock::new();
- L.get_or_init(|| Arc::new((0..4096).map(|k| (k as f32 / 4095.0 * std::f32::consts::FRAC_PI_2).sin()).collect())).clone()
-}
-
/// The map program of one enabled effect (`build_maps`).
pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> MapProgram {
let mut b = B { stages: Vec::new(), fields: Vec::new() };
@@ -282,7 +284,7 @@ pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> Ma
let solid = g.size * g.spread;
let soft = (g.size - solid).max(1e-3);
let m = b.push(stage(Kernel::MGlow, Some(d), None, [solid, soft, f32::from(u8::from(center)), 0.0], 0));
- b.finish(m, None, false, &g.contour, inner, 0);
+ b.finish_lut(m, None, false, photocraft_compose::effects::glow_lut(g), inner, 0);
}
GlowTechnique::Softer => {
// Inner glows (edge, and centre as 1 - the edge result) spread 1 - alpha.
@@ -294,7 +296,7 @@ pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> Ma
m = b.dilate(src, d, r);
}
let m = b.blur(m, g.size * (1.0 - g.spread));
- b.finish(m, None, center, &g.contour, inner, 0);
+ b.finish_lut(m, None, center, photocraft_compose::effects::glow_lut(g), inner, 0);
}
}
1
@@ -303,40 +305,55 @@ pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> Ma
// satin_map
let (dx, dy) = offset(s.angle, s.distance);
let a = b.shift(In::Shape, dx, dy, 0.0, false);
- let a = b.blur(a, s.size);
+ let a = b.conv(a, photocraft_compose::effects::tent_kernel(s.size));
let c = b.shift(In::Shape, -dx, -dy, 0.0, false);
- let c = b.blur(c, s.size);
+ let c = b.conv(c, photocraft_compose::effects::tent_kernel(s.size));
b.finish(a, Some(c), s.invert, &s.contour, true, 0);
1
}
Effect::BevelEmboss(bv) => {
- // bevel_maps
+ // bevel_maps: height map (tent blur of the shape, or chiselled distance ramps), then
+ // highlight / shadow shading inside and / or outside the shape.
+ let g = photocraft_compose::effects::bevel_geom(bv);
let size = bv.size.max(1.0);
- let din = b.field(FieldKind::Inside, size);
- let dout = b.field(FieldKind::Outside, size);
- let style = match bv.style {
- BevelStyle::OuterBevel => 0.0,
- BevelStyle::Emboss | BevelStyle::PillowEmboss => 1.0,
- _ => 2.0,
+ let paint = |p: BevelPaint| match p {
+ BevelPaint::Outer => 0.0,
+ BevelPaint::Both => 1.0,
+ BevelPaint::Inner => 2.0,
};
- let mut h = stage(Kernel::MBevelH, Some(din), Some(dout), [style, size, 0.0, 0.0], 0);
- h.lut = Some(sine_lut());
- let h = b.push(h);
- let h = b.blur(h, bv.soften.max(1.0));
+ let mut h = if bv.technique == BevelTechnique::Smooth {
+ b.conv(In::Shape, photocraft_compose::effects::tent_kernel(g.width))
+ } else {
+ let din = b.field(FieldKind::Inside, size);
+ let dout = b.field(FieldKind::Outside, size);
+ let h = b.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint(g.paint), size, 0.0, 0.0], 0));
+ if g.chisel_soft > 0.0 { b.conv(h, photocraft_compose::effects::tent_kernel(g.chisel_soft)) } else { h }
+ };
+ if bv.soften >= 1.0 {
+ h = b.conv(h, photocraft_compose::effects::tent_kernel(bv.soften));
+ }
let (angle, altitude) = if bv.use_global_light { (light.angle, light.altitude) } else { (bv.angle, bv.altitude) };
let (sa, ca) = angle.to_radians().sin_cos();
let (se, ce) = altitude.to_radians().sin_cos();
- let depth = bv.depth * size * if bv.up { 1.0 } else { -1.0 };
let lut = contour_lut(&bv.gloss_contour).map(Arc::new);
- for (which, out) in [(0.0, 0), (1.0, 1)] {
- let mut s = stage(Kernel::MBevelShade, Some(h), None, [ca * ce, -sa * ce, se, se], 1);
- s.p1 = [depth, f32::from(u8::from(style == 0.0)), which, f32::from(u8::from(lut.is_some()))];
- s.lut = lut.clone();
- s.s = Some(In::Shape);
- s.out = Some(out);
- b.stages.push(s);
+ let passes: Vec<(f32, bool)> = match g.paint {
+ BevelPaint::Inner => vec![(g.depth, false)],
+ BevelPaint::Outer => vec![(g.depth, true)],
+ BevelPaint::Both => vec![(g.depth, false), (if g.pillow { -g.depth } else { g.depth }, true)],
+ };
+ let mut out = 0;
+ for (depth, outer) in &passes {
+ for which in [0.0, 1.0] {
+ let mut s = stage(Kernel::MBevelShade, Some(h), None, [ca * ce, -sa * ce, se, se], 1);
+ s.p1 = [*depth, f32::from(u8::from(*outer)), which, f32::from(u8::from(lut.is_some()))];
+ s.lut = lut.clone();
+ s.s = Some(In::Shape);
+ s.out = Some(out);
+ out += 1;
+ b.stages.push(s);
+ }
}
- 2
+ out
}
Effect::Stroke(st) => {
// composite_with_effects' stroke bands (maps 0 outside, 1 inside)
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index a0819a554..69d8786ed 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -17,10 +17,11 @@
//! each finished chunk is handed to a caller-supplied sink, e.g. to encode it straight into a
//! display texture — no readback.
//!
-//! Anything the planner can't express (vector masks, layers clipped to pass-through groups, stroked
-//! shapes with clipped layers, uncached pattern fills, artboards, documents or effect regions
-//! larger than the device's texture limit) returns [`Unsupported`]; callers fall back to the CPU
-//! compositor.
+//! Vector masks (rasterised once per mask state into a combined mask texture), layers clipped to
+//! pass-through groups, stroked shapes with clipped layers (fill and stroke split once per shape
+//! state), pattern fills and artboards are planned like everything else. What remains
+//! (Multichannel documents, documents or effect regions larger than the device's texture limit)
+//! returns [`Unsupported`]; callers fall back to the CPU compositor.
#![forbid(unsafe_code)]
pub mod bounds;
@@ -96,9 +97,9 @@ enum TexKind {
impl TexKind {
fn for_surface(role: Role, f: PixelFormat) -> Self {
match role {
- Role::Content if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct,
- Role::Content if f.sample == SampleType::U8 => TexKind::Rgba8,
- Role::Content => TexKind::Rgba16F,
+ Role::Content | Role::Stroke if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct,
+ Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8,
+ Role::Content | Role::Stroke => TexKind::Rgba16F,
Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct,
Role::Mask => TexKind::R32F,
}
@@ -498,11 +499,11 @@ impl Compositor {
let mut maps = Vec::with_capacity(plan.passes.len());
let mut patterns = Vec::with_capacity(plan.passes.len());
for p in &plan.passes {
- let tex = p.tex.and_then(|t| self.sync(device, queue, doc, t.layer, t.role, t.surface, tile_grid(canvas), stats)).map(|(k, r)| {
+ let tex = p.tex.as_ref().and_then(|t| self.sync(device, queue, doc, t.layer, t.role, t.surface.get(), tile_grid(canvas), stats)).map(|(k, r)| {
keys.push(k);
(keys.len() - 1, r)
});
- let mask = p.mask.and_then(|m| self.sync(device, queue, doc, m.layer, Role::Mask, m.surface, tile_grid(canvas), stats)).map(|(k, r)| {
+ let mask = p.mask.as_ref().and_then(|m| self.sync(device, queue, doc, m.layer, Role::Mask, m.surface.get(), tile_grid(canvas), stats)).map(|(k, r)| {
keys.push(k);
(keys.len() - 1, r)
});
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index a959a05f7..5f16a55d3 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -135,14 +135,16 @@ impl Kernel {
pub enum Role {
Content,
Mask,
+ /// A stroked shape's stroke alone (its fill uses `Content`).
+ Stroke,
}
/// A surface the pass needs on the GPU.
-#[derive(Clone, Copy, Debug)]
+#[derive(Clone, Debug)]
pub struct TexUse<'a> {
pub layer: LayerId,
pub role: Role,
- pub surface: &'a Surface,
+ pub surface: SurfaceRef<'a>,
}
/// An effect map sampled by a pass: map `map` of enabled effect `item` of `plan.fx[fx]`.
@@ -189,10 +191,27 @@ pub struct Pass<'a> {
pub clip: Option<Rect>,
}
-#[derive(Clone, Copy, Debug)]
+/// Pixels a pass samples: a surface of the document, or one derived from it on the CPU (a
+/// combined pixel × vector mask, a shape's fill or stroke alone).
+#[derive(Clone, Debug)]
+pub enum SurfaceRef<'a> {
+ Doc(&'a Surface),
+ Derived(std::sync::Arc<Surface>),
+}
+
+impl SurfaceRef<'_> {
+ pub fn get(&self) -> &Surface {
+ match self {
+ SurfaceRef::Doc(s) => s,
+ SurfaceRef::Derived(s) => s,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
pub struct MaskUse<'a> {
pub layer: LayerId,
- pub surface: &'a Surface,
+ pub surface: SurfaceRef<'a>,
pub density: f32,
pub default: f32,
}
@@ -262,16 +281,21 @@ pub struct DocCtx<'a> {
pub transfer: Transfer,
pub light: GlobalLight,
pub patterns: &'a [Pattern],
+ /// Colour mode (channel restrictions name its channels).
+ pub mode: photocraft_color::ColorMode,
}
impl<'a> DocCtx<'a> {
pub fn of(doc: &'a Document) -> Self {
- DocCtx { canvas: doc.bounds(), transfer: Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns }
+ DocCtx { canvas: doc.bounds(), transfer: Transfer::for_mode(doc.mode), light: doc.global_light, patterns: &doc.patterns, mode: doc.mode }
}
}
/// Build the pass list for `doc`.
pub fn plan(doc: &Document) -> Result<Plan<'_>, Unsupported> {
+ if doc.mode == photocraft_color::ColorMode::Multichannel {
+ return Err(Unsupported("Multichannel inks (printed on the CPU)".into()));
+ }
let mut p = Planner::new(DocCtx::of(doc));
let root = p.clear();
let root = p.stack(&doc.layers, root)?;
@@ -309,6 +333,16 @@ pub const F_REL: u32 = 512;
pub const F_STROKE_OUT: u32 = 1024;
/// First outside stroke (no accumulated share yet).
pub const F_FIRST: u32 = 2048;
+/// `Lerp` per channel: weights in `p0` (channel restrictions), no opacity or mask.
+pub const F_CHANNELS: u32 = 4096;
+/// `Lerp` as A + (B − C) premultiplied (layers clipped to pass-through groups).
+pub const F_ADD_DIFF: u32 = 16384;
+/// Blend / Atop / FxMerge of a type layer: coverage mixed at `psblend::TEXT_GAMMA`.
+pub const F_TEXT_GAMMA: u32 = 8192;
+
+fn gamma_flag(layer: &Layer) -> u32 {
+ if photocraft_compose::text_gamma(layer) != 1.0 { F_TEXT_GAMMA } else { 0 }
+}
/// `FxInit` kinds: A at `opacity` × alpha; an opaque copy of A; A's colour with alpha `opacity`
/// inside B's shape; A with alpha × B's alpha.
@@ -378,32 +412,86 @@ impl<'a> Planner<'a> {
Ok(backdrop)
}
- fn check(&self, layer: &Layer) -> Result<(), Unsupported> {
- if layer.artboard().is_some() {
- return Err(Unsupported(format!("artboard `{}` (clipped and rendered on the CPU)", layer.name)));
- }
- if layer.vector_mask.is_some() {
- return Err(Unsupported(format!("vector mask on `{}`", layer.name)));
- }
- if let LayerContent::Fill(f @ Fill::Pattern { .. }) = &layer.content
- && layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f)
- {
- return Err(Unsupported(format!("pattern fill `{}` (rendered on the CPU)", layer.name)));
- }
- Ok(())
- }
-
fn mask_use(&self, layer: &'a Layer) -> Option<MaskUse<'a>> {
+ if let Some(c) = photocraft_compose::masks::combined_mask(layer, self.cx.canvas) {
+ let default = c.default_pixel().first().copied().unwrap_or(1.0);
+ return Some(MaskUse { layer: layer.id, surface: SurfaceRef::Derived(std::sync::Arc::new(c)), density: 1.0, default });
+ }
let m = layer.mask.as_ref()?;
if !m.enabled {
return None;
}
- Some(MaskUse { layer: layer.id, surface: &m.surface, density: m.density, default: m.surface.default_pixel().first().copied().unwrap_or(1.0) })
+ Some(MaskUse { layer: layer.id, surface: SurfaceRef::Doc(&m.surface), density: m.density, default: m.surface.default_pixel().first().copied().unwrap_or(1.0) })
}
- /// composite_layer
+ /// composite_layer, honouring the layer's channel restrictions.
fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result<Slot, Unsupported> {
- self.check(layer)?;
+ match photocraft_compose::channel_weights(layer, self.cx.mode) {
+ Some(w) => {
+ let before = self.retain(backdrop);
+ let after = self.layer_any(layer, clipped, backdrop)?;
+ Ok(self.restore_channels(before, after, w))
+ }
+ None => self.layer_any(layer, clipped, backdrop),
+ }
+ }
+
+ /// `compose::restore_channels`: `after` with the channels a layer leaves out taken from
+ /// `before` (consumes both).
+ fn restore_channels(&mut self, before: Slot, after: Slot, w: [f32; 3]) -> Slot {
+ let mut p = Pass::new(Kernel::Lerp, 0);
+ p.a = Some(before);
+ p.b = Some(after);
+ p.flags = F_CHANNELS;
+ p.params[0] = [w[0], w[1], w[2], 1.0];
+ self.emit(p)
+ }
+
+ fn layer_any(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result<Slot, Unsupported> {
+ match layer.artboard() {
+ Some(ab) => self.artboard(layer, ab, clipped, backdrop),
+ None => self.layer_plain(layer, clipped, backdrop),
+ }
+ }
+
+ /// compose::composite_artboard: the board's background and the group composited over the
+ /// backdrop, kept only inside the board (contents and effects outside it are clipped away).
+ fn artboard(&mut self, layer: &'a Layer, ab: &photocraft_doc::Artboard, clipped: &'a [Layer], backdrop: Slot) -> Result<Slot, Unsupported> {
+ let board = ab.rect.intersect(&self.cx.canvas);
+ if board.is_empty() {
+ return Ok(backdrop);
+ }
+ let before = self.retain(backdrop);
+ let mut sub = backdrop;
+ if let Some(bg) = ab.background.rgba() {
+ let mut c = Pass::new(Kernel::Content, 0);
+ c.color = bg;
+ let c = self.emit(c);
+ let mut p = Pass::new(Kernel::Blend, 0);
+ p.a = Some(sub);
+ p.b = Some(c);
+ sub = self.emit(p);
+ }
+ let sub = self.layer_plain(layer, clipped, sub)?;
+ let dst = if self.refs[before as usize] == 1 {
+ before
+ } else {
+ let n = self.alloc();
+ let mut p = Pass::new(Kernel::CopyFull, n);
+ p.a = Some(before);
+ self.passes.push(p);
+ self.release(before);
+ n
+ };
+ let mut p = Pass::new(Kernel::CopyRect, dst);
+ p.a = Some(sub);
+ p.clip = Some(board);
+ self.passes.push(p);
+ self.release(sub);
+ Ok(dst)
+ }
+
+ fn layer_plain(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result<Slot, Unsupported> {
let opacity = layer.opacity * layer.fill_opacity;
let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect();
@@ -411,21 +499,45 @@ impl<'a> Planner<'a> {
&& layer.blend == BlendMode::PassThrough
&& !has_effects(layer)
{
- if !visible_clipped.is_empty() {
- return Err(Unsupported(format!("layers clipped to pass-through group `{}`", layer.name)));
- }
let before = self.retain(backdrop);
- let after = self.stack(&g.children, backdrop)?;
- if opacity < 1.0 || layer.mask.is_some() {
+ let mut after = self.stack(&g.children, backdrop)?;
+ if opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some() {
let mut p = Pass::new(Kernel::Lerp, 0);
- p.a = Some(before);
+ p.a = Some(self.retain(before));
p.b = Some(after);
p.opacity = opacity;
p.mask = self.mask_use(layer);
- return Ok(self.emit(p));
+ after = self.emit(p);
}
- self.release(before);
- return Ok(after);
+ if visible_clipped.is_empty() {
+ self.release(before);
+ return Ok(after);
+ }
+ // Layers clipped to a pass-through group (compose: their effect on the group's
+ // isolated rendering, each placed over the original backdrop, is added to the
+ // pass-through result, premultiplied).
+ let iso = self.content(layer)?;
+ let iso_keep = self.retain(iso);
+ let mut clipped_iso = iso;
+ for c in visible_clipped {
+ clipped_iso = self.atop(c, clipped_iso)?;
+ }
+ let over = |s: &mut Self, src: Slot, before: Slot| {
+ let mut p = Pass::new(Kernel::Blend, 0);
+ p.a = Some(before);
+ p.b = Some(src);
+ p.opacity = opacity;
+ s.emit(p)
+ };
+ let b2 = self.retain(before);
+ let without = over(self, iso_keep, b2);
+ let with = over(self, clipped_iso, before);
+ let mut p = Pass::new(Kernel::Lerp, 0);
+ p.a = Some(after);
+ p.b = Some(with);
+ p.c = Some(without);
+ p.flags = F_ADD_DIFF;
+ return Ok(self.emit(p));
}
if let LayerContent::Adjustment(adj) = &layer.content {
@@ -448,11 +560,35 @@ impl<'a> Planner<'a> {
}
if let LayerContent::Shape(sh) = &layer.content
- && sh.stroke.is_some()
&& !visible_clipped.is_empty()
+ && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas)
{
- // The vector stroke goes above the clipped layers (CPU path splits fill and stroke).
- return Err(Unsupported(format!("stroked shape `{}` with clipped layers", layer.name)));
+ // The vector stroke goes above the clipped layers: the fill is the clipping base,
+ // the stroke is laid over the clipped result (compose::shape_parts).
+ let part = |s: &mut Self, role: Role, surface: Surface| {
+ let mut p = Pass::new(Kernel::Content, 0);
+ p.mask = s.mask_use(layer);
+ p.color = photocraft_raster::to_rgba(&surface.format(), &surface.default_pixel());
+ if surface.tile_count() > 0 {
+ p.tex = Some(TexUse { layer: layer.id, role, surface: SurfaceRef::Derived(std::sync::Arc::new(surface)) });
+ }
+ s.emit(p)
+ };
+ let mut content = part(self, Role::Content, fill);
+ for c in visible_clipped {
+ content = self.atop(c, content)?;
+ }
+ let stroke = part(self, Role::Stroke, stroke);
+ let mut p = Pass::new(Kernel::Blend, 0);
+ p.a = Some(content);
+ p.b = Some(stroke);
+ let content = self.emit(p);
+ let mut p = Pass::new(Kernel::Blend, 0);
+ p.a = Some(backdrop);
+ p.b = Some(content);
+ p.mode = layer.blend;
+ p.opacity = opacity;
+ return Ok(self.emit(p));
}
let mut content = self.content(layer)?;
@@ -464,6 +600,7 @@ impl<'a> Planner<'a> {
p.b = Some(content);
p.mode = layer.blend;
p.opacity = opacity;
+ p.flags = gamma_flag(layer);
Ok(self.emit(p))
}
@@ -473,7 +610,7 @@ impl<'a> Planner<'a> {
LayerContent::Group(g) => {
let empty = self.clear();
let s = self.stack(&g.children, empty)?;
- if layer.mask.is_some() {
+ if layer.mask.is_some() || layer.vector_mask.is_some() {
let mut p = Pass::new(Kernel::Mask, 0);
p.a = Some(s);
p.mask = self.mask_use(layer);
@@ -482,6 +619,24 @@ impl<'a> Planner<'a> {
Ok(s)
}
LayerContent::Adjustment(_) => unreachable!("adjustments handled by the caller"),
+ LayerContent::Fill(f @ Fill::Pattern { name, scale, id, angle, link, phase }) if layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f) => {
+ // compose::render_fill: the pattern tiled from the layer's frame (transparent
+ // when missing), then the layer's masks.
+ let empty = self.clear();
+ let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| !p.is_empty()) else { return Ok(empty) };
+ let frame = photocraft_compose::fill_frame(layer, self.cx.canvas);
+ let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) };
+ let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle));
+ let canvas = self.cx.canvas;
+ let s = self.paint(empty, empty, Cov::One, &paint, BlendMode::Normal, 1.0, 0, canvas, canvas);
+ if layer.mask.is_some() || layer.vector_mask.is_some() {
+ let mut p = Pass::new(Kernel::Mask, 0);
+ p.a = Some(s);
+ p.mask = self.mask_use(layer);
+ return Ok(self.emit(p));
+ }
+ Ok(s)
+ }
_ => {
let p = self.content_pass(layer);
Ok(self.emit(p))
@@ -511,7 +666,7 @@ impl<'a> Planner<'a> {
let dp = s.default_pixel();
p.color = photocraft_raster::to_rgba(&s.format(), &dp);
if s.tile_count() > 0 {
- p.tex = Some(TexUse { layer: id, role: Role::Content, surface: s });
+ p.tex = Some(TexUse { layer: id, role: Role::Content, surface: SurfaceRef::Doc(s) });
}
}
@@ -547,9 +702,20 @@ impl<'a> Planner<'a> {
}
}
- /// composite_atop: `layer` onto `base`, restricted to the base's alpha.
+ /// composite_atop: `layer` onto `base`, restricted to the base's alpha, honouring the
+ /// layer's channel restrictions.
fn atop(&mut self, layer: &'a Layer, base: Slot) -> Result<Slot, Unsupported> {
- self.check(layer)?;
+ match photocraft_compose::channel_weights(layer, self.cx.mode) {
+ Some(w) => {
+ let before = self.retain(base);
+ let after = self.atop_any(layer, base)?;
+ Ok(self.restore_channels(before, after, w))
+ }
+ None => self.atop_any(layer, base),
+ }
+ }
+
+ fn atop_any(&mut self, layer: &'a Layer, base: Slot) -> Result<Slot, Unsupported> {
let opacity = layer.opacity * layer.fill_opacity;
if let LayerContent::Adjustment(adj) = &layer.content {
let before = self.retain(base);
@@ -571,6 +737,7 @@ impl<'a> Planner<'a> {
p.b = Some(content);
p.mode = layer.blend;
p.opacity = opacity;
+ p.flags = gamma_flag(layer);
Ok(self.emit(p))
}
@@ -695,6 +862,7 @@ impl<'a> Planner<'a> {
if let Effect::BevelEmboss(b) = e
&& b.style != photocraft_doc::BevelStyle::OuterBevel
{
+ // Inner part (emboss styles: maps 0–1 inside, 2–3 outside).
l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(b.highlight_color.to_rgb()), b.highlight.blend, b.highlight.opacity, F_REL, clip, sb);
l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb);
}
@@ -738,10 +906,12 @@ impl<'a> Planner<'a> {
}
for &(i, e) in &rev {
if let Effect::BevelEmboss(b) = e
- && b.style == photocraft_doc::BevelStyle::OuterBevel
+ && let paint = photocraft_compose::effects::bevel_geom(b).paint
+ && paint != photocraft_compose::effects::BevelPaint::Inner
{
- w = self.paint(w, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(b.highlight_color.to_rgb()), b.highlight.blend, b.highlight.opacity, 0, clip, sb);
- w = self.paint(w, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb);
+ let k = if paint == photocraft_compose::effects::BevelPaint::Both { 2 } else { 0 };
+ w = self.paint(w, content, Cov::Map(map(i, k), 0.0), &Paint::Color(b.highlight_color.to_rgb()), b.highlight.blend, b.highlight.opacity, 0, clip, sb);
+ w = self.paint(w, content, Cov::Map(map(i, k + 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb);
}
}
@@ -751,7 +921,7 @@ impl<'a> Planner<'a> {
p.c = Some(self.retain(backdrop));
p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend };
p.opacity = layer.opacity;
- p.flags = if atop { F_ATOP } else { 0 };
+ p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer);
p.clip = Some(clip);
let merged = self.emit(p);
self.release(content);
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 35ae977a6..015c4dbe4 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -224,6 +224,22 @@ fn groups_masks_and_clipping() {
c.clipped = true;
d.layers.extend([gb, c]);
check(&mut g, &d, "clipped to isolated group");
+ // Layers clipped to a pass-through group (with opacity and a mask, children in modes).
+ for (op, masked) in [(1.0, false), (0.6, true)] {
+ let mut d = base_doc(56, 44);
+ let mut pt = Layer::group("pt", vec![child(31, BlendMode::Normal), child(32, BlendMode::Multiply)]);
+ pt.opacity = op;
+ if masked {
+ pt.mask = Some(mask(Rect::new(5, 0, 50, 44), 33, 1.0));
+ }
+ let mut c1 = child(34, BlendMode::Screen);
+ c1.clipped = true;
+ c1.opacity = 0.8;
+ let mut c2 = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert));
+ c2.clipped = true;
+ d.layers.extend([pt, c1, c2]);
+ check(&mut g, &d, &format!("clipped to pass-through op {op} masked {masked}"));
+ }
}
#[test]
@@ -441,6 +457,11 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
("bevel outer", vec![Effect::BevelEmboss(bevel(BevelStyle::OuterBevel, true, 6.0, 0.0))]),
("bevel emboss down", vec![Effect::BevelEmboss(bevel(BevelStyle::Emboss, false, 8.0, 1.0))]),
("bevel pillow", vec![Effect::BevelEmboss(bevel(BevelStyle::PillowEmboss, true, 5.0, 4.0))]),
+ ("bevel inner chisel hard", vec![Effect::BevelEmboss(Bevel { technique: BevelTechnique::ChiselHard, ..bevel(BevelStyle::InnerBevel, true, 9.0, 0.0) })]),
+ ("bevel outer chisel soft", vec![Effect::BevelEmboss(Bevel { technique: BevelTechnique::ChiselSoft, ..bevel(BevelStyle::OuterBevel, false, 7.5, 2.0) })]),
+ ("bevel pillow chisel hard", vec![Effect::BevelEmboss(Bevel { technique: BevelTechnique::ChiselHard, ..bevel(BevelStyle::PillowEmboss, false, 7.0, 0.0) })]),
+ ("bevel emboss smooth wide", vec![Effect::BevelEmboss(bevel(BevelStyle::Emboss, true, 21.0, 0.0))]),
+ ("bevel stroke emboss", vec![Effect::BevelEmboss(bevel(BevelStyle::StrokeEmboss, true, 6.0, 0.0))]),
("bevel contour own light", vec![Effect::BevelEmboss(bevel_contour)]),
("satin", vec![Effect::Satin(satin)]),
("satin inverted contour", vec![Effect::Satin(satin_inv)]),
@@ -683,3 +704,209 @@ fn layer_effects_on_shape_layers() {
fx_check(&mut g, &d, &format!("shape layer alpha {alpha}"));
}
}
+
+#[test]
+fn channel_restrictions() {
+ let Some(mut g) = gpu() else { return };
+ for mask_bits in [0b001u32, 0b010, 0b100, 0b101, 0b111] {
+ // Raster layer in a blend mode, an adjustment and a clipped layer.
+ let mut d = base_doc(64, 48);
+ let mut l = noise_layer("top", PixelFormat::RGBA8, Rect::new(4, 3, 60, 45), 2, 0.0);
+ l.blend = BlendMode::Multiply;
+ l.excluded_channels = mask_bits;
+ d.layers.push(l);
+ let mut adj = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert));
+ adj.excluded_channels = mask_bits.rotate_left(1) & 0b111;
+ d.layers.push(adj);
+ let mut c = noise_layer("clip", PixelFormat::RGBA8, Rect::new(10, 10, 50, 40), 3, 0.2);
+ c.clipped = true;
+ c.excluded_channels = mask_bits;
+ d.layers.push(c);
+ check(&mut g, &d, &format!("channels {mask_bits:03b}"));
+
+ // An effect layer (exterior and interior effects).
+ let mut d = fx_doc(96, 80, SampleType::U8);
+ let mut l = blob("fx", d.pixel_format(), 46.0, 40.0, 22.0, [0.9, 0.4, 0.2]);
+ l.effects.items = vec![
+ Effect::DropShadow(shadow(BlendMode::Multiply, 0.7, 120.0, 6.0, 8.0, 0.1)),
+ Effect::InnerGlow(glow(FxPaint::Color(Color::rgb(1.0, 1.0, 0.5)), GlowTechnique::Softer, 9.0, 0.0, GlowSource::Edge)),
+ ];
+ l.excluded_channels = mask_bits;
+ d.layers.push(l);
+ fx_check(&mut g, &d, &format!("fx channels {mask_bits:03b}"));
+ }
+ // Grayscale: the single channel left out keeps the backdrop.
+ let mut d = Document::new("g", Size::new(32, 32), ColorMode::Grayscale, SampleType::U8);
+ d.layers.push(noise_layer("bg", PixelFormat::GRAYA8, Rect::new(0, 0, 32, 32), 9, 1.0));
+ let mut l = noise_layer("top", PixelFormat::GRAYA8, Rect::new(0, 0, 32, 32), 10, 1.0);
+ l.excluded_channels = 1;
+ d.layers.push(l);
+ check(&mut g, &d, "gray channels");
+ let flat = photocraft_compose::flatten(&d);
+ let bg = photocraft_compose::render_layer(&d.layers[0], d.bounds());
+ assert!(flat.px.iter().zip(&bg.px).all(|(a, b)| (a[0] - b[0]).abs() < 1e-6));
+}
+
+/// A type layer whose rendered pixels are `src`'s (blends with the text gamma).
+fn as_text(src: Layer) -> Layer {
+ let t = photocraft_doc::TextLayer { cache: src.surface().cloned(), ..Default::default() };
+ let mut l = Layer::new(&src.name, LayerContent::Text(t));
+ l.blend = src.blend;
+ l.opacity = src.opacity;
+ l.effects = src.effects;
+ l
+}
+
+#[test]
+fn type_layers_blend_with_text_gamma() {
+ let Some(mut g) = gpu() else { return };
+ for mode in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Color] {
+ let mut d = base_doc(64, 48);
+ let mut l = as_text(noise_layer("text", PixelFormat::RGBA8, Rect::new(4, 3, 60, 45), 21, 0.0));
+ l.blend = mode;
+ l.opacity = 0.9;
+ d.layers.push(l);
+ // Clipped type layer.
+ let mut c = as_text(noise_layer("clip", PixelFormat::RGBA8, Rect::new(8, 8, 50, 40), 22, 0.0));
+ c.clipped = true;
+ c.blend = mode;
+ d.layers.push(c);
+ check(&mut g, &d, &format!("text {mode:?}"));
+ }
+ // With effects (the merge of the layer onto its exterior effects).
+ let mut d = fx_doc(96, 80, SampleType::U8);
+ let mut l = as_text(blob("fx", d.pixel_format(), 46.0, 40.0, 22.0, [0.2, 0.1, 0.6]));
+ l.effects.items = vec![Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: Color::rgb(0.0, 0.2, 0.6) }, Effect::DropShadow(shadow(BlendMode::Multiply, 0.6, 90.0, 5.0, 6.0, 0.0))];
+ d.layers.push(l);
+ fx_check(&mut g, &d, "text fx");
+ // The gamma changes edge pixels against a linear mix.
+ let flat = photocraft_compose::flatten(&d);
+ let mut lin = d.clone();
+ let raster = {
+ let LayerContent::Text(t) = &lin.layers[1].content else { unreachable!() };
+ let mut r = Layer::new("r", LayerContent::Raster(t.cache.clone().unwrap()));
+ r.effects = lin.layers[1].effects.clone();
+ r
+ };
+ lin.layers[1] = raster;
+ let flat_lin = photocraft_compose::flatten(&lin);
+ assert!(flat.px.iter().zip(&flat_lin.px).any(|(a, b)| (a[0] - b[0]).abs() > 0.02));
+}
+
+#[test]
+fn blend_mode_extremes() {
+ // Exact 0 / 1 channels on both sides (Color Burn / Dodge / Vivid Light / Hard Mix corners).
+ let Some(mut g) = gpu() else { return };
+ let vals = [0.0f32, 1.0, 0.5];
+ for depth in [SampleType::U8, SampleType::U16] {
+ for mode in BlendMode::LAYER_MODES {
+ let mut d = Document::new("x", Size::new(9, 9), ColorMode::Rgb, depth);
+ let fmt = d.pixel_format();
+ let mut bg = Layer::raster("bg", fmt);
+ let mut top = Layer::raster("top", fmt);
+ for (i, &b) in vals.iter().enumerate() {
+ for (j, &s) in vals.iter().enumerate() {
+ for k in 0..3 {
+ let (x, y) = ((i * 3 + k) as i32, j as i32 * 3);
+ let r = Rect::from_xywh(x, y, 1, 3);
+ bg.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [b, b, b, 1.0]));
+ top.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [s, s, s, [1.0, 0.6, 0.2][k]]));
+ }
+ }
+ }
+ top.blend = mode;
+ d.layers.push(bg);
+ d.layers.push(top);
+ check(&mut g, &d, &format!("extremes {mode:?} {depth:?}"));
+ }
+ }
+}
+
+#[test]
+fn stroked_shapes_with_clipped_layers() {
+ let Some(mut g) = gpu() else { return };
+ use photocraft_doc::vector::{Path, ShapeLayer, ShapeStroke, Subpath};
+ for (blend, masked) in [(BlendMode::Normal, false), (BlendMode::Multiply, true)] {
+ let mut d = base_doc(80, 64);
+ let path = Path::new(vec![Subpath::polygon(&[(10.3, 8.6), (66.2, 12.1), (58.7, 54.4), (16.9, 48.2)])]);
+ let stroke = ShapeStroke { width: 5.0, paint: Fill::Solid(Color::rgb(0.9, 0.9, 0.1)), ..Default::default() };
+ let mut sh = ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(0.2, 0.3, 0.8))), stroke: Some(stroke), live: None, cache: None, psd_raw: None };
+ sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds()));
+ let mut l = Layer::new("shape", LayerContent::Shape(sh));
+ l.blend = blend;
+ l.opacity = 0.9;
+ if masked {
+ l.mask = Some(mask(Rect::new(0, 0, 80, 64), 41, 1.0));
+ }
+ let mut c = noise_layer("clip", PixelFormat::RGBA8, Rect::new(0, 0, 80, 64), 42, 0.5);
+ c.clipped = true;
+ c.blend = BlendMode::Screen;
+ d.layers.extend([l, c]);
+ let st = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, &d, d.bounds());
+ assert!(st.is_ok(), "planned on the GPU");
+ check(&mut g, &d, &format!("stroked shape + clipped {blend:?} masked {masked}"));
+ }
+}
+
+#[test]
+fn artboards() {
+ let Some(mut g) = gpu() else { return };
+ use photocraft_doc::{Artboard, ArtboardBackground};
+ let backgrounds = [ArtboardBackground::White, ArtboardBackground::Transparent, ArtboardBackground::Custom({
+ let mut c = Color::rgb(0.2, 0.7, 0.4);
+ c.alpha = 0.5;
+ c
+ })];
+ for bg in backgrounds {
+ for blend in [BlendMode::PassThrough, BlendMode::Normal, BlendMode::Multiply] {
+ let mut d = base_doc(72, 48);
+ let mut child = noise_layer("c", PixelFormat::RGBA8, Rect::new(0, 0, 72, 48), 51, 0.0);
+ child.blend = BlendMode::Screen;
+ let mut fx = blob("fx", PixelFormat::RGBA8, 34.0, 24.0, 12.0, [0.8, 0.3, 0.2]);
+ fx.effects.items = vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.8, 120.0, 6.0, 8.0, 0.0))];
+ let mut ab = Layer::group("Artboard", vec![child, fx]);
+ ab.blend = blend;
+ if let LayerContent::Group(gr) = &mut ab.content {
+ gr.artboard = Some(Artboard { rect: Rect::new(12, 6, 60, 40), background: bg.clone(), preset: String::new() });
+ }
+ d.layers.push(ab);
+ // A second, partly off-canvas board.
+ let mut ab2 = Layer::group("Artboard 2", vec![noise_layer("c2", PixelFormat::RGBA8, Rect::new(0, 0, 72, 48), 52, 0.3)]);
+ if let LayerContent::Group(gr) = &mut ab2.content {
+ gr.artboard = Some(Artboard { rect: Rect::new(50, 30, 90, 70), background: ArtboardBackground::Black, preset: String::new() });
+ }
+ d.layers.push(ab2);
+ fx_check(&mut g, &d, &format!("artboard {bg:?} {blend:?}"));
+ }
+ }
+}
+
+#[test]
+fn pattern_fill_layers() {
+ let Some(mut g) = gpu() else { return };
+ let pat = checker_pattern();
+ for (link, scale, angle, masked) in [(true, 1.0, 0.0, false), (false, 0.7, 25.0, true), (true, 1.6, -40.0, false)] {
+ let mut d = base_doc(70, 50);
+ d.patterns.push(pat.clone());
+ let fill = Fill::Pattern { name: pat.name.clone(), id: pat.id.clone(), scale, angle, link, phase: (3.0, -2.0) };
+ let mut l = Layer::new("pat", LayerContent::Fill(fill));
+ l.opacity = 0.85;
+ l.blend = BlendMode::Overlay;
+ if masked {
+ l.mask = Some(mask(Rect::new(5, 5, 60, 45), 61, 0.0));
+ }
+ d.layers.push(l.clone());
+ // With effects, and a missing pattern (transparent).
+ let mut fx = l.clone();
+ fx.id = photocraft_doc::LayerId::fresh();
+ fx.effects.items = vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.6, 90.0, 3.0, 4.0, 0.0))];
+ fx.mask = Some(mask(Rect::new(20, 10, 50, 40), 62, 0.0));
+ d.layers.push(fx);
+ let mut missing = l;
+ missing.id = photocraft_doc::LayerId::fresh();
+ missing.content = LayerContent::Fill(Fill::Pattern { name: "nope".into(), id: "nope".into(), scale: 1.0, angle: 0.0, link: true, phase: (0.0, 0.0) });
+ d.layers.push(missing);
+ fx_check(&mut g, &d, &format!("pattern fill link {link} scale {scale} angle {angle}"));
+ }
+}
+
diff --git a/crates/gpu/tests/vector_mask.rs b/crates/gpu/tests/vector_mask.rs
index 48a9d6797..04d40f6da 100644
--- a/crates/gpu/tests/vector_mask.rs
+++ b/crates/gpu/tests/vector_mask.rs
@@ -1,16 +1,90 @@
-//! Layers with vector masks are not planned on the GPU yet: the planner reports `Unsupported`
-//! so callers fall back to the CPU compositor (which rasterizes the mask).
+//! Vector masks on the GPU: the planner samples the layer's combined mask (pixel mask × the
+//! rasterised path, `compose::masks::combined_mask`); results must match the CPU compositor.
-use photocraft_color::{Color, ColorMode, SampleType};
-use photocraft_doc::{Document, Layer, Path, Size, Subpath, VectorMask};
+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{Adjustment, Document, Effect, Layer, LayerContent, LayerMask, Path, Size, Subpath, VectorMask};
+use photocraft_geom::Rect;
+
+fn gpu() -> Option<(wgpu::Device, wgpu::Queue, photocraft_gpu::Compositor)> {
+ let instance = wgpu::Instance::default();
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()?;
+ let comp = photocraft_gpu::Compositor::new(&device);
+ Some((device, queue, comp))
+}
+
+fn check(g: &mut (wgpu::Device, wgpu::Queue, photocraft_gpu::Compositor), d: &Document, what: &str) {
+ let cpu = photocraft_compose::flatten(d);
+ let out = photocraft_gpu::render_to_vec(&mut g.2, &g.0, &g.1, d, d.bounds()).unwrap_or_else(|e| panic!("{what}: {e}"));
+ let worst = cpu
+ .px
+ .iter()
+ .zip(&out)
+ .map(|(c, o)| (0..4).map(|k| if k == 3 { (c[3] - o[3]).abs() } else { (c[k] * c[3] - o[k] * o[3]).abs() }).fold(0.0f32, f32::max))
+ .fold(0.0f32, f32::max);
+ assert!(worst <= 1.0 / 255.0, "{what}: max diff {:.2}/255", worst * 255.0);
+}
+
+fn tri(inverted: bool, density: f32) -> VectorMask {
+ let mut p = Path::new(vec![Subpath::polygon(&[(3.5, 2.0), (40.0, 6.3), (12.0, 30.7)])]);
+ p.inverted = inverted;
+ let mut vm = VectorMask::new(p);
+ vm.density = density;
+ vm
+}
+
+fn painted(name: &str, fmt: PixelFormat, rgba: [f32; 4]) -> Layer {
+ let mut l = Layer::raster(name, fmt);
+ l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 44, 34), &photocraft_raster::from_rgba(&fmt, rgba));
+ l
+}
#[test]
-fn vector_mask_falls_back_to_cpu() {
- let mut d = Document::with_background("v", Size::new(16, 16), ColorMode::Rgb, SampleType::U8, Color::WHITE);
- assert!(photocraft_gpu::plan(&d).is_ok());
- let mut l = Layer::raster("masked", d.pixel_format());
- l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (8.0, 0.0), (8.0, 16.0)])])));
- d.layers.push(Layer::group("g", vec![l]));
- let Err(err) = photocraft_gpu::plan(&d) else { panic!("vector masks are CPU-only") };
- assert!(err.0.contains("vector mask"), "{err}");
+fn vector_masks_match_the_cpu() {
+ let Some(mut g) = gpu() else { return };
+ for depth in [SampleType::U8, SampleType::U16] {
+ for (inverted, density) in [(false, 1.0), (true, 1.0), (false, 0.6)] {
+ let mut d = Document::with_background("v", Size::new(44, 34), ColorMode::Rgb, depth, Color::WHITE);
+ let fmt = d.pixel_format();
+ // Raster layer with a vector mask and a pixel mask.
+ let mut l = painted("a", fmt, [0.9, 0.2, 0.1, 0.8]);
+ l.vector_mask = Some(tri(inverted, density));
+ let mut m = LayerMask::reveal_all();
+ m.surface.fill_rect(Rect::new(20, 0, 44, 34), &[0.3]);
+ m.density = 0.9;
+ l.mask = Some(m);
+ l.blend = BlendMode::Multiply;
+ d.layers.push(l);
+ // A group (isolated and pass-through) with a vector mask.
+ let mut inner = painted("b", fmt, [0.1, 0.6, 0.9, 1.0]);
+ inner.opacity = 0.7;
+ let mut grp = Layer::group("g", vec![inner]);
+ grp.vector_mask = Some(tri(!inverted, density));
+ grp.blend = BlendMode::Normal;
+ d.layers.push(grp.clone());
+ grp.blend = BlendMode::PassThrough;
+ d.layers.push(grp);
+ // An adjustment layer and an effect layer with vector masks.
+ let mut adj = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert));
+ adj.vector_mask = Some(tri(inverted, density));
+ d.layers.push(adj);
+ let mut fx = painted("fx", fmt, [0.2, 0.8, 0.3, 1.0]);
+ fx.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 44, 34), &photocraft_raster::from_rgba(&fmt, [0.0; 4]));
+ fx.surface_mut().unwrap().fill_rect(Rect::new(8, 8, 30, 26), &photocraft_raster::from_rgba(&fmt, [0.2, 0.8, 0.3, 1.0]));
+ fx.vector_mask = Some(tri(inverted, density));
+ fx.effects.items = vec![Effect::default_drop_shadow()];
+ d.layers.push(fx);
+ check(&mut g, &d, &format!("{depth:?} inverted {inverted} density {density}"));
+ // Editing the path re-rasterises the mask.
+ if let Some(vm) = &mut d.layers[1].vector_mask {
+ vm.path.subpaths[0].knots[1].anchor.x = 30.0;
+ vm.path.subpaths[0].knots[1].in_ctrl.x = 30.0;
+ vm.path.subpaths[0].knots[1].out_ctrl.x = 30.0;
+ }
+ check(&mut g, &d, "edited path");
+ // Disabling it shows the layer unmasked by the path.
+ d.layers[1].vector_mask.as_mut().unwrap().enabled = false;
+ check(&mut g, &d, "disabled");
+ }
+ }
}
diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs
index 0bd5c3fc2..961d3650c 100644
--- a/crates/io/examples/oracle_diff.rs
+++ b/crates/io/examples/oracle_diff.rs
@@ -8,18 +8,39 @@
//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 worst [n] # n worst pixels
//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 grid x0 y0 x1 y1 [ch] # value grids
//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 layerpx x y # each layer's pixel
+//! cargo run --release -p photocraft-io --example oracle_diff -- corpus/psd # every file: max err, bad %, PASS/DIFF
+//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 dump prefix # raw f32 planes for offline fitting
+//! HIDE_ADJ=1 … # adjustment layers hidden
//! DUMP_FX=1 … # raw effects descriptors
//! ```
fn main() {
let path = std::env::args().nth(1).expect("path");
+ if std::path::Path::new(&path).is_dir() {
+ corpus_summary(std::path::Path::new(&path));
+ return;
+ }
let bytes = std::fs::read(&path).unwrap();
let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();
- let imp = photocraft_io::import(&path, &bytes).unwrap();
+ let mut imp = photocraft_io::import(&path, &bytes).unwrap();
+ if std::env::var_os("HIDE_ADJ").is_some() {
+ // Composite without adjustment layers (their input, for fitting transfer curves).
+ fn hide(ls: &mut [photocraft_doc::Layer]) {
+ for l in ls {
+ if matches!(l.content, photocraft_doc::LayerContent::Adjustment(_)) {
+ l.visible = false;
+ }
+ if let photocraft_doc::LayerContent::Group(g) = &mut l.content {
+ hide(&mut g.children);
+ }
+ }
+ }
+ hide(&mut imp.document.layers);
+ }
let doc = &imp.document;
- println!("mode {:?} depth {:?} layers {} warnings {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings);
+ println!("mode {:?} depth {:?} layers {} warnings {:?} light {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings, doc.global_light);
for l in doc.walk() {
let l = l.2;
- println!(" layer {:?} {:?} blend {:?} op {} fill {} fill_cache {}", l.name, l.content.kind_name(), l.blend, l.opacity, l.fill_opacity, l.fill_cache.is_some());
+ println!(" layer {:?} {:?} blend {:?} op {} fill {} fill_cache {} visible {}", l.name, l.content.kind_name(), l.blend, l.opacity, l.fill_opacity, l.fill_cache.is_some(), l.visible);
if let photocraft_doc::LayerContent::Adjustment(a) = &l.content {
println!(" {}", format!("{a:?}").chars().take(800).collect::<String>());
}
@@ -62,7 +83,7 @@ fn main() {
let g = format!("{gradient:?}");
println!(" gradient overlay: {g}");
} else if format!("{e:?}").contains("enabled: true") {
- println!(" fx {}", format!("{e:?}").chars().take(200).collect::<String>());
+ println!(" fx {}", format!("{e:?}").chars().take(if std::env::var_os("FULL").is_some() { 100_000 } else { 200 }).collect::<String>());
}
}
println!(" blocks {:?}", l.psd_blocks.iter().map(|(k, v)| format!("{}({})", String::from_utf8_lossy(k), v.len())).collect::<Vec<_>>());
@@ -155,6 +176,26 @@ fn main() {
println!("wrote {out}");
return;
}
+ if std::env::args().nth(3).as_deref() == Some("dump") {
+ // dump prefix: raw little-endian f32 RGBA (straight) planes for offline fitting:
+ // prefix_ours.f32, prefix_ps.f32, prefix_L<i>.f32 (each top-level layer's own pixels,
+ // masks not applied) and prefix.txt (width, height, layer names).
+ let out = std::env::args().nth(4).expect("prefix");
+ let wr = |name: String, px: &[[f32; 4]]| {
+ let bytes: Vec<u8> = px.iter().flat_map(|p| p.iter().flat_map(|v| v.to_le_bytes())).collect();
+ std::fs::write(name, bytes).unwrap();
+ };
+ wr(format!("{out}_ours.f32"), &ours);
+ wr(format!("{out}_ps.f32"), &merged);
+ let mut meta = format!("{} {}\n", doc.size.width, doc.size.height);
+ for (i, l) in doc.layers.iter().enumerate() {
+ let b = photocraft_compose::surface_to_buffer(l.surface().unwrap_or(&photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8)), doc.bounds());
+ wr(format!("{out}_L{i}.f32"), &b.px);
+ meta += &format!("{i} {}\n", l.name);
+ }
+ std::fs::write(format!("{out}.txt"), meta).unwrap();
+ return;
+ }
if std::env::args().nth(3).as_deref() == Some("layerpx") {
// layerpx x y: each layer's own pixel (0-255).
let x: i32 = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0);
@@ -228,3 +269,78 @@ fn main() {
println!("{i:4}: ours {:?}\n ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0));
}
}
+
+/// The corpus oracle table (as `tests/corpus.rs`), files in parallel, without a test build.
+fn corpus_summary(root: &std::path::Path) {
+ fn collect(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
+ let Ok(rd) = std::fs::read_dir(dir) else { return };
+ for e in rd.flatten() {
+ let p = e.path();
+ if p.is_dir() {
+ collect(&p, out);
+ } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb")) {
+ out.push(p);
+ }
+ }
+ }
+ let mut files = Vec::new();
+ collect(root, &mut files);
+ files.sort();
+ const TOL: f32 = 2.0 / 255.0;
+ let row = |p: &std::path::PathBuf| -> (String, Option<(f32, f32)>) {
+ let name = p.strip_prefix(root).unwrap_or(p).display().to_string();
+ let Ok(bytes) = std::fs::read(p) else { return (name, None) };
+ let Ok(file) = photocraft_psd::PsdFile::from_bytes(&bytes) else { return (name, None) };
+ let Ok(imp) = photocraft_io::import(&name, &bytes) else { return (name, None) };
+ if file.has_real_merged_data() == Some(false) || file.layers().is_empty() {
+ return (name, None);
+ }
+ let Ok(merged) = photocraft_io::merged_composite(&file) else { return (name, None) };
+ let ours = photocraft_compose::flatten(&imp.document).px;
+ let mut m = 0.0f32;
+ let mut bad = 0usize;
+ for (a, b) in ours.iter().zip(&merged) {
+ let d = (0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max);
+ m = m.max(d);
+ if (0..4).any(|c| (a[c] * a[3] - b[c] * b[3]).abs() > TOL) {
+ bad += 1;
+ }
+ }
+ (name, Some((m, 100.0 * bad as f32 / ours.len().max(1) as f32)))
+ };
+ // Files in parallel (a few threads; flatten itself is tile-parallel).
+ let next = std::sync::atomic::AtomicUsize::new(0);
+ let mut rows: Vec<(usize, (String, Option<(f32, f32)>))> = std::thread::scope(|sc| {
+ let hs: Vec<_> = (0..4)
+ .map(|_| {
+ sc.spawn(|| {
+ let mut out = Vec::new();
+ loop {
+ let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ let Some(p) = files.get(i) else { break };
+ out.push((i, row(p)));
+ }
+ out
+ })
+ })
+ .collect();
+ hs.into_iter().flat_map(|h| h.join().unwrap()).collect()
+ });
+ rows.sort_by_key(|r| r.0);
+ let rows: Vec<(String, Option<(f32, f32)>)> = rows.into_iter().map(|r| r.1).collect();
+ let (mut pass, mut diff, mut skip) = (0, 0, 0);
+ for (name, r) in &rows {
+ match r {
+ Some((m, pct)) if *m <= TOL => {
+ pass += 1;
+ println!("{name:<60} {m:>9.4} {pct:>7.2}% PASS");
+ }
+ Some((m, pct)) => {
+ diff += 1;
+ println!("{name:<60} {m:>9.4} {pct:>7.2}% DIFF");
+ }
+ None => skip += 1,
+ }
+ }
+ println!("{} files: {pass} pass, {diff} differ, {skip} skipped/errors", rows.len());
+}
diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs
new file mode 100644
index 000000000..3b8c42e72
--- /dev/null
+++ b/crates/io/src/annotations_map.rs
@@ -0,0 +1,408 @@
+//! Notes and Image › Analysis data ⇄ PSD.
+//!
+//! * Notes: the global additional-info block `Anno` ("Annotations (Photoshop 6.0)" in the Adobe
+//! PSD spec): `u16` major version 2, `u16` minor version 1, `u32` count, then per annotation a
+//! `u32` length (including itself), type `txtA` (text) or `sndA` (sound), open flag `u8`,
+//! flags `u8`, optional blocks `u16`, icon rect and popup rect (four `i32` each: top, left,
+//! bottom, right), a colour (`u16` space + four `u16`), author, name and modification date as
+//! even-padded Pascal strings, then a `u32` length (including itself) of the data block:
+//! `txtC`/`sndM`, `u32` size and the data. Text is UTF-16BE with a byte-order mark, lines
+//! separated by CR. Layout checked against `corpus/psd/ag-psd/read-write/annotations`.
+//! Sound annotations are not modelled; they are carried over verbatim when notes are rewritten.
+//! * Measurement scale: image resource 1074 (a version-16 descriptor). The key names
+//! (`pixelLength`, `logicalLength`, `logicalUnits`) follow Photoshop's scripting names for the
+//! measurement scale; no sample file was available, so parsing is lenient and the raw resource
+//! is kept byte-exact while the scale is unchanged.
+//! * Count information: image resource 1080 is kept verbatim (its layout is not public) unless
+//! the document has its own count markers, which only `.pcraft` stores.
+
+use std::sync::Arc;
+
+use photocraft_doc::{Color, Document, MeasurementScale, Note};
+use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor};
+
+pub const MEASUREMENT_SCALE: u16 = 1074;
+pub const COUNT_INFO: u16 = 1080;
+pub const ANNO: [u8; 4] = *b"Anno";
+
+struct Reader<'a> {
+ d: &'a [u8],
+ p: usize,
+}
+
+impl<'a> Reader<'a> {
+ fn take(&mut self, n: usize) -> Option<&'a [u8]> {
+ let s = self.d.get(self.p..self.p.checked_add(n)?)?;
+ self.p += n;
+ Some(s)
+ }
+ fn u8(&mut self) -> Option<u8> {
+ self.take(1).map(|b| b[0])
+ }
+ fn u16(&mut self) -> Option<u16> {
+ self.take(2).map(|b| u16::from_be_bytes([b[0], b[1]]))
+ }
+ fn u32(&mut self) -> Option<u32> {
+ self.take(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
+ }
+ fn i32(&mut self) -> Option<i32> {
+ self.u32().map(|v| v as i32)
+ }
+ fn pascal(&mut self) -> Option<String> {
+ let n = usize::from(self.u8()?);
+ let s = self.take(n)?;
+ if (n + 1) % 2 == 1 {
+ self.take(1)?;
+ }
+ Some(s.iter().map(|&c| c as char).collect())
+ }
+}
+
+fn pascal(out: &mut Vec<u8>, s: &str) {
+ let bytes: Vec<u8> = s.chars().map(|c| if (c as u32) < 256 { c as u32 as u8 } else { b'?' }).take(255).collect();
+ out.push(bytes.len() as u8);
+ out.extend_from_slice(&bytes);
+ if (bytes.len() + 1) % 2 == 1 {
+ out.push(0);
+ }
+}
+
+/// PSD colour struct (space + 4 × u16) → RGB.
+fn color_from(space: u16, c: [u16; 4]) -> Color {
+ let f = |v: u16| f32::from(v) / 65535.0;
+ match space {
+ // HSB: hue 0–65535 maps to 0–360°.
+ 1 => {
+ let (h, s, v) = (f(c[0]) * 6.0, f(c[1]), f(c[2]));
+ let i = (h.floor() as i32).rem_euclid(6);
+ let fr = h - h.floor();
+ let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * fr), v * (1.0 - s * (1.0 - fr)));
+ let (r, g, b) = match i {
+ 0 => (v, t, p),
+ 1 => (q, v, p),
+ 2 => (p, v, t),
+ 3 => (p, q, v),
+ 4 => (t, p, v),
+ _ => (v, p, q),
+ };
+ Color::rgb(r, g, b)
+ }
+ // CMYK (inverted: 0 = 100 % ink), naive.
+ 2 => {
+ let k = 1.0 - f(c[3]);
+ Color::rgb(f(c[0]) * (1.0 - k), f(c[1]) * (1.0 - k), f(c[2]) * (1.0 - k))
+ }
+ // Grayscale 0–10000.
+ 8 => {
+ let g = 1.0 - (f32::from(c[0]) / 10000.0).clamp(0.0, 1.0);
+ Color::rgb(g, g, g)
+ }
+ _ => Color::rgb(f(c[0]), f(c[1]), f(c[2])),
+ }
+}
+
+fn decode_text(data: &[u8]) -> String {
+ let s = if data.len() >= 2 && data[0] == 0xFE && data[1] == 0xFF {
+ let units: Vec<u16> = data[2..].chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
+ String::from_utf16_lossy(&units)
+ } else {
+ data.iter().map(|&c| c as char).collect()
+ };
+ s.trim_end_matches('\0').replace("\r\n", "\n").replace('\r', "\n")
+}
+
+fn encode_text(s: &str) -> Vec<u8> {
+ let mut out = vec![0xFE, 0xFF];
+ for u in s.replace("\r\n", "\n").replace('\n', "\r").encode_utf16() {
+ out.extend_from_slice(&u.to_be_bytes());
+ }
+ out
+}
+
+/// One parsed `Anno` entry: a note, or a raw entry we keep (sound annotations).
+enum Entry {
+ Text(Note),
+ Raw(Vec<u8>),
+}
+
+fn parse_entries(data: &[u8]) -> Option<Vec<Entry>> {
+ let mut r = Reader { d: data, p: 0 };
+ let (_major, _minor) = (r.u16()?, r.u16()?);
+ let count = r.u32()? as usize;
+ let mut out = Vec::with_capacity(count.min(4096));
+ for _ in 0..count {
+ let start = r.p;
+ let len = r.u32()? as usize;
+ let end = start.checked_add(len)?;
+ let raw = data.get(start..end)?;
+ let kind = r.take(4)?;
+ if kind != b"txtA" {
+ out.push(Entry::Raw(raw.to_vec()));
+ r.p = end;
+ continue;
+ }
+ let open = r.u8()? != 0;
+ let (_flags, _opt) = (r.u8()?, r.u16()?);
+ let icon = [r.i32()?, r.i32()?, r.i32()?, r.i32()?];
+ let popup = [r.i32()?, r.i32()?, r.i32()?, r.i32()?];
+ let space = r.u16()?;
+ let c = [r.u16()?, r.u16()?, r.u16()?, r.u16()?];
+ let author = r.pascal()?;
+ let _name = r.pascal()?;
+ let modified = r.pascal()?;
+ let _data_len = r.u32()?;
+ let _key = r.take(4)?;
+ let n = r.u32()? as usize;
+ let text = decode_text(r.take(n)?);
+ out.push(Entry::Text(Note {
+ author,
+ color: color_from(space, c),
+ text,
+ position: [f64::from(icon[1]), f64::from(icon[0])],
+ popup: [f64::from(popup[1]), f64::from(popup[0]), f64::from(popup[3]), f64::from(popup[2])],
+ open,
+ modified,
+ }));
+ r.p = end;
+ }
+ Some(out)
+}
+
+/// Notes in an `Anno` block (None when it doesn't parse).
+pub fn parse_anno(data: &[u8]) -> Option<Vec<Note>> {
+ Some(parse_entries(data)?.into_iter().filter_map(|e| if let Entry::Text(n) = e { Some(n) } else { None }).collect())
+}
+
+fn write_note(n: &Note) -> Vec<u8> {
+ let mut b = Vec::new();
+ b.extend_from_slice(b"txtA");
+ b.push(u8::from(n.open));
+ b.push(0x1C);
+ b.extend_from_slice(&1u16.to_be_bytes());
+ let (x, y) = (n.position[0].round() as i32, n.position[1].round() as i32);
+ for v in [y, x, y + 20, x + 16] {
+ b.extend_from_slice(&v.to_be_bytes());
+ }
+ let pp = if n.popup == [0.0; 4] { [n.position[0] + 20.0, n.position[1] + 20.0, n.position[0] + 260.0, n.position[1] + 160.0] } else { n.popup };
+ for v in [pp[1], pp[0], pp[3], pp[2]] {
+ b.extend_from_slice(&(v.round() as i32).to_be_bytes());
+ }
+ b.extend_from_slice(&0u16.to_be_bytes());
+ let rgb = n.color.to_rgb();
+ for v in rgb {
+ b.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_be_bytes());
+ }
+ b.extend_from_slice(&0u16.to_be_bytes());
+ pascal(&mut b, &n.author);
+ pascal(&mut b, "");
+ pascal(&mut b, &n.modified);
+ let text = encode_text(&n.text);
+ b.extend_from_slice(&((text.len() + 12) as u32).to_be_bytes());
+ b.extend_from_slice(b"txtC");
+ b.extend_from_slice(&(text.len() as u32).to_be_bytes());
+ b.extend_from_slice(&text);
+ let mut out = ((b.len() + 4) as u32).to_be_bytes().to_vec();
+ out.extend_from_slice(&b);
+ out
+}
+
+/// An `Anno` block holding `notes` (plus raw sound entries carried over).
+pub fn write_anno(notes: &[Note], raw_extra: &[Vec<u8>]) -> Vec<u8> {
+ let mut out = Vec::new();
+ out.extend_from_slice(&2u16.to_be_bytes());
+ out.extend_from_slice(&1u16.to_be_bytes());
+ out.extend_from_slice(&((notes.len() + raw_extra.len()) as u32).to_be_bytes());
+ for n in notes {
+ out.extend_from_slice(&write_note(n));
+ }
+ for r in raw_extra {
+ out.extend_from_slice(r);
+ }
+ out
+}
+
+/// The document's notes from its raw global blocks (empty when there is no `Anno` block).
+pub fn notes_from_blocks(doc: &Document) -> Vec<Note> {
+ doc.metadata.psd_global_blocks.iter().find(|(_, k, _)| *k == ANNO).and_then(|(_, _, d)| parse_anno(d)).unwrap_or_default()
+}
+
+/// Global blocks to write: the raw `Anno` block while it still describes `doc.notes`, else a
+/// regenerated one in its place (appended when new, dropped when the last note is deleted).
+pub fn export_blocks(doc: &Document, mut blocks: Vec<photocraft_doc::PsdGlobalBlock>) -> Vec<photocraft_doc::PsdGlobalBlock> {
+ let at = blocks.iter().position(|(_, k, _)| *k == ANNO);
+ let raw = at.map(|i| blocks[i].2.clone());
+ let entries = raw.as_deref().and_then(|d| parse_entries(d));
+ let parsed: Option<Vec<Note>> = entries.as_ref().map(|e| e.iter().filter_map(|e| if let Entry::Text(n) = e { Some(n.clone()) } else { None }).collect());
+ // Compare in stored precision (colours are 16-bit, positions whole pixels, empty popups get a
+ // default rectangle).
+ let want = parse_anno(&write_anno(&doc.notes, &[]));
+ let same = |a: &[Note], b: &[Note]| {
+ a.len() == b.len()
+ && a.iter().zip(b).all(|(x, y)| {
+ let (cx, cy) = (x.color.to_rgb(), y.color.to_rgb());
+ Note { color: y.color, ..x.clone() } == *y && cx.iter().zip(cy).all(|(p, q)| (p - q).abs() < 1.0 / 512.0)
+ })
+ };
+ if parsed.as_deref().zip(want.as_deref()).is_some_and(|(p, w)| same(p, w)) || (raw.is_none() && doc.notes.is_empty()) {
+ return blocks;
+ }
+ let extra: Vec<Vec<u8>> = entries.unwrap_or_default().into_iter().filter_map(|e| if let Entry::Raw(r) = e { Some(r) } else { None }).collect();
+ let fresh = (!doc.notes.is_empty() || !extra.is_empty()).then(|| Arc::new(write_anno(&doc.notes, &extra)));
+ match (at, fresh) {
+ (Some(i), Some(f)) => blocks[i].2 = f,
+ (Some(i), None) => {
+ blocks.remove(i);
+ }
+ (None, Some(f)) => blocks.push((*b"8BIM", ANNO, f)),
+ (None, None) => {}
+ }
+ blocks
+}
+
+fn num(v: &Value) -> Option<f64> {
+ match v {
+ Value::Double(d) => Some(*d),
+ Value::Integer(i) => Some(f64::from(*i)),
+ Value::LargeInteger(i) => Some(*i as f64),
+ Value::UnitFloat { value, .. } => Some(*value),
+ _ => None,
+ }
+}
+
+fn find<'a>(d: &'a Descriptor, keys: &[&str]) -> Option<&'a Value> {
+ keys.iter().find_map(|k| d.get(k)).or_else(|| {
+ // The scale may be nested one object deep (`measurementScale` object).
+ d.items.iter().find_map(|(_, v)| if let Value::Descriptor(o) = v { keys.iter().find_map(|k| o.get(k)) } else { None })
+ })
+}
+
+/// Measurement scale described by resource 1074 (None when it doesn't parse).
+pub fn scale_from_resource(data: &[u8]) -> Option<MeasurementScale> {
+ let d = VersionedDescriptor::parse_prefix(data).ok()?.0.descriptor;
+ let pixel_length = find(&d, &["pixelLength", "PxlL"]).and_then(num)?;
+ let logical_length = find(&d, &["logicalLength", "LglL"]).and_then(num)?;
+ let units = match find(&d, &["logicalUnits", "LglU"]) {
+ Some(Value::Text(t)) => t.to_string_lossy(),
+ _ => "pixels".into(),
+ };
+ Some(MeasurementScale { pixel_length, logical_length, units })
+}
+
+/// Resource 1074 data for a scale.
+pub fn write_scale_resource(s: &MeasurementScale) -> Vec<u8> {
+ let d = Descriptor::new("null")
+ .with("pixelLength", Value::Double(s.pixel_length))
+ .with("logicalLength", Value::Double(s.logical_length))
+ .with("logicalUnits", Value::Text(photocraft_psd::descriptor::UnicodeString::new(&s.units)));
+ let mut v = VersionedDescriptor::new(d).to_bytes();
+ if v.len() % 2 == 1 {
+ v.push(0);
+ }
+ v
+}
+
+/// The measurement scale a document's preserved resource 1074 holds (the default when absent).
+pub fn raw_scale(doc: &Document) -> Option<MeasurementScale> {
+ let raw = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == MEASUREMENT_SCALE)?;
+ scale_from_resource(&raw.2)
+}
+
+/// Whether the preserved resource 1074 may be written as is: it still describes the document's
+/// scale (or doesn't parse and the scale was never changed from the default).
+pub fn keep_raw_scale(doc: &Document) -> bool {
+ match raw_scale(doc) {
+ Some(s) => s == doc.measurement.scale,
+ None => doc.measurement.scale.is_default(),
+ }
+}
+
+/// Resource 1074 to write when the preserved one can't be used (None = write nothing).
+pub fn fresh_scale_resource(doc: &Document) -> Option<Vec<u8>> {
+ let has_raw = doc.metadata.psd_resources.iter().any(|(id, _, _)| *id == MEASUREMENT_SCALE);
+ if has_raw && keep_raw_scale(doc) {
+ return None;
+ }
+ (!doc.measurement.scale.is_default()).then(|| write_scale_resource(&doc.measurement.scale))
+}
+
+/// Whether to keep a preserved resource with this id on export.
+pub fn keep_resource(doc: &Document, id: u16) -> bool {
+ match id {
+ MEASUREMENT_SCALE => keep_raw_scale(doc),
+ // Our count markers can't be written into Photoshop's (unpublished) layout; a stale copy
+ // would contradict them, so it is dropped once the document has markers of its own.
+ COUNT_INFO => doc.measurement.count_total() == 0,
+ _ => true,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SAMPLE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../corpus/psd/ag-psd/read-write/annotations/src.psd");
+
+ fn anno_of(bytes: &[u8]) -> Option<Vec<u8>> {
+ let i = bytes.windows(8).position(|w| w == b"8BIMAnno")?;
+ let n = u32::from_be_bytes(bytes[i + 8..i + 12].try_into().ok()?) as usize;
+ Some(bytes[i + 12..i + 12 + n].to_vec())
+ }
+
+ #[test]
+ fn parses_and_rewrites_the_sample_byte_exact() {
+ let Ok(file) = std::fs::read(SAMPLE) else { return };
+ let raw = anno_of(&file).unwrap();
+ let notes = parse_anno(&raw).unwrap();
+ assert_eq!(notes.len(), 2);
+ assert_eq!(notes[0].author, "someone");
+ assert_eq!(notes[0].text, "Example annotation\nis here\n\n~ annotator\n");
+ assert_eq!(notes[0].position, [42.0, 28.0]);
+ assert_eq!(notes[0].popup, [92.0, 74.0, 332.0, 214.0]);
+ assert_eq!(notes[0].modified, "D:20210521231029+01'00'");
+ assert!(notes[0].open);
+ // Second note's colour is stored as HSB.
+ assert_eq!(notes[1].author, "some author");
+ assert_eq!(notes[1].text, "open note");
+ let rgb = notes[1].color.to_rgb();
+ // Hue 343°, saturation 0.49, brightness 1: pink.
+ assert!(rgb[0] > 0.99 && rgb[1] < rgb[2] && rgb[2] < 0.7, "{rgb:?}");
+ // Text, positions, flags and RGB colours are rewritten exactly.
+ let again = write_anno(&notes[..1], &[]);
+ assert_eq!(parse_anno(&again).unwrap()[..], notes[..1]);
+ let n0 = 8 + u32::from_be_bytes(raw[8..12].try_into().unwrap()) as usize;
+ assert_eq!(&again[8..], &raw[8..n0]);
+ }
+
+ #[test]
+ fn export_blocks_keeps_replaces_and_drops() {
+ let mut d = Document::new("n", photocraft_doc::Size::new(10, 10), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
+ assert!(export_blocks(&d, vec![]).is_empty());
+ d.notes.push(Note { text: "héllo ✓".into(), author: "me".into(), position: [3.0, 4.0], ..Default::default() });
+ let out = export_blocks(&d, vec![]);
+ assert_eq!(out.len(), 1);
+ assert_eq!(parse_anno(&out[0].2).unwrap()[0].text, "héllo ✓");
+ // Unchanged → the very same bytes.
+ d.metadata.psd_global_blocks = out.clone();
+ assert!(Arc::ptr_eq(&export_blocks(&d, out.clone())[0].2, &out[0].2));
+ d.notes.clear();
+ assert!(export_blocks(&d, out).is_empty());
+ assert!(parse_anno(&[0, 2, 0, 1, 0, 0, 0, 9]).is_none());
+ }
+
+ #[test]
+ fn scale_resource_roundtrip_and_keep_rules() {
+ let s = MeasurementScale { pixel_length: 150.0, logical_length: 2.0, units: "mm".into() };
+ assert_eq!(scale_from_resource(&write_scale_resource(&s)), Some(s.clone()));
+ let mut d = Document::new("n", photocraft_doc::Size::new(10, 10), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
+ assert!(fresh_scale_resource(&d).is_none());
+ // An unparseable resource stays while the scale is untouched.
+ d.metadata.psd_resources.push((MEASUREMENT_SCALE, String::new(), Arc::new(vec![0, 0, 0, 16, 1])));
+ assert!(keep_resource(&d, MEASUREMENT_SCALE) && fresh_scale_resource(&d).is_none());
+ d.measurement.scale = s.clone();
+ assert!(!keep_resource(&d, MEASUREMENT_SCALE));
+ assert_eq!(scale_from_resource(&fresh_scale_resource(&d).unwrap()), Some(s));
+ assert!(keep_resource(&d, COUNT_INFO));
+ d.measurement.count_groups.push(photocraft_doc::CountGroup { points: vec![[1.0, 1.0]], ..Default::default() });
+ assert!(!keep_resource(&d, COUNT_INFO));
+ }
+}
diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs
index 9eae02e87..724aeb33a 100644
--- a/crates/io/src/blocks.rs
+++ b/crates/io/src/blocks.rs
@@ -6,6 +6,17 @@ use photocraft_doc::{Fill, GradientStyle, LabelColor, Locks};
use photocraft_geom::Affine;
use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor};
+/// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of
+/// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored).
+pub fn parse_brst(data: &[u8]) -> u32 {
+ data.chunks_exact(4).map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).filter(|&i| i < 32).fold(0, |m, i| m | 1 << i)
+}
+
+/// Inverse of [`parse_brst`]; `None` when every channel blends (no block).
+pub fn brst_data(mask: u32) -> Option<Vec<u8>> {
+ (mask != 0).then(|| (0..32u32).filter(|i| mask & 1 << i != 0).flat_map(u32::to_be_bytes).collect())
+}
+
/// `lspf` bits (Adobe spec: bit 0 transparency, 1 composite, 2 position).
/// Artboard (bit 3... here `0x10` as observed by ag-psd) and "all" (bit 31)
/// are undocumented.
@@ -406,6 +417,14 @@ pub fn effects_enabled(lfx2: &[u8]) -> bool {
#[cfg(test)]
mod tests {
+ #[test]
+ fn brst_round_trip() {
+ assert_eq!(super::parse_brst(&[0, 0, 0, 2]), 0b100);
+ assert_eq!(super::parse_brst(&[0, 0, 0, 0, 0, 0, 0, 1]), 0b11);
+ assert_eq!(super::brst_data(0b101).unwrap(), vec![0, 0, 0, 0, 0, 0, 0, 2]);
+ assert_eq!(super::brst_data(0), None);
+ }
+
use super::*;
#[test]
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 6268b0850..c66a2ae81 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -18,17 +18,21 @@
#![forbid(unsafe_code)]
mod adjust_map;
+pub mod annotations_map;
mod channel_map;
pub mod comps_map;
pub mod effects_map;
pub mod blocks;
mod gradient_bake;
mod flat;
+mod multichannel_map;
pub mod linked;
pub mod pattern_map;
mod pixels;
mod psd_export;
mod psd_import;
+pub mod slices_map;
+pub mod text_styles_map;
pub mod vector_map;
use photocraft_codecs::{CodecError, EncodeOptions};
diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs
new file mode 100644
index 000000000..e70624c8b
--- /dev/null
+++ b/crates/io/src/multichannel_map.rs
@@ -0,0 +1,117 @@
+//! Multichannel documents <-> PSD colour mode 7.
+//!
+//! A Multichannel document has no layers: its image is a set of ink (spot) channels, stored in
+//! [`Document::channels`] with ink density as the value (1 = solid ink, like every spot channel).
+//! A PSD stores the same planes the way Photoshop shows them in the Channels panel: 0 (black) =
+//! solid ink, max = paper. Channel names come from resources 1006 / 1045 and ink colours from
+//! DisplayInfo (1077), exactly as for spot channels in the other modes.
+
+use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{AlphaChannel, Document};
+use photocraft_geom::Rect;
+use photocraft_psd::file::LayerInfoPlacement;
+use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource};
+use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile, Version};
+use photocraft_raster::Surface;
+
+use crate::pixels::{encode_be, psd_depth};
+
+/// Value of sample `i` of a big-endian plane.
+fn decode(plane: &[u8], i: usize, s: SampleType) -> f32 {
+ match s {
+ SampleType::U8 => f32::from(plane[i]) / 255.0,
+ SampleType::U16 => f32::from(u16::from_be_bytes([plane[2 * i], plane[2 * i + 1]])) / 65535.0,
+ SampleType::F32 => f32::from_be_bytes([plane[4 * i], plane[4 * i + 1], plane[4 * i + 2], plane[4 * i + 3]]),
+ }
+}
+
+/// Fills `doc` (already in Multichannel mode at the file depth) from the merged planes `all`.
+pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[String], warnings: &mut Vec<String>) {
+ let h = &file.header;
+ let depth = doc.depth;
+ let (w, hh) = (h.width as usize, h.height as usize);
+ let n = w * hh;
+ let plane = h.row_bytes() * hh;
+ let canvas = Rect::new(0, 0, h.width as i32, h.height as i32);
+ let fmt = PixelFormat::new(ColorMode::Grayscale, depth, false);
+ for k in 0..usize::from(h.channels) {
+ let Some(p) = all.get(k * plane..(k + 1) * plane) else {
+ warnings.push(format!("multichannel: channel {} is missing", k + 1));
+ break;
+ };
+ let vals: Vec<f32> = (0..n).map(|i| 1.0 - decode(p, i, depth)).collect();
+ let mut s = Surface::new(fmt);
+ s.write_region(canvas, &vals);
+ s.prune();
+ let name = names.get(k).cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Channel {}", k + 1));
+ // Without DisplayInfo the channels print in black, as Photoshop shows them.
+ doc.channels.push(AlphaChannel { spot: Some((Color::BLACK, 0.0)), ..AlphaChannel::new(name, s) });
+ }
+ if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) {
+ crate::channel_map::apply_display_info(&r.data, true, &mut doc.channels);
+ } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) {
+ crate::channel_map::apply_display_info(&r.data, false, &mut doc.channels);
+ }
+}
+
+/// Writes a Multichannel document as a mode-7 PSD (no layer section; every channel a plane).
+pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec<String>) {
+ let mut warnings = Vec::new();
+ // Photoshop's Multichannel mode is 8 or 16 bits per channel.
+ let sample = match doc.depth {
+ SampleType::F32 => {
+ warnings.push("32-bit Multichannel written as 16 bits/channel (Photoshop has no 32-bit Multichannel)".into());
+ SampleType::U16
+ }
+ s => s,
+ };
+ if !doc.layers.is_empty() {
+ warnings.push("Multichannel documents have no layers: the layers were not written".into());
+ }
+ let canvas = doc.bounds();
+ let channels: Vec<&AlphaChannel> = doc.channels.iter().take(56).collect();
+ if doc.channels.len() > 56 {
+ warnings.push("only 56 channels fit in PSD; the rest were dropped".into());
+ }
+ let mut planes = Vec::new();
+ if channels.is_empty() {
+ // A PSD needs at least one channel: an empty (paper) plane.
+ for _ in 0..canvas.width() as usize * canvas.height() as usize {
+ encode_be(1.0, sample, &mut planes);
+ }
+ }
+ for ch in &channels {
+ for v in ch.surface.read_region(canvas).chunks_exact(ch.surface.channels()) {
+ encode_be(1.0 - v[0], sample, &mut planes);
+ }
+ }
+ let big = doc.size.width > 30_000 || doc.size.height > 30_000;
+ let version = if force_psb || big { Version::Psb } else { Version::Psd };
+ let header = Header::new(version, doc.size.width, doc.size.height, channels.len().max(1) as u16, psd_depth(sample), PsdMode::Multichannel);
+ let image_data = ImageData::encode(Compression::Rle, &planes, &header)
+ .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header))
+ .unwrap_or(ImageData { compression: Compression::Raw, data: planes });
+ let mut resources = vec![ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes())];
+ if !channels.is_empty() {
+ let names: Vec<&str> = channels.iter().map(|c| c.name.as_str()).collect();
+ resources.push(ImageResource::new(1006, crate::psd_export::pascal_names_resource(&names)));
+ resources.push(ImageResource::new(1045, crate::psd_export::unicode_names_resource(&names)));
+ resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&channels)));
+ }
+ if let Some(x) = &doc.metadata.xmp {
+ resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec()));
+ }
+ resources.push(version_info_resource(true));
+ let file = PsdFile {
+ header,
+ color_mode_data: Vec::new(),
+ resources,
+ layer_info: None,
+ layer_info_placement: LayerInfoPlacement::Section,
+ global_layer_mask: None,
+ global_blocks: Vec::new(),
+ layer_mask_trailing: Vec::new(),
+ image_data,
+ };
+ (file, warnings)
+}
diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs
index a8929a860..4c36d2219 100644
--- a/crates/io/src/psd_export.rs
+++ b/crates/io/src/psd_export.rs
@@ -28,6 +28,8 @@ struct Ex {
fmt: PixelFormat,
/// Document resolution (for generated type-layer data).
dpi: f32,
+ /// Character/paragraph styles written into every type layer's engine data.
+ text_styles: photocraft_doc::TextStyles,
mask_fmt: PixelFormat,
cc: usize,
cmyk: bool,
@@ -262,7 +264,10 @@ impl Ex {
LayerContent::Text(t) => {
// Text layers without PSD data (created here) get a generated TySh.
let generated = t.psd_raw.is_none().then(|| std::sync::Arc::new(photocraft_text::psd::build_tysh(t, self.dpi, None)));
- set_principal(&mut raw, &[b"TySh"], t.psd_raw.as_ref().or(generated.as_ref()));
+ let src = t.psd_raw.as_ref().or(generated.as_ref());
+ // Character/paragraph style sheets from the document's styles.
+ let styled = src.and_then(|d| crate::text_styles_map::export_tysh(d, t, &self.text_styles, self.dpi)).map(std::sync::Arc::new);
+ set_principal(&mut raw, &[b"TySh"], styled.as_ref().or(src));
if !raw.iter().any(|(k, _)| k == b"TySh") {
self.warnings.push(format!("layer \"{}\": text layer written as pixels (no TySh data)", l.name));
}
@@ -286,6 +291,14 @@ impl Ex {
}
None => raw.retain(|(k, _)| k != b"fxrp"),
}
+ // Advanced Blending channel restrictions: written from the field (in place).
+ match crate::blocks::brst_data(l.excluded_channels) {
+ Some(data) => match raw.iter_mut().find(|(k, _)| k == b"brst") {
+ Some(e) => e.1 = data,
+ None => raw.push((*b"brst", data)),
+ },
+ None => raw.retain(|(k, _)| k != b"brst"),
+ }
if !matches!(l.content, LayerContent::Shape(_)) {
self.vector_mask_block(l, &mut raw);
}
@@ -439,7 +452,7 @@ fn legacy_name(s: &str) -> Vec<u8> {
s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect()
}
-fn unicode_names_resource(names: &[&str]) -> Vec<u8> {
+pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec<u8> {
let mut v = Vec::new();
for n in names {
let units: Vec<u16> = n.encode_utf16().chain(std::iter::once(0)).collect();
@@ -451,7 +464,7 @@ fn unicode_names_resource(names: &[&str]) -> Vec<u8> {
v
}
-fn pascal_names_resource(names: &[&str]) -> Vec<u8> {
+pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec<u8> {
let mut v = Vec::new();
for n in names {
let b = legacy_name(n);
@@ -486,6 +499,9 @@ pub fn document_to_psd(doc: &Document) -> PsdFile {
/// anything that could not be represented. The merged composite is rendered
/// with `photocraft_compose::flatten`.
pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec<String>) {
+ if doc.mode == ColorMode::Multichannel {
+ return crate::multichannel_map::document_to_psd(doc, opts.force_psb);
+ }
let fmt = doc.pixel_format();
let sample = fmt.sample;
let cc = fmt.mode.color_channels();
@@ -494,6 +510,7 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
let mut ex = Ex {
fmt,
dpi: doc.resolution_dpi,
+ text_styles: doc.text_styles.clone(),
mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false),
cc,
cmyk: fmt.mode == ColorMode::Cmyk,
@@ -657,17 +674,26 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
resources.push(ImageResource::new(ids::EXIF, e.to_vec()));
}
let mut global_blocks = Vec::new();
- for (sig, key, data) in &crate::pattern_map::export_global_blocks(doc) {
+ for (sig, key, data) in &crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc)) {
let mut tb = TaggedBlock::new(*key, data.to_vec());
tb.signature = *sig;
global_blocks.push(tb);
}
let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc));
+ let slices_resource = crate::slices_map::export_resource(doc, &ex.layer_ids);
for (id, name, data) in &doc.metadata.psd_resources {
// Layer comps: the preserved list while unchanged, else regenerated (or dropped) below.
if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() {
continue;
}
+ // Slices: the preserved resource while unchanged, else regenerated (or dropped) below.
+ if *id == crate::slices_map::SLICES && slices_resource.is_some() {
+ continue;
+ }
+ // Measurement scale / count resources: only while they still describe the document.
+ if !crate::annotations_map::keep_resource(doc, *id) {
+ continue;
+ }
// A preserved clipping-path resource is only valid while it names the current one.
if *id == crate::vector_map::CLIPPING_PATH {
let n = usize::from(data.first().copied().unwrap_or(0));
@@ -680,9 +706,15 @@ pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile
r.name = legacy_name(name);
resources.push(r);
}
+ if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) {
+ resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data));
+ }
if let Some(Some(data)) = comps_resource {
resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data));
}
+ if let Some(Some(data)) = slices_resource {
+ resources.push(ImageResource::new(crate::slices_map::SLICES, data));
+ }
resources.push(version_info_resource(true));
let has_layers = !ex.records.is_empty();
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 407f5b5e6..b8a462bab 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -186,6 +186,11 @@ impl Ctx<'_> {
let f = |s: &[u8]| f64::from_be_bytes(s.try_into().unwrap_or([0; 8]));
l.effects.reference = Some((f(x), f(y)));
}
+ // Advanced Blending channel restrictions (`brst`: the u32 ids of channels left out);
+ // also kept in `psd_blocks`, where export rewrites it from the field.
+ if let Some(b) = rec.block(b"brst") {
+ l.excluded_channels = crate::blocks::parse_brst(&b.data);
+ }
l.psd_id = rec.layer_id();
let name = l.name.clone();
l.mask = self.record_mask(rec, &name);
@@ -376,7 +381,8 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
ColorMode::Rgb
});
let layered = matches!(mode, ColorMode::Grayscale | ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab) && h.depth != 1;
- let depth = if layered { sample_for_depth(h.depth) } else { SampleType::U8 };
+ let multichannel = mode == ColorMode::Multichannel && h.depth != 1;
+ let depth = if layered || multichannel { sample_for_depth(h.depth) } else { SampleType::U8 };
let mut doc = Document::new("Untitled", Size::new(h.width, h.height), mode, depth);
// Resources.
@@ -430,6 +436,11 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone())));
}
doc.patterns = crate::pattern_map::from_global_blocks(&doc);
+ // Notes (`Anno`) and the measurement scale (resource 1074); raw data stays for verbatim export.
+ doc.notes = crate::annotations_map::notes_from_blocks(&doc);
+ if let Some(scale) = crate::annotations_map::raw_scale(&doc) {
+ doc.measurement.scale = scale;
+ }
let fmt = doc.pixel_format();
let cc = fmt.mode.color_channels();
@@ -451,7 +462,16 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
cx.warn(format!("merged image could not be decoded: {e}"));
}
- if layered {
+ if multichannel {
+ // Ink channels only (no layers); see `multichannel_map`.
+ if let Ok(all) = &merged {
+ let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default();
+ crate::multichannel_map::import(file, all, &mut doc, &names, &mut cx.warnings);
+ }
+ if !file.layers().is_empty() {
+ cx.warn(format!("Multichannel documents have no layers: {} layer records were not imported", file.layers().len()));
+ }
+ } else if layered {
let tree = file.layer_tree();
doc.layers = cx.build(&tree);
// Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked).
@@ -580,6 +600,10 @@ pub fn psd_to_document(file: &PsdFile) -> (Document, Vec<String>) {
// Layer comps (resource 1065 + per-layer `cmls`); the raw data stays for verbatim export.
let raw_comps = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == crate::comps_map::LAYER_COMPS).map(|(_, _, d)| d.clone());
(doc.layer_comps, doc.last_applied_comp, doc.last_document_state) = crate::comps_map::comps_from_psd(raw_comps.as_deref().map(Vec::as_slice), &doc);
+ // Slices (resource 1050), after layer ids are known; the raw data stays for verbatim export.
+ crate::slices_map::import(&mut doc);
+ // Character and paragraph styles from the type layers' engine data.
+ crate::text_styles_map::import(&mut doc);
(doc, cx.warnings)
}
diff --git a/crates/io/src/slices_map.rs b/crates/io/src/slices_map.rs
new file mode 100644
index 000000000..fe512a24b
--- /dev/null
+++ b/crates/io/src/slices_map.rs
@@ -0,0 +1,140 @@
+//! Document slices ↔ PSD resource 1050 (see `photocraft_psd::slices`).
+//!
+//! Import keeps user and layer-based slices (auto slices are regenerated from them) and links
+//! layer-based slices to the layer whose `lyid` they name. Export writes the preserved resource
+//! byte-for-byte while the slices are unchanged, else a fresh version 6 resource that also lists
+//! the current auto slices, as Photoshop saves them.
+
+use std::collections::HashMap;
+
+use photocraft_doc::slices::{self, Slice, SliceKind, SliceOrigin, Slices};
+use photocraft_doc::{Document, LayerId, Rect};
+use photocraft_psd::slices::{SliceRecord, SlicesResource};
+
+/// Image resource id of the slices.
+pub const SLICES: u16 = photocraft_psd::slices::SLICES;
+
+fn raw(doc: &Document) -> Option<&[u8]> {
+ doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == SLICES).map(|(_, _, d)| d.as_slice())
+}
+
+/// The document's slices from the raw resource (None or unreadable = no slices).
+pub fn slices_from_psd(raw: Option<&[u8]>, doc: &Document) -> Slices {
+ let Some(res) = raw.and_then(|r| SlicesResource::from_bytes(r).ok()) else { return Slices::default() };
+ let by_psd_id: HashMap<u32, LayerId> = doc.walk().into_iter().filter_map(|(_, _, l)| l.psd_id.map(|p| (p, l.id))).collect();
+ let list = res
+ .slices
+ .iter()
+ .filter(|s| s.origin != 0)
+ .map(|s| {
+ let layer = s.layer_id.and_then(|p| by_psd_id.get(&p).copied()).filter(|_| s.origin == 1);
+ Slice {
+ id: s.id,
+ group_id: s.group_id,
+ // A layer-based slice whose layer is gone keeps its rect as a user slice.
+ origin: if s.origin == 1 && layer.is_some() { SliceOrigin::Layer } else { SliceOrigin::User },
+ layer,
+ name: s.name.clone(),
+ rect: Rect::new(s.rect[0], s.rect[1], s.rect[2], s.rect[3]),
+ kind: SliceKind::from_code(s.kind),
+ url: s.url.clone(),
+ target: s.target.clone(),
+ message: s.message.clone(),
+ alt: s.alt.clone(),
+ cell_text_is_html: s.cell_text_is_html,
+ cell_text: s.cell_text.clone(),
+ horizontal_align: s.horizontal_align,
+ vertical_align: s.vertical_align,
+ background: (s.color[0] != 0).then_some(s.color),
+ outsets: s.outsets,
+ }
+ })
+ .collect();
+ Slices { group_name: res.group_name, list }
+}
+
+/// Sets `doc.slices` from its preserved resource (called after layers and ids are imported).
+pub fn import(doc: &mut Document) {
+ doc.slices = slices_from_psd(raw(doc), doc);
+}
+
+/// Do the document's slices still match the preserved resource?
+pub fn unchanged(doc: &Document) -> bool {
+ slices_from_psd(raw(doc), doc) == doc.slices
+}
+
+/// The resource to write: `None` keeps the preserved one, `Some(None)` drops it, `Some(Some)` is
+/// a fresh resource. `layer_ids` maps document layers to the PSD layer ids being written.
+pub fn export_resource(doc: &Document, layer_ids: &HashMap<LayerId, u32>) -> Option<Option<Vec<u8>>> {
+ if unchanged(doc) {
+ return None;
+ }
+ if doc.slices.is_empty() {
+ return Some(None);
+ }
+ let mut records: Vec<SliceRecord> = doc
+ .slices
+ .list
+ .iter()
+ .map(|s| SliceRecord {
+ id: s.id,
+ group_id: s.group_id,
+ origin: s.origin.code(),
+ layer_id: s.layer.and_then(|l| layer_ids.get(&l).copied()),
+ name: s.name.clone(),
+ kind: s.kind.code(),
+ rect: [s.rect.x0, s.rect.y0, s.rect.x1, s.rect.y1],
+ url: s.url.clone(),
+ target: s.target.clone(),
+ message: s.message.clone(),
+ alt: s.alt.clone(),
+ cell_text_is_html: s.cell_text_is_html,
+ cell_text: s.cell_text.clone(),
+ horizontal_align: s.horizontal_align,
+ vertical_align: s.vertical_align,
+ color: s.background.unwrap_or([0; 4]),
+ outsets: s.outsets,
+ })
+ .map(|mut r| {
+ // A layer slice whose layer isn't written becomes a user slice.
+ if r.origin == 1 && r.layer_id.is_none() {
+ r.origin = 2;
+ }
+ r
+ })
+ .collect();
+ let taken: Vec<Rect> = doc.slices.list.iter().map(|s| s.rect).collect();
+ for (id, r) in (doc.slices.next_id()..).zip(slices::auto_slices(doc.bounds(), &taken)) {
+ records.push(SliceRecord { id, origin: 0, kind: 1, rect: [r.x0, r.y0, r.x1, r.y1], ..Default::default() });
+ }
+ let group_name = if doc.slices.group_name.is_empty() { slices::base_name(doc) } else { doc.slices.group_name.clone() };
+ let res = SlicesResource { version: 6, bounds: [0, 0, doc.size.height as i32, doc.size.width as i32], group_name, slices: records };
+ Some(Some(res.to_bytes()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::{ColorMode, Layer, SampleType, Size};
+
+ #[test]
+ fn slices_survive_a_psd_round_trip() {
+ let mut d = Document::new("site.psd", Size::new(120, 90), ColorMode::Rgb, SampleType::U8);
+ let mut l = Layer::raster("Logo", d.pixel_format());
+ l.psd_id = Some(5);
+ let lid = l.id;
+ d.layers.push(l);
+ d.slices.list.push(Slice { id: 1, name: "hero".into(), rect: Rect::new(10, 10, 60, 40), url: "https://example.org".into(), alt: "Hero".into(), ..Default::default() });
+ d.slices.list.push(Slice { id: 2, origin: SliceOrigin::Layer, layer: Some(lid), rect: Rect::new(70, 50, 100, 80), kind: SliceKind::NoImage, outsets: [1, 1, 1, 1], ..Default::default() });
+ let ids: HashMap<LayerId, u32> = [(lid, 5)].into_iter().collect();
+ let data = export_resource(&d, &ids).unwrap().unwrap();
+ // Read back into a copy of the document without slices.
+ let mut back = d.clone();
+ back.slices = Slices::default();
+ back.metadata.psd_resources.push((SLICES, String::new(), std::sync::Arc::new(data)));
+ import(&mut back);
+ assert_eq!(back.slices.list, d.slices.list);
+ assert!(unchanged(&back));
+ assert!(export_resource(&back, &ids).is_none(), "unchanged → keep the raw resource");
+ }
+}
diff --git a/crates/io/src/text_styles_map.rs b/crates/io/src/text_styles_map.rs
new file mode 100644
index 000000000..c14d28c5e
--- /dev/null
+++ b/crates/io/src/text_styles_map.rs
@@ -0,0 +1,74 @@
+//! Character and paragraph styles ⇄ the PSD text engine's style sheets (see
+//! `photocraft_text::psd_styles`). Import merges the named sheets of every type layer into the
+//! document's [`TextStyles`] by name and sets the runs' style references; export rewrites each
+//! type layer's sheets from the document's styles. Files without named styles are left as they
+//! are (byte-exact).
+
+use std::collections::HashMap;
+
+use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef, diff_attrs};
+use photocraft_doc::{Document, LayerContent, LayerId, TextLayer, TextStyles};
+
+/// Builds `doc.text_styles` from the type layers' engine data and links the runs.
+pub fn import(doc: &mut Document) {
+ let dpi = doc.resolution_dpi;
+ let mut styles = std::mem::take(&mut doc.text_styles);
+ let mut char_ids: HashMap<String, u32> = styles.character.iter().map(|d| (d.name.clone(), d.id)).collect();
+ let mut para_ids: HashMap<String, u32> = styles.paragraph.iter().map(|d| (d.name.clone(), d.id)).collect();
+ let ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();
+ for id in ids {
+ let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) else { continue };
+ let Some(raw) = t.psd_raw.clone() else { continue };
+ if !photocraft_text::psd_styles::has_named_sheets(&raw) {
+ continue;
+ }
+ let Some(sh) = photocraft_text::psd_styles::read_style_sheets(&raw, dpi) else { continue };
+ let mut cmap: HashMap<usize, u32> = HashMap::new();
+ for (ix, name, st) in &sh.char_sheets {
+ let id = *char_ids.entry(name.clone()).or_insert_with(|| {
+ let id = styles.next_char_id();
+ let mut attrs = diff_attrs(st, &sh.normal_char);
+ attrs.remove("postscript_name");
+ styles.character.push(CharacterStyleDef { id, name: name.clone(), attrs });
+ id
+ });
+ cmap.insert(*ix, id);
+ }
+ let mut pmap: HashMap<usize, u32> = HashMap::new();
+ for (ix, name, p, cs) in &sh.para_sheets {
+ let id = *para_ids.entry(name.clone()).or_insert_with(|| {
+ let id = styles.next_para_id();
+ let mut char_attrs = cs.as_ref().map(|c| diff_attrs(c, &sh.normal_char)).unwrap_or_default();
+ char_attrs.remove("postscript_name");
+ styles.paragraph.push(ParagraphStyleDef { id, name: name.clone(), para_attrs: diff_attrs(p, &sh.normal_para), char_attrs });
+ id
+ });
+ pmap.insert(*ix, id);
+ }
+ link(t, &sh.run_char, &cmap, &sh.run_para, &pmap);
+ }
+ doc.text_styles = styles;
+}
+
+fn link(t: &mut TextLayer, run_char: &[Option<usize>], cmap: &HashMap<usize, u32>, run_para: &[Option<usize>], pmap: &HashMap<usize, u32>) {
+ if t.runs.len() == run_char.len() {
+ for (r, ix) in t.runs.iter_mut().zip(run_char) {
+ r.style.style_sheet = ix.and_then(|i| cmap.get(&i).copied());
+ }
+ }
+ if t.paragraphs.len() == run_para.len() {
+ for (r, ix) in t.paragraphs.iter_mut().zip(run_para) {
+ r.style.style_sheet = ix.and_then(|i| pmap.get(&i).copied());
+ }
+ }
+}
+
+/// The `TySh` data to write for a type layer, with its style sheets regenerated from
+/// `styles`; None when neither the document nor the data has named styles (write as is).
+pub fn export_tysh(data: &[u8], t: &TextLayer, styles: &TextStyles, dpi: f32) -> Option<Vec<u8>> {
+ let named = !styles.character.is_empty() || !styles.paragraph.is_empty();
+ if !named && !photocraft_text::psd_styles::has_named_sheets(data) {
+ return None;
+ }
+ photocraft_text::psd_styles::write_style_sheets(data, t, styles, dpi)
+}
diff --git a/crates/io/tests/annotations.rs b/crates/io/tests/annotations.rs
new file mode 100644
index 000000000..9ca5cf250
--- /dev/null
+++ b/crates/io/tests/annotations.rs
@@ -0,0 +1,61 @@
+//! Notes (`Anno`) and the measurement scale (resource 1074) through PSD: verbatim while
+//! unchanged, regenerated after edits.
+
+use std::path::PathBuf;
+
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_doc::{Document, MeasurementScale, Note};
+use photocraft_geom::Size;
+use photocraft_io::annotations_map::MEASUREMENT_SCALE;
+use photocraft_io::{ExportOptions, export, import};
+use photocraft_psd::PsdFile;
+
+fn corpus(rel: &str) -> Option<Vec<u8>> {
+ std::fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd").join(rel)).ok()
+}
+
+fn to_psd(doc: &Document) -> Vec<u8> {
+ export(doc, "x.psd", &ExportOptions::default()).expect("export").bytes
+}
+
+#[test]
+fn corpus_notes_import_and_verbatim_export() {
+ let Some(bytes) = corpus("ag-psd/read-write/annotations/src.psd") else { return };
+ let src = PsdFile::from_bytes(&bytes).unwrap();
+ let mut doc = import("src.psd", &bytes).unwrap().document;
+ assert_eq!(doc.notes.len(), 2);
+ assert_eq!(doc.notes[1].text, "open note");
+ let out = to_psd(&doc);
+ let f = PsdFile::from_bytes(&out).unwrap();
+ assert_eq!(f.global_block(b"Anno").unwrap().data, src.global_block(b"Anno").unwrap().data);
+
+ // Edit a note: the block is regenerated and reads back with the change.
+ doc.notes[0].text = "changed".into();
+ doc.notes.push(Note { author: "agent".into(), text: "third".into(), position: [5.0, 6.0], ..Default::default() });
+ let back = import("x.psd", &to_psd(&doc)).unwrap().document;
+ assert_eq!(back.notes.len(), 3);
+ assert_eq!(back.notes[0].text, "changed");
+ assert_eq!(back.notes[2].position, [5.0, 6.0]);
+ // Deleting every note drops the block.
+ doc.notes.clear();
+ let f = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
+ assert!(f.global_block(b"Anno").is_none());
+}
+
+#[test]
+fn measurement_scale_roundtrips_through_psd() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut doc = Document::with_background("m", Size::new(16, 8), ColorMode::Rgb, depth, photocraft_color::Color::rgb(1.0, 1.0, 1.0));
+ let f = PsdFile::from_bytes(&to_psd(&doc)).unwrap();
+ assert!(f.resource(MEASUREMENT_SCALE).is_none());
+ doc.measurement.scale = MeasurementScale { pixel_length: 120.0, logical_length: 3.0, units: "cm".into() };
+ doc.notes.push(Note { text: "n".into(), ..Default::default() });
+ let back = import("x.psd", &to_psd(&doc)).unwrap().document;
+ assert_eq!(back.measurement.scale, doc.measurement.scale);
+ assert_eq!(back.notes.len(), 1);
+ assert_eq!((back.notes[0].text.as_str(), back.notes[0].position), ("n", [0.0, 0.0]));
+ // Unchanged → the preserved resource is written byte-exact (once).
+ let again = PsdFile::from_bytes(&to_psd(&back)).unwrap();
+ assert_eq!(again.resources.iter().filter(|r| r.id == MEASUREMENT_SCALE).count(), 1);
+ }
+}
diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rs
index b72cd8edd..ef72e8f71 100644
--- a/crates/io/tests/psd_structure.rs
+++ b/crates/io/tests/psd_structure.rs
@@ -172,7 +172,7 @@ fn testgen_import_details() {
#[test]
fn fallback_modes_import_flattened() {
- for mode in [ColorMode::Indexed, ColorMode::Bitmap, ColorMode::Duotone, ColorMode::Multichannel] {
+ for mode in [ColorMode::Indexed, ColorMode::Bitmap, ColorMode::Duotone] {
let depth = testgen::mode_depths(mode)[0];
let f = testgen::merged_only(Version::Psd, mode, depth, Compression::Rle, 9, 5);
let (d, w) = psd_to_document(&f);
@@ -185,6 +185,27 @@ fn fallback_modes_import_flattened() {
}
}
+#[test]
+fn multichannel_imports_ink_channels() {
+ for depth in testgen::mode_depths(ColorMode::Multichannel) {
+ let f = testgen::merged_only(Version::Psd, ColorMode::Multichannel, *depth, Compression::Rle, 9, 5);
+ let (d, _) = psd_to_document(&f);
+ assert_eq!(d.mode, photocraft_color::ColorMode::Multichannel);
+ assert!(d.layers.is_empty());
+ assert_eq!(d.channels.len(), usize::from(f.header.channels));
+ assert!(d.channels.iter().all(|c| c.spot.is_some()));
+ // Stored dark = ink: the channel value is 1 − the stored sample.
+ let merged = f.decode_merged().unwrap();
+ let first = if *depth == 8 { f32::from(merged[0]) / 255.0 } else { f32::from(u16::from_be_bytes([merged[0], merged[1]])) / 65535.0 };
+ assert!((d.channels[0].surface.pixel(0, 0)[0] - (1.0 - first)).abs() < 1e-3);
+ // Re-export writes the same planes.
+ let out = export(&d, "x.psd", &ExportOptions::default()).unwrap();
+ let back = PsdFile::from_bytes(&out.bytes).unwrap();
+ assert_eq!(back.header.color_mode, ColorMode::Multichannel);
+ assert_eq!(back.decode_merged().unwrap(), merged, "{depth}");
+ }
+}
+
#[test]
fn indexed_colors_match_palette() {
let f = testgen::merged_only(Version::Psd, ColorMode::Indexed, 8, Compression::Raw, 4, 2);
diff --git a/crates/io/tests/text_styles.rs b/crates/io/tests/text_styles.rs
new file mode 100644
index 000000000..f026aaf15
--- /dev/null
+++ b/crates/io/tests/text_styles.rs
@@ -0,0 +1,85 @@
+//! Character and paragraph styles through PSD: named sheets in the type layers' engine data,
+//! run references, and untouched files staying byte-exact.
+
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_doc::text::{CharStyle, ParagraphRun, ParagraphStyle, TextAlign, TextRun};
+use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef, diff_attrs};
+use photocraft_doc::{Document, Layer, LayerContent, Size, TextLayer, TextStyles};
+
+fn styles() -> TextStyles {
+ let mut s = TextStyles::default();
+ s.character.push(CharacterStyleDef { id: 3, name: "Loud".into(), attrs: diff_attrs(&CharStyle { size_pt: 30.0, underline: true, ..Default::default() }, &CharStyle::default()) });
+ s.paragraph.push(ParagraphStyleDef { id: 1, name: "Middle".into(), para_attrs: diff_attrs(&ParagraphStyle { align: TextAlign::Center, ..Default::default() }, &ParagraphStyle::default()), ..Default::default() });
+ s
+}
+
+fn doc_with(styles: TextStyles, link: bool) -> Document {
+ let mut doc = Document::new("t", Size::new(200, 80), ColorMode::Rgb, SampleType::U8);
+ let base = CharStyle { font_family: "Inter".into(), ..Default::default() };
+ let loud = if link { styles.resolve_char(None, Some(3), "Inter") } else { base.clone() };
+ let para = if link { styles.resolve_para(Some(1)) } else { ParagraphStyle::default() };
+ let mut t = TextLayer {
+ text: "calm LOUD".into(),
+ runs: vec![TextRun { len: 5, style: base }, TextRun { len: 4, style: loud }],
+ paragraphs: vec![ParagraphRun { len: 9, style: para }],
+ transform: photocraft_geom::Affine::translate(4.0, 40.0),
+ ..Default::default()
+ };
+ t.sync_summary();
+ photocraft_text::TextEngine::new().render_layer(&mut t, doc.resolution_dpi, doc.pixel_format());
+ doc.layers.push(Layer::new("t", LayerContent::Text(t)));
+ doc.text_styles = styles;
+ doc
+}
+
+fn text(doc: &Document) -> &TextLayer {
+ match &doc.layers[0].content {
+ LayerContent::Text(t) => t,
+ _ => panic!("not text"),
+ }
+}
+
+#[test]
+fn named_styles_round_trip_through_psd() {
+ let doc = doc_with(styles(), true);
+ let out = photocraft_io::export(&doc, "t.psd", &Default::default()).unwrap();
+ let back = photocraft_io::import("t.psd", &out.bytes).unwrap().document;
+ let st = &back.text_styles;
+ assert_eq!(st.character.len(), 1);
+ assert_eq!(st.character[0].name, "Loud");
+ assert_eq!(st.character[0].attrs.get("size_pt").and_then(|v| v.as_f64()), Some(30.0));
+ assert_eq!(st.character[0].attrs.get("underline").and_then(|v| v.as_bool()), Some(true));
+ assert_eq!(st.paragraph[0].name, "Middle");
+ assert_eq!(st.paragraph[0].para_attrs.get("align").and_then(|v| v.as_str()), Some("Center"));
+ let t = text(&back);
+ let runs = t.char_runs();
+ assert_eq!(runs[0].style.style_sheet, None);
+ assert_eq!(runs[1].style.style_sheet, Some(st.character[0].id));
+ assert_eq!(t.paragraph_runs()[0].style.style_sheet, Some(st.paragraph[0].id));
+ // Export again: stable.
+ let out2 = photocraft_io::export(&back, "t.psd", &Default::default()).unwrap();
+ let back2 = photocraft_io::import("t.psd", &out2.bytes).unwrap().document;
+ assert_eq!(back2.text_styles.character.len(), 1);
+ assert_eq!(back2.text_styles.paragraph.len(), 1);
+}
+
+#[test]
+fn documents_without_styles_keep_their_type_data() {
+ let doc = doc_with(TextStyles::default(), false);
+ let out = photocraft_io::export(&doc, "t.psd", &Default::default()).unwrap();
+ let back = photocraft_io::import("t.psd", &out.bytes).unwrap().document;
+ assert!(back.text_styles.is_empty());
+ // Re-export of an imported file without styles keeps TySh byte-exact.
+ let raw = text(&back).psd_raw.clone().unwrap();
+ let out2 = photocraft_io::export(&back, "t.psd", &Default::default()).unwrap();
+ let back2 = photocraft_io::import("t.psd", &out2.bytes).unwrap().document;
+ assert_eq!(text(&back2).psd_raw.as_deref(), Some(&*raw));
+ // Deleting every style removes the named sheets on the next save.
+ let styled = doc_with(styles(), true);
+ let out = photocraft_io::export(&styled, "t.psd", &Default::default()).unwrap();
+ let mut back = photocraft_io::import("t.psd", &out.bytes).unwrap().document;
+ back.text_styles = TextStyles::default();
+ let out = photocraft_io::export(&back, "t.psd", &Default::default()).unwrap();
+ let back = photocraft_io::import("t.psd", &out.bytes).unwrap().document;
+ assert!(back.text_styles.character.is_empty() && back.text_styles.paragraph.is_empty());
+}
diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs
index fa597f3cb..5d401c247 100644
--- a/crates/psd/src/lib.rs
+++ b/crates/psd/src/lib.rs
@@ -54,6 +54,7 @@ pub mod path;
pub mod patterns;
pub mod pixels;
pub mod resources;
+pub mod slices;
pub mod tagged;
#[cfg(any(test, feature = "testgen"))]
pub mod testgen;
diff --git a/crates/psd/src/slices.rs b/crates/psd/src/slices.rs
new file mode 100644
index 000000000..65fe9e6d9
--- /dev/null
+++ b/crates/psd/src/slices.rs
@@ -0,0 +1,417 @@
+//! Slices image resource (id 1050), from the Adobe Photoshop File Format Specification.
+//!
+//! Version 6 is a fixed binary layout (bounding rect, group name, then per slice: ids, origin,
+//! optional layer id, name, type, rect, URL / target / message / alt strings, cell text and
+//! alignment, background colour), optionally followed by a versioned descriptor carrying extra
+//! per-slice data (layer-slice outsets). Versions 7 and 8 store everything as one versioned
+//! descriptor (`baseName`, `bounds`, `slices` list).
+//!
+//! [`SlicesResource::to_bytes`] writes version 6, the documented binary layout every Photoshop
+//! version reads. Unknown fields are not kept here; callers that need a byte-exact round trip
+//! keep the raw resource while the slices are unchanged.
+
+use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor};
+use crate::error::{PsdError, Result};
+use crate::io::{Reader, WriteExt};
+
+/// Resource id of the slices resource.
+pub const SLICES: u16 = 1050;
+
+/// One slice record.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+pub struct SliceRecord {
+ /// Slice id.
+ pub id: u32,
+ /// Group id.
+ pub group_id: u32,
+ /// Origin: 0 auto-generated, 1 layer-based, 2 user-drawn.
+ pub origin: u32,
+ /// Layer id of a layer-based slice (the layer record's `lyid`).
+ pub layer_id: Option<u32>,
+ /// Slice name.
+ pub name: String,
+ /// Type: 0 no image, 1 image, 2 table.
+ pub kind: u32,
+ /// Left, top, right, bottom in document pixels.
+ pub rect: [i32; 4],
+ /// URL.
+ pub url: String,
+ /// Target frame.
+ pub target: String,
+ /// Status-bar message.
+ pub message: String,
+ /// Alt tag.
+ pub alt: String,
+ /// Cell text is HTML.
+ pub cell_text_is_html: bool,
+ /// Cell text.
+ pub cell_text: String,
+ /// Horizontal alignment.
+ pub horizontal_align: u32,
+ /// Vertical alignment.
+ pub vertical_align: u32,
+ /// Background colour as alpha, red, green, blue.
+ pub color: [u8; 4],
+ /// Layer-based slice outsets: top, left, bottom, right.
+ pub outsets: [i32; 4],
+}
+
+/// The whole slices resource.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+pub struct SlicesResource {
+ /// Version read (6, 7 or 8); writing always produces 6.
+ pub version: u32,
+ /// Bounding rectangle of all slices: top, left, bottom, right.
+ pub bounds: [i32; 4],
+ /// Name of the slice group (the base name).
+ pub group_name: String,
+ /// Slices, including auto-generated ones as Photoshop saves them.
+ pub slices: Vec<SliceRecord>,
+}
+
+fn ustr(r: &mut Reader<'_>) -> Result<String> {
+ Ok(UnicodeString::read(r)?.to_string_lossy())
+}
+
+fn put_ustr(out: &mut Vec<u8>, s: &str) {
+ UnicodeString::new(s).write(out);
+}
+
+// ---------- descriptor helpers (versions 7/8 and the v6 tail) ----------
+
+fn d_int(d: &Descriptor, key: &str) -> Option<i64> {
+ match d.get(key)? {
+ Value::Integer(v) => Some(i64::from(*v)),
+ Value::LargeInteger(v) => Some(*v),
+ Value::Double(v) => Some(*v as i64),
+ Value::UnitFloat { value, .. } => Some(*value as i64),
+ _ => None,
+ }
+}
+
+fn d_text(d: &Descriptor, key: &str) -> String {
+ match d.get(key) {
+ Some(Value::Text(t)) => t.to_string_lossy(),
+ _ => String::new(),
+ }
+}
+
+fn d_enum(d: &Descriptor, key: &str) -> Option<String> {
+ match d.get(key)? {
+ Value::Enumerated { value, .. } => Some(String::from_utf8_lossy(value.as_bytes()).into_owned()),
+ _ => None,
+ }
+}
+
+fn d_bool(d: &Descriptor, key: &str) -> bool {
+ matches!(d.get(key), Some(Value::Boolean(true)))
+}
+
+fn d_bounds(d: &Descriptor, key: &str) -> Option<[i32; 4]> {
+ let Value::Descriptor(b) = d.get(key)? else { return None };
+ let g = |k: &str| d_int(b, k).unwrap_or(0) as i32;
+ // top, left, bottom, right
+ Some([g("Top "), g("Left"), g("Btom"), g("Rght")])
+}
+
+fn origin_from(s: &str) -> u32 {
+ match s {
+ "autoGenerated" => 0,
+ "layerGenerated" | "layer" => 1,
+ _ => 2,
+ }
+}
+
+fn kind_from(s: &str) -> u32 {
+ match s {
+ "noImage" => 0,
+ "Tbl " | "table" => 2,
+ _ => 1,
+ }
+}
+
+fn slice_from_descriptor(d: &Descriptor) -> SliceRecord {
+ let b = d_bounds(d, "bounds").unwrap_or_default();
+ let color = match (d_enum(d, "bgColorType").as_deref(), d.get("bgColor")) {
+ (Some("Clr "), Some(Value::Descriptor(c))) => {
+ let g = |k: &str| d_int(c, k).unwrap_or(0).clamp(0, 255) as u8;
+ let a = if c.get("alpha").is_some() { g("alpha") } else { 255 };
+ [a, g("Rd "), g("Grn "), g("Bl ")]
+ }
+ _ => [0; 4],
+ };
+ SliceRecord {
+ id: d_int(d, "sliceID").unwrap_or(0) as u32,
+ group_id: d_int(d, "groupID").unwrap_or(0) as u32,
+ origin: d_enum(d, "origin").map_or(2, |s| origin_from(&s)),
+ layer_id: d_int(d, "layerID").map(|v| v as u32),
+ name: d_text(d, "Nm "),
+ kind: d_enum(d, "Type").map_or(1, |s| kind_from(&s)),
+ // Descriptor bounds are top/left/bottom/right; records use left/top/right/bottom.
+ rect: [b[1], b[0], b[3], b[2]],
+ url: d_text(d, "url"),
+ target: d_text(d, "null"),
+ message: d_text(d, "Msge"),
+ alt: d_text(d, "altTag"),
+ cell_text_is_html: d_bool(d, "cellTextIsHTML"),
+ cell_text: d_text(d, "cellText"),
+ horizontal_align: 0,
+ vertical_align: 0,
+ color,
+ outsets: [
+ d_int(d, "topOutset").unwrap_or(0) as i32,
+ d_int(d, "leftOutset").unwrap_or(0) as i32,
+ d_int(d, "bottomOutset").unwrap_or(0) as i32,
+ d_int(d, "rightOutset").unwrap_or(0) as i32,
+ ],
+ }
+}
+
+fn bounds_descriptor(tlbr: [i32; 4]) -> Value {
+ Value::Descriptor(
+ Descriptor::new("Rct1")
+ .with("Top ", Value::Integer(tlbr[0]))
+ .with("Left", Value::Integer(tlbr[1]))
+ .with("Btom", Value::Integer(tlbr[2]))
+ .with("Rght", Value::Integer(tlbr[3])),
+ )
+}
+
+fn enumerated(ty: &str, v: &str) -> Value {
+ Value::Enumerated { type_id: Id::new(ty), value: Id::new(v) }
+}
+
+impl SlicesResource {
+ /// Parses resource data (versions 6, 7 and 8).
+ pub fn from_bytes(data: &[u8]) -> Result<Self> {
+ let mut r = Reader::new(data);
+ let version = r.u32()?;
+ match version {
+ 6 => Self::read_v6(&mut r),
+ 7 | 8 => {
+ let vd = VersionedDescriptor::read(&mut r)?;
+ let d = &vd.descriptor;
+ let slices = match d.get("slices") {
+ Some(Value::List(items)) => items
+ .iter()
+ .filter_map(|v| match v {
+ Value::Descriptor(s) => Some(slice_from_descriptor(s)),
+ _ => None,
+ })
+ .collect(),
+ _ => Vec::new(),
+ };
+ Ok(SlicesResource { version, bounds: d_bounds(d, "bounds").unwrap_or_default(), group_name: d_text(d, "baseName"), slices })
+ }
+ v => Err(PsdError::invalid(format!("unsupported slices resource version {v}"))),
+ }
+ }
+
+ fn read_v6(r: &mut Reader<'_>) -> Result<Self> {
+ let bounds = [r.i32()?, r.i32()?, r.i32()?, r.i32()?];
+ let group_name = ustr(r)?;
+ let n = r.u32()? as usize;
+ if n > r.remaining() / 16 {
+ return Err(PsdError::invalid("slice count exceeds the resource size"));
+ }
+ let mut slices = Vec::with_capacity(n);
+ for _ in 0..n {
+ let id = r.u32()?;
+ let group_id = r.u32()?;
+ let origin = r.u32()?;
+ let layer_id = if origin == 1 { Some(r.u32()?) } else { None };
+ let name = ustr(r)?;
+ let kind = r.u32()?;
+ let rect = [r.i32()?, r.i32()?, r.i32()?, r.i32()?];
+ let url = ustr(r)?;
+ let target = ustr(r)?;
+ let message = ustr(r)?;
+ let alt = ustr(r)?;
+ let cell_text_is_html = r.u8()? != 0;
+ let cell_text = ustr(r)?;
+ let horizontal_align = r.u32()?;
+ let vertical_align = r.u32()?;
+ let color = [r.u8()?, r.u8()?, r.u8()?, r.u8()?];
+ slices.push(SliceRecord { id, group_id, origin, layer_id, name, kind, rect, url, target, message, alt, cell_text_is_html, cell_text, horizontal_align, vertical_align, color, outsets: [0; 4] });
+ }
+ // Optional trailing descriptor (Photoshop 7+): per-slice extras such as outsets.
+ if r.remaining() >= 4
+ && let Ok(vd) = VersionedDescriptor::read(r)
+ && let Some(Value::List(items)) = vd.descriptor.get("slices")
+ {
+ for v in items {
+ let Value::Descriptor(d) = v else { continue };
+ let extra = slice_from_descriptor(d);
+ if let Some(s) = slices.iter_mut().find(|s| s.id == extra.id) {
+ s.outsets = extra.outsets;
+ }
+ }
+ }
+ Ok(SlicesResource { version: 6, bounds, group_name, slices })
+ }
+
+ /// Serializes as version 6. A trailing descriptor with the outsets is added when any slice
+ /// has them, the way Photoshop extends the version 6 layout.
+ pub fn to_bytes(&self) -> Vec<u8> {
+ let mut out = Vec::new();
+ out.put_u32(6);
+ for v in self.bounds {
+ out.put_i32(v);
+ }
+ put_ustr(&mut out, &self.group_name);
+ out.put_u32(self.slices.len() as u32);
+ for s in &self.slices {
+ out.put_u32(s.id);
+ out.put_u32(s.group_id);
+ out.put_u32(s.origin);
+ if s.origin == 1 {
+ out.put_u32(s.layer_id.unwrap_or(0));
+ }
+ put_ustr(&mut out, &s.name);
+ out.put_u32(s.kind);
+ for v in s.rect {
+ out.put_i32(v);
+ }
+ put_ustr(&mut out, &s.url);
+ put_ustr(&mut out, &s.target);
+ put_ustr(&mut out, &s.message);
+ put_ustr(&mut out, &s.alt);
+ out.put_u8(u8::from(s.cell_text_is_html));
+ put_ustr(&mut out, &s.cell_text);
+ out.put_u32(s.horizontal_align);
+ out.put_u32(s.vertical_align);
+ out.put(&s.color);
+ }
+ if self.slices.iter().any(|s| s.outsets != [0; 4]) {
+ let list = self
+ .slices
+ .iter()
+ .map(|s| {
+ Value::Descriptor(
+ Descriptor::new("slice")
+ .with("sliceID", Value::Integer(s.id as i32))
+ .with("topOutset", Value::Integer(s.outsets[0]))
+ .with("leftOutset", Value::Integer(s.outsets[1]))
+ .with("bottomOutset", Value::Integer(s.outsets[2]))
+ .with("rightOutset", Value::Integer(s.outsets[3])),
+ )
+ })
+ .collect();
+ VersionedDescriptor::new(Descriptor::new("null").with("slices", Value::List(list))).write(&mut out);
+ }
+ out
+ }
+
+ /// Serializes in the version 7 descriptor form (what newer Photoshop versions write).
+ pub fn to_descriptor_bytes(&self) -> Vec<u8> {
+ let list = self
+ .slices
+ .iter()
+ .map(|s| {
+ let origin = match s.origin {
+ 0 => "autoGenerated",
+ 1 => "layerGenerated",
+ _ => "userGenerated",
+ };
+ let kind = match s.kind {
+ 0 => "noImage",
+ 2 => "Tbl ",
+ _ => "Img ",
+ };
+ let mut d = Descriptor::new("slice")
+ .with("sliceID", Value::Integer(s.id as i32))
+ .with("groupID", Value::Integer(s.group_id as i32))
+ .with("origin", enumerated("ESliceOrigin", origin));
+ if let Some(l) = s.layer_id.filter(|_| s.origin == 1) {
+ d = d.with("layerID", Value::Integer(l as i32));
+ }
+ d.with("Nm ", Value::Text(UnicodeString::new(&s.name)))
+ .with("Type", enumerated("ESliceType", kind))
+ .with("bounds", bounds_descriptor([s.rect[1], s.rect[0], s.rect[3], s.rect[2]]))
+ .with("url", Value::Text(UnicodeString::new(&s.url)))
+ .with("null", Value::Text(UnicodeString::new(&s.target)))
+ .with("Msge", Value::Text(UnicodeString::new(&s.message)))
+ .with("altTag", Value::Text(UnicodeString::new(&s.alt)))
+ .with("cellTextIsHTML", Value::Boolean(s.cell_text_is_html))
+ .with("cellText", Value::Text(UnicodeString::new(&s.cell_text)))
+ .with("horzAlign", enumerated("ESliceHorzAlign", "default"))
+ .with("vertAlign", enumerated("ESliceVertAlign", "default"))
+ .with("bgColorType", enumerated("ESliceBGColorType", "None"))
+ .with("topOutset", Value::Integer(s.outsets[0]))
+ .with("leftOutset", Value::Integer(s.outsets[1]))
+ .with("bottomOutset", Value::Integer(s.outsets[2]))
+ .with("rightOutset", Value::Integer(s.outsets[3]))
+ })
+ .map(Value::Descriptor)
+ .collect();
+ let d = Descriptor::new("null")
+ .with("bounds", bounds_descriptor(self.bounds))
+ .with("slices", Value::List(list))
+ .with("baseName", Value::Text(UnicodeString::new(&self.group_name)));
+ let mut out = Vec::new();
+ out.put_u32(7);
+ VersionedDescriptor::new(d).write(&mut out);
+ out
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample() -> SlicesResource {
+ SlicesResource {
+ version: 6,
+ bounds: [0, 0, 80, 100],
+ group_name: "site".into(),
+ slices: vec![
+ SliceRecord { id: 0, origin: 0, kind: 1, rect: [0, 0, 100, 10], ..Default::default() },
+ SliceRecord { id: 1, group_id: 0, origin: 2, name: "logo".into(), kind: 1, rect: [20, 10, 60, 30], url: "https://example.org/".into(), target: "_blank".into(), message: "hi".into(), alt: "Logo".into(), cell_text_is_html: true, cell_text: "<b>x</b>".into(), horizontal_align: 1, vertical_align: 2, color: [255, 10, 20, 30], ..Default::default() },
+ SliceRecord { id: 2, origin: 1, layer_id: Some(7), kind: 0, rect: [5, 40, 25, 70], outsets: [1, 2, 3, 4], ..Default::default() },
+ ],
+ }
+ }
+
+ #[test]
+ fn v6_roundtrips() {
+ let s = sample();
+ let bytes = s.to_bytes();
+ let back = SlicesResource::from_bytes(&bytes).unwrap();
+ assert_eq!(back, s);
+ assert_eq!(back.to_bytes(), bytes, "byte-stable");
+ }
+
+ #[test]
+ fn v7_descriptor_parses() {
+ let s = sample();
+ let back = SlicesResource::from_bytes(&s.to_descriptor_bytes()).unwrap();
+ assert_eq!(back.version, 7);
+ assert_eq!(back.group_name, "site");
+ assert_eq!(back.bounds, s.bounds);
+ assert_eq!(back.slices.len(), 3);
+ assert_eq!(back.slices[1].rect, [20, 10, 60, 30]);
+ assert_eq!(back.slices[1].alt, "Logo");
+ assert_eq!(back.slices[1].target, "_blank");
+ assert_eq!(back.slices[2].origin, 1);
+ assert_eq!(back.slices[2].layer_id, Some(7));
+ assert_eq!(back.slices[2].kind, 0);
+ assert_eq!(back.slices[2].outsets, [1, 2, 3, 4]);
+ }
+
+ #[test]
+ fn malformed_input_is_an_error() {
+ let bytes = sample().to_bytes();
+ // Cuts inside the records; a damaged trailing descriptor is ignored on purpose.
+ for cut in [0, 3, 10, 30, 120] {
+ assert!(SlicesResource::from_bytes(&bytes[..cut]).is_err(), "cut at {cut}");
+ }
+ let mut huge = 6u32.to_be_bytes().to_vec();
+ huge.extend([0u8; 16]);
+ huge.extend(0u32.to_be_bytes());
+ huge.extend(u32::MAX.to_be_bytes());
+ assert!(SlicesResource::from_bytes(&huge).is_err());
+ assert!(SlicesResource::from_bytes(&9u32.to_be_bytes()).is_err());
+ }
+}
diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml
index 301e38395..2016c27a0 100644
--- a/crates/text/Cargo.toml
+++ b/crates/text/Cargo.toml
@@ -19,3 +19,4 @@ photocraft-psd = { workspace = true }
# directories ourselves (native) and always register the bundled fonts (native + web).
parley = { version = "0.11", default-features = false, features = ["std"] }
skrifa = "0.44"
+flate2 = { workspace = true }
diff --git a/crates/text/src/glyphs.rs b/crates/text/src/glyphs.rs
new file mode 100644
index 000000000..3745b5ff7
--- /dev/null
+++ b/crates/text/src/glyphs.rs
@@ -0,0 +1,154 @@
+//! Glyphs panel support: the characters a face maps (its `cmap`), Photoshop's "Show" categories,
+//! and small glyph previews.
+
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_doc::TextLayer;
+use photocraft_doc::text::{CharStyle, TextRun};
+use photocraft_geom::Affine;
+use skrifa::MetadataProvider;
+
+use crate::FontDb;
+
+/// The Glyphs panel's "Show" categories, in menu order.
+pub const CATEGORIES: &[&str] = &[
+ "Entire Font",
+ "Basic Latin",
+ "Latin 1",
+ "Latin Extended-A",
+ "Latin Extended-B",
+ "Greek",
+ "Cyrillic",
+ "Punctuation",
+ "Numbers",
+ "Currency",
+ "Symbols",
+ "Math Symbols",
+ "Arrows",
+ "Ornaments",
+];
+
+/// Whether `c` belongs to a [`CATEGORIES`] entry (unknown names match everything).
+pub fn in_category(c: char, category: &str) -> bool {
+ let u = c as u32;
+ match category {
+ "Basic Latin" => (0x20..=0x7E).contains(&u),
+ "Latin 1" => (0xA0..=0xFF).contains(&u),
+ "Latin Extended-A" => (0x100..=0x17F).contains(&u),
+ "Latin Extended-B" => (0x180..=0x24F).contains(&u),
+ "Greek" => (0x370..=0x3FF).contains(&u) || (0x1F00..=0x1FFF).contains(&u),
+ "Cyrillic" => (0x400..=0x52F).contains(&u),
+ "Punctuation" => {
+ c.is_ascii_punctuation() && !matches!(c, '$' | '+' | '<' | '=' | '>' | '^' | '`' | '|' | '~')
+ || matches!(u, 0xA1 | 0xA7 | 0xAB | 0xB6 | 0xB7 | 0xBB | 0xBF)
+ || (0x2010..=0x2027).contains(&u)
+ || (0x2030..=0x205E).contains(&u)
+ || (0x2E00..=0x2E7F).contains(&u)
+ || (0x3000..=0x303F).contains(&u)
+ }
+ "Numbers" => c.is_numeric() || (0x2150..=0x218F).contains(&u),
+ "Currency" => matches!(c, '$' | '¢' | '£' | '¤' | '¥') || (0x20A0..=0x20CF).contains(&u),
+ "Symbols" => {
+ matches!(c, '©' | '®' | '°' | '¦' | '¨' | '¯' | '´' | '¸' | '™' | '℠' | '№' | '℮' | '^' | '`' | '|' | '~')
+ || (0x2100..=0x214F).contains(&u)
+ || (0x2300..=0x23FF).contains(&u)
+ || (0x2500..=0x25FF).contains(&u)
+ }
+ "Math Symbols" => {
+ matches!(c, '+' | '<' | '=' | '>' | '±' | '×' | '÷' | '¬' | 'µ' | '¹' | '²' | '³' | '¼' | '½' | '¾')
+ || (0x2070..=0x209F).contains(&u)
+ || (0x2200..=0x22FF).contains(&u)
+ || (0x27C0..=0x27EF).contains(&u)
+ || (0x2980..=0x2AFF).contains(&u)
+ }
+ "Arrows" => (0x2190..=0x21FF).contains(&u) || (0x27F0..=0x27FF).contains(&u) || (0x2900..=0x297F).contains(&u) || (0x2B00..=0x2BFF).contains(&u),
+ "Ornaments" => (0x2600..=0x27BF).contains(&u) || (0x1F300..=0x1FAFF).contains(&u) || (0xE000..=0xF8FF).contains(&u),
+ _ => true,
+ }
+}
+
+impl FontDb {
+ /// Characters mapped by the face of `family` nearest to `weight`/`italic`, ascending
+ /// (controls and whitespace other than the space excluded). Empty for an unknown family.
+ pub fn charmap(&mut self, family: &str, weight: u16, italic: bool) -> Vec<char> {
+ let Some(info) = self.fcx.collection.family_by_name(family) else {
+ return Vec::new();
+ };
+ let fonts = info.fonts();
+ let Some(font) = fonts.iter().min_by_key(|f| {
+ let it = !matches!(f.style(), parley::fontique::FontStyle::Normal);
+ (u32::from(it != italic) * 10_000) + (f.weight().value() - f32::from(weight)).abs() as u32
+ }) else {
+ return Vec::new();
+ };
+ let Some(blob) = font.load(Some(&mut self.fcx.source_cache)) else {
+ return Vec::new();
+ };
+ let Ok(fr) = skrifa::FontRef::from_index(blob.as_ref(), font.index()) else {
+ return Vec::new();
+ };
+ let mut out: Vec<char> = fr
+ .charmap()
+ .mappings()
+ .filter(|(_, g)| g.to_u32() != 0)
+ .filter_map(|(u, _)| char::from_u32(u))
+ .filter(|c| *c == ' ' || !(c.is_control() || c.is_whitespace() || ('\u{FE00}'..='\u{FE0F}').contains(c)))
+ .collect();
+ out.sort_unstable();
+ out.dedup();
+ out
+ }
+}
+
+/// An 8-bit coverage preview of one character in a `px`-pixel em box, centred horizontally on
+/// the baseline at 80 % of the box: (width = height = `px`, alpha bytes).
+pub fn preview(engine: &mut crate::TextEngine, style: &CharStyle, c: char, px: u32) -> (u32, Vec<u8>) {
+ let px = px.clamp(4, 512);
+ let text = c.to_string();
+ let mut st = style.clone();
+ st.size_pt = px as f32 * 0.72;
+ st.underline = false;
+ st.strikethrough = false;
+ st.tracking = 0.0;
+ st.baseline_shift_pt = 0.0;
+ let layer = TextLayer { runs: vec![TextRun { len: text.len(), style: st }], text, ..Default::default() };
+ let layout = engine.layout(&layer, 72.0);
+ let w = layout.bounds().map_or(0.0, |b| b[2] - b[0]);
+ let x0 = layout.bounds().map_or(0.0, |b| b[0]);
+ let tx = (px as f32 - w) / 2.0 - x0;
+ let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
+ let r = crate::render::rasterize_warped(&layout, &Affine::translate(f64::from(tx), f64::from(px as f32 * 0.78)), fmt, photocraft_doc::text::AntiAlias::Smooth, None);
+ let mut rgba = vec![[0u8; 4]; (px * px) as usize];
+ r.surface.read_rgba8_into(photocraft_geom::Rect::new(0, 0, px as i32, px as i32), &mut rgba);
+ (px, rgba.into_iter().map(|p| p[3]).collect())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bundled_charmap_and_categories() {
+ let mut db = FontDb::new();
+ let cm = db.charmap(crate::fonts::DEFAULT_FAMILY, 400, false);
+ assert!(cm.len() > 500, "{}", cm.len());
+ assert!(cm.contains(&'A') && cm.contains(&'€') && cm.contains(&' '));
+ assert!(!cm.contains(&'\n'));
+ assert!(db.charmap("No Such Family", 400, false).is_empty());
+ let latin: Vec<char> = cm.iter().copied().filter(|c| in_category(*c, "Basic Latin")).collect();
+ assert_eq!(latin.len(), 95);
+ assert!(in_category('€', "Currency") && in_category('—', "Punctuation") && in_category('→', "Arrows"));
+ assert!(!in_category('A', "Punctuation") && in_category('A', "Entire Font"));
+ }
+
+ #[test]
+ fn preview_draws_ink() {
+ let mut eng = crate::TextEngine::new();
+ let st = CharStyle { font_family: crate::fonts::DEFAULT_FAMILY.into(), ..Default::default() };
+ let (n, a) = preview(&mut eng, &st, 'W', 32);
+ assert_eq!((n, a.len()), (32, 32 * 32));
+ let ink: u32 = a.iter().map(|&v| u32::from(v)).sum();
+ assert!(ink > 20 * 255, "{ink}");
+ let (_, sp) = preview(&mut eng, &st, ' ', 32);
+ assert!(sp.iter().all(|&v| v == 0));
+ }
+}
diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs
index d94e68f6f..3dee90530 100644
--- a/crates/text/src/lib.rs
+++ b/crates/text/src/lib.rs
@@ -15,10 +15,13 @@
pub mod engine_data;
pub mod fonts;
+pub mod glyphs;
pub mod layout;
pub mod psd;
+pub mod psd_styles;
pub mod raster;
pub mod render;
+pub mod spell;
pub mod warp;
use photocraft_color::PixelFormat;
diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs
index c0909c6c6..ea121d6f9 100644
--- a/crates/text/src/psd.rs
+++ b/crates/text/src/psd.rs
@@ -170,7 +170,7 @@ pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option<TextLayer> {
Some(layer)
}
-fn arr_f(v: Option<&E>) -> Vec<f64> {
+pub(crate) fn arr_f(v: Option<&E>) -> Vec<f64> {
v.and_then(E::as_array)
.map(|a| a.iter().filter_map(E::as_f64).collect())
.unwrap_or_default()
@@ -303,7 +303,7 @@ fn lookup<'a>(run: &'a E, base: Option<&'a E>, key: &str) -> Option<&'a E> {
run.get(key).or_else(|| base.and_then(|b| b.get(key)))
}
-fn char_style(base: Option<&E>, d: &E, fonts: &[String], k: f32) -> CharStyle {
+pub(crate) fn char_style(base: Option<&E>, d: &E, fonts: &[String], k: f32) -> CharStyle {
let g = |key: &str| lookup(d, base, key);
let num = |key: &str| g(key).and_then(E::as_f64);
let flag = |key: &str| g(key).and_then(E::as_bool);
@@ -375,7 +375,7 @@ fn char_style(base: Option<&E>, d: &E, fonts: &[String], k: f32) -> CharStyle {
s
}
-fn para_style(base: Option<&E>, d: &E, k: f32) -> ParagraphStyle {
+pub(crate) fn para_style(base: Option<&E>, d: &E, k: f32) -> ParagraphStyle {
let num = |key: &str| lookup(d, base, key).and_then(E::as_f64);
ParagraphStyle {
align: match num("Justification").map(|v| v as i64) {
@@ -407,7 +407,7 @@ fn real(v: f32) -> E {
}
/// PostScript name for a style (the PSD `FontSet` stores these).
-fn postscript_for(s: &CharStyle) -> String {
+pub(crate) fn postscript_for(s: &CharStyle) -> String {
if let Some(ps) = &s.postscript_name {
return ps.clone();
}
@@ -448,7 +448,7 @@ pub const OPENTYPE_KEYS: [(&str, &str); 8] = [
("Fractions", "frac"),
];
-fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
+pub(crate) fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
let c = &s.color;
let values = match c.mode {
ColorMode::Cmyk => vec![
@@ -511,7 +511,7 @@ fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
E::Dict(dict)
}
-fn paragraph_properties(p: &ParagraphStyle, k: f32) -> E {
+pub(crate) fn paragraph_properties(p: &ParagraphStyle, k: f32) -> E {
let j = match p.align {
TextAlign::Left => 0,
TextAlign::Right => 1,
@@ -538,7 +538,7 @@ fn utf16_len(s: &str) -> i64 {
s.encode_utf16().count() as i64
}
-fn font_entry(name: &str) -> E {
+pub(crate) fn font_entry(name: &str) -> E {
E::Dict(vec![
("Name".into(), E::String(name.into())),
("Script".into(), E::Int(0)),
diff --git a/crates/text/src/psd_styles.rs b/crates/text/src/psd_styles.rs
new file mode 100644
index 000000000..e78492cc5
--- /dev/null
+++ b/crates/text/src/psd_styles.rs
@@ -0,0 +1,238 @@
+//! Named character and paragraph styles in the PSD text engine data.
+//!
+//! Every type layer's `EngineData` carries the document's style sheets in its `ResourceDict`
+//! (and `DocumentResources`): `StyleSheetSet` (character style sheets: `Name`,
+//! `StyleSheetData`) and `ParagraphSheetSet` (`Name`, `DefaultStyleSheet`, `Properties`), with
+//! `TheNormalStyleSheet` / `TheNormalParagraphSheet` naming the defaults. Runs refer to a sheet
+//! from their `StyleSheet` / `ParagraphSheet` dictionaries.
+//!
+//! How Photoshop links a run to a named sheet isn't in Adobe's published PSD spec. We read both
+//! a `Parent` index and a `Name` on the run's sheet, and write `Parent` (plus the run's fully
+//! resolved attributes, so the text looks the same whatever a reader makes of the reference).
+//! Named sheets are written with fully resolved attributes too. Unverified against Photoshop.
+
+use photocraft_doc::text::{CharStyle, ParagraphStyle};
+use photocraft_doc::{TextLayer, TextStyles};
+
+use crate::engine_data::Value as E;
+use crate::psd::{char_style, engine_data, para_style, paragraph_properties, parse_tysh, postscript_for, style_sheet_data, write_tysh};
+
+/// Style sheets read from one type layer.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct PsdStyleSheets {
+ /// The default ("Normal") character sheet, resolved.
+ pub normal_char: CharStyle,
+ pub normal_para: ParagraphStyle,
+ /// Named character sheets other than the normal one: (set index, name, resolved style).
+ pub char_sheets: Vec<(usize, String, CharStyle)>,
+ /// Named paragraph sheets: (set index, name, paragraph style, character style of its
+ /// `DefaultStyleSheet` when that isn't the normal sheet).
+ pub para_sheets: Vec<(usize, String, ParagraphStyle, Option<CharStyle>)>,
+ /// Per `StyleRun` entry: the character sheet index it refers to, if any.
+ pub run_char: Vec<Option<usize>>,
+ /// Per `ParagraphRun` entry: the paragraph sheet index it refers to, if any.
+ pub run_para: Vec<Option<usize>>,
+}
+
+fn k_of(dpi: f32) -> f32 {
+ 72.0 / if dpi > 0.0 { dpi } else { 72.0 }
+}
+
+fn names(set: Option<&E>) -> Vec<String> {
+ set.and_then(E::as_array).map(|a| a.iter().map(|s| s.get("Name").and_then(E::as_str).unwrap_or("").to_string()).collect()).unwrap_or_default()
+}
+
+/// Index a run's sheet dictionary refers to (`Parent` index, else `Name`), skipping `normal`.
+fn reference(sheet: Option<&E>, set_names: &[String], normal: usize) -> Option<usize> {
+ let s = sheet?;
+ let i = s.get("Parent").and_then(E::as_i64).map(|i| i as usize).or_else(|| {
+ let n = s.get("Name").and_then(E::as_str)?;
+ set_names.iter().position(|x| x == n)
+ })?;
+ (i != normal && i < set_names.len()).then_some(i)
+}
+
+/// Reads the style sheets of a `TySh` block. None when it has no engine data.
+pub fn read_style_sheets(tysh: &[u8], dpi: f32) -> Option<PsdStyleSheets> {
+ let t = parse_tysh(tysh)?;
+ let e = engine_data(&t.text)?;
+ let k = k_of(dpi);
+ let res = e.get("ResourceDict").or_else(|| e.get("DocumentResources"))?;
+ let fonts: Vec<String> = names(res.get("FontSet"));
+ let sset = res.get("StyleSheetSet").and_then(E::as_array).unwrap_or(&[]);
+ let pset = res.get("ParagraphSheetSet").and_then(E::as_array).unwrap_or(&[]);
+ let normal_c = res.get("TheNormalStyleSheet").and_then(E::as_i64).unwrap_or(0) as usize;
+ let normal_p = res.get("TheNormalParagraphSheet").and_then(E::as_i64).unwrap_or(0) as usize;
+ let empty = E::dict();
+ let base_data = sset.get(normal_c).and_then(|s| s.get("StyleSheetData"));
+ let normal_char = char_style(None, base_data.unwrap_or(&empty), &fonts, k);
+ let base_props = pset.get(normal_p).and_then(|s| s.get("Properties"));
+ let normal_para = para_style(None, base_props.unwrap_or(&empty), k);
+ let mut out = PsdStyleSheets { normal_char, normal_para, ..Default::default() };
+ for (i, s) in sset.iter().enumerate() {
+ if i == normal_c {
+ continue;
+ }
+ let name = s.get("Name").and_then(E::as_str).unwrap_or("").to_string();
+ let data = s.get("StyleSheetData").unwrap_or(&empty);
+ out.char_sheets.push((i, name, char_style(base_data, data, &fonts, k)));
+ }
+ for (i, s) in pset.iter().enumerate() {
+ if i == normal_p {
+ continue;
+ }
+ let name = s.get("Name").and_then(E::as_str).unwrap_or("").to_string();
+ let props = s.get("Properties").unwrap_or(&empty);
+ let dss = s.get("DefaultStyleSheet").and_then(E::as_i64).map(|i| i as usize).filter(|i| *i != normal_c);
+ let cs = dss.and_then(|d| sset.get(d)).map(|d| char_style(base_data, d.get("StyleSheetData").unwrap_or(&empty), &fonts, k));
+ out.para_sheets.push((i, name, para_style(base_props, props, k), cs));
+ }
+ let snames = names(res.get("StyleSheetSet"));
+ let pnames = names(res.get("ParagraphSheetSet"));
+ if let Some(a) = e.path(&["EngineDict", "StyleRun", "RunArray"]).and_then(E::as_array) {
+ out.run_char = a.iter().map(|r| reference(r.get("StyleSheet"), &snames, normal_c)).collect();
+ }
+ if let Some(a) = e.path(&["EngineDict", "ParagraphRun", "RunArray"]).and_then(E::as_array) {
+ out.run_para = a.iter().map(|r| reference(r.get("ParagraphSheet"), &pnames, normal_p)).collect();
+ }
+ Some(out)
+}
+
+fn remove_key(d: &mut E, key: &str) {
+ if let E::Dict(items) = d {
+ items.retain(|(k, _)| k != key);
+ }
+}
+
+/// Whether a `TySh` block carries named sheets beyond the normal ones.
+pub fn has_named_sheets(tysh: &[u8]) -> bool {
+ let Some(e) = parse_tysh(tysh).and_then(|t| engine_data(&t.text)) else { return false };
+ let Some(res) = e.get("ResourceDict") else { return false };
+ let n = |k: &str| res.get(k).and_then(E::as_array).map_or(0, <[E]>::len);
+ n("StyleSheetSet") > 1 || n("ParagraphSheetSet") > 1
+}
+
+/// Rewrites the style sheets of a `TySh` block from the document's styles and the layer's run
+/// references. The normal sheets are kept; other sheets are replaced by `styles`.
+pub fn write_style_sheets(tysh: &[u8], layer: &TextLayer, styles: &TextStyles, dpi: f32) -> Option<Vec<u8>> {
+ let mut t = parse_tysh(tysh)?;
+ let mut e = engine_data(&t.text)?;
+ let k = k_of(dpi);
+ for key in ["ResourceDict", "DocumentResources"] {
+ let Some(rd) = e.get_mut(key) else { continue };
+ let mut fonts = names(rd.get("FontSet"));
+ let normal_c = rd.get("TheNormalStyleSheet").and_then(E::as_i64).unwrap_or(0) as usize;
+ let normal_p = rd.get("TheNormalParagraphSheet").and_then(E::as_i64).unwrap_or(0) as usize;
+ let keep_c = rd.get("StyleSheetSet").and_then(E::as_array).and_then(|a| a.get(normal_c).or(a.first())).cloned();
+ let keep_p = rd.get("ParagraphSheetSet").and_then(E::as_array).and_then(|a| a.get(normal_p).or(a.first())).cloned();
+ let mut font_index = |s: &CharStyle| {
+ let ps = postscript_for(s);
+ match fonts.iter().position(|f| *f == ps) {
+ Some(i) => i,
+ None => {
+ fonts.push(ps);
+ fonts.len() - 1
+ }
+ }
+ };
+ let mut sset: Vec<E> = keep_c.into_iter().collect();
+ for d in &styles.character {
+ let st = styles.resolve_char(None, Some(d.id), crate::fonts::DEFAULT_FAMILY);
+ let fi = font_index(&st);
+ sset.push(E::Dict(vec![("Name".into(), E::String(d.name.clone())), ("Parent".into(), E::Int(0)), ("StyleSheetData".into(), style_sheet_data(&st, fi, k))]));
+ }
+ let mut pset: Vec<E> = keep_p.into_iter().collect();
+ for d in &styles.paragraph {
+ let p = styles.resolve_para(Some(d.id));
+ pset.push(E::Dict(vec![("Name".into(), E::String(d.name.clone())), ("DefaultStyleSheet".into(), E::Int(0)), ("Parent".into(), E::Int(0)), ("Properties".into(), paragraph_properties(&p, k))]));
+ }
+ rd.set("StyleSheetSet", E::Array(sset));
+ rd.set("ParagraphSheetSet", E::Array(pset));
+ rd.set("TheNormalStyleSheet", E::Int(0));
+ rd.set("TheNormalParagraphSheet", E::Int(0));
+ rd.set("FontSet", E::Array(fonts.iter().map(|f| crate::psd::font_entry(f)).collect()));
+ }
+ let char_ix = |id: Option<u32>| id.and_then(|id| styles.character.iter().position(|d| d.id == id)).map(|i| i as i64 + 1);
+ let para_ix = |id: Option<u32>| id.and_then(|id| styles.paragraph.iter().position(|d| d.id == id)).map(|i| i as i64 + 1);
+ let runs = layer.char_runs();
+ if let Some(E::Array(a)) = e.get_mut("EngineDict").and_then(|d| d.get_mut("StyleRun")).and_then(|r| r.get_mut("RunArray")) {
+ for (i, r) in a.iter_mut().enumerate() {
+ if let Some(sheet) = r.get_mut("StyleSheet") {
+ remove_key(sheet, "Parent");
+ remove_key(sheet, "Name");
+ if let Some(ix) = char_ix(runs.get(i).and_then(|r| r.style.style_sheet)) {
+ sheet.set("Parent", E::Int(ix));
+ }
+ }
+ }
+ }
+ let paras = layer.paragraph_runs();
+ if let Some(E::Array(a)) = e.get_mut("EngineDict").and_then(|d| d.get_mut("ParagraphRun")).and_then(|r| r.get_mut("RunArray")) {
+ for (i, r) in a.iter_mut().enumerate() {
+ if let Some(sheet) = r.get_mut("ParagraphSheet") {
+ remove_key(sheet, "Parent");
+ remove_key(sheet, "Name");
+ if let Some(ix) = para_ix(paras.get(i).and_then(|p| p.style.style_sheet)) {
+ sheet.set("Parent", E::Int(ix));
+ }
+ }
+ }
+ }
+ let raw = crate::engine_data::write(&e);
+ match t.text.items.iter_mut().find(|(k, _)| k.is("EngineData")) {
+ Some(item) => item.1 = photocraft_psd::descriptor::Value::RawData(raw),
+ None => return None,
+ }
+ Some(write_tysh(&t))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::text::{TextAlign, TextRun};
+ use photocraft_doc::text_styles::{CharacterStyleDef, ParagraphStyleDef, diff_attrs};
+
+ #[test]
+ fn named_sheets_round_trip() {
+ let mut styles = TextStyles::default();
+ styles.character.push(CharacterStyleDef { id: 4, name: "Emphasis".into(), attrs: diff_attrs(&CharStyle { size_pt: 30.0, underline: true, ..Default::default() }, &CharStyle::default()) });
+ styles.paragraph.push(ParagraphStyleDef { id: 2, name: "Centered".into(), para_attrs: diff_attrs(&ParagraphStyle { align: TextAlign::Center, ..Default::default() }, &ParagraphStyle::default()), ..Default::default() });
+ let base = CharStyle { font_family: crate::fonts::DEFAULT_FAMILY.into(), ..Default::default() };
+ let emph = styles.resolve_char(Some(2), Some(4), crate::fonts::DEFAULT_FAMILY);
+ let mut layer = TextLayer {
+ text: "plain bold".into(),
+ runs: vec![TextRun { len: 6, style: base.clone() }, TextRun { len: 4, style: emph }],
+ paragraphs: vec![photocraft_doc::text::ParagraphRun { len: 10, style: styles.resolve_para(Some(2)) }],
+ ..Default::default()
+ };
+ layer.sync_summary();
+ let tysh = crate::psd::build_tysh(&layer, 72.0, None);
+ assert!(!has_named_sheets(&tysh));
+ let out = write_style_sheets(&tysh, &layer, &styles, 72.0).unwrap();
+ assert!(has_named_sheets(&out));
+ let r = read_style_sheets(&out, 72.0).unwrap();
+ assert_eq!(r.char_sheets.len(), 1);
+ assert_eq!(r.char_sheets[0].1, "Emphasis");
+ assert_eq!((r.char_sheets[0].2.size_pt, r.char_sheets[0].2.underline), (30.0, true));
+ assert_eq!(r.para_sheets[0].1, "Centered");
+ assert_eq!(r.para_sheets[0].2.align, TextAlign::Center);
+ assert_eq!(r.run_char, vec![None, Some(1)]);
+ assert_eq!(r.run_para, vec![Some(1)]);
+ // The text itself still reads back the same.
+ let back = crate::psd::text_layer_from_tysh(&out, 72.0).unwrap();
+ assert_eq!(back.text, layer.text);
+ assert_eq!(back.char_runs()[1].style.size_pt, 30.0);
+ // No styles: the sets shrink back to the normal sheets.
+ let plain = write_style_sheets(&out, &layer, &TextStyles::default(), 72.0).unwrap();
+ assert!(!has_named_sheets(&plain));
+ assert!(read_style_sheets(&plain, 72.0).unwrap().run_char.iter().all(Option::is_none));
+ }
+
+ #[test]
+ fn malformed_input() {
+ assert!(read_style_sheets(&[], 72.0).is_none());
+ assert!(read_style_sheets(&[0u8; 60], 72.0).is_none());
+ assert!(!has_named_sheets(b"junk"));
+ assert!(write_style_sheets(&[1, 2, 3], &TextLayer::default(), &TextStyles::default(), 72.0).is_none());
+ }
+}
diff --git a/crates/text/src/spell.rs b/crates/text/src/spell.rs
new file mode 100644
index 000000000..57076991e
--- /dev/null
+++ b/crates/text/src/spell.rs
@@ -0,0 +1,318 @@
+//! Spelling checker for Edit › Check Spelling.
+//!
+//! The dictionary is SCOWL size 50 (American English, ~72k words; see
+//! `assets/dict/LICENSE-SCOWL.txt`), gzip-compressed into the binary and decoded on first use.
+//! Words are grouped by SCOWL level (10 = most common … 50), which ranks suggestions.
+//!
+//! Case rules follow common spell checkers: a lowercase dictionary word may be written
+//! capitalised or in all caps; a capitalised entry (proper noun) must keep its capital. Trailing
+//! possessive `'s` is ignored, typographic apostrophes count as `'`, and tokens containing digits
+//! are skipped.
+
+use std::collections::{HashMap, HashSet};
+use std::io::Read;
+use std::sync::OnceLock;
+
+static WORDS_GZ: &[u8] = include_bytes!("../../../assets/dict/en_US-scowl-50.txt.gz");
+
+/// A word list with frequency levels.
+pub struct Dictionary {
+ /// Word (as listed) → SCOWL level.
+ words: HashMap<String, u8>,
+ /// Lowercase form → listed forms (for case-insensitive lookups and suggestions).
+ by_lower: HashMap<String, Vec<String>>,
+ /// Lowercase words grouped by char length, for suggestions.
+ by_len: Vec<Vec<(String, Vec<char>, u8)>>,
+}
+
+/// A misspelled word in a string.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Misspelling {
+ /// Byte range in the checked text.
+ pub start: usize,
+ pub end: usize,
+ pub word: String,
+}
+
+impl Dictionary {
+ /// The bundled English dictionary (decoded once).
+ pub fn english() -> &'static Dictionary {
+ static D: OnceLock<Dictionary> = OnceLock::new();
+ D.get_or_init(|| {
+ let mut s = String::new();
+ let _ = flate2::read::GzDecoder::new(WORDS_GZ).read_to_string(&mut s);
+ Dictionary::from_list(&s)
+ })
+ }
+
+ /// Builds a dictionary from one word per line; `#NN` lines set the level of the words after.
+ pub fn from_list(list: &str) -> Dictionary {
+ let mut words = HashMap::new();
+ let mut by_lower: HashMap<String, Vec<String>> = HashMap::new();
+ let mut level = 50u8;
+ for line in list.lines() {
+ let w = line.trim();
+ if let Some(l) = w.strip_prefix('#') {
+ level = l.parse().unwrap_or(level);
+ continue;
+ }
+ if w.is_empty() || words.contains_key(w) {
+ continue;
+ }
+ words.insert(w.to_string(), level);
+ by_lower.entry(w.to_lowercase()).or_default().push(w.to_string());
+ }
+ let mut by_len: Vec<Vec<(String, Vec<char>, u8)>> = Vec::new();
+ for (lw, forms) in &by_lower {
+ let n = lw.chars().count();
+ if by_len.len() <= n {
+ by_len.resize(n + 1, Vec::new());
+ }
+ let lvl = forms.iter().filter_map(|f| words.get(f)).min().copied().unwrap_or(50);
+ by_len[n].push((lw.clone(), lw.chars().collect(), lvl));
+ }
+ for v in &mut by_len {
+ v.sort();
+ }
+ Dictionary { words, by_lower, by_len }
+ }
+
+ pub fn len(&self) -> usize {
+ self.words.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.words.is_empty()
+ }
+
+ /// Whether `word` is spelled correctly (also accepting `user` words, compared without case).
+ pub fn check(&self, word: &str, user: &HashSet<String>) -> bool {
+ let w = normalize(word);
+ let w = w.strip_suffix("'s").filter(|b| !b.is_empty()).unwrap_or(&w);
+ let w = w.trim_matches('\'');
+ if w.is_empty() || w.chars().any(|c| c.is_numeric()) || !w.chars().any(char::is_alphabetic) {
+ return true;
+ }
+ let lower = w.to_lowercase();
+ if user.contains(&lower) || self.words.contains_key(w) {
+ return true;
+ }
+ let Some(forms) = self.by_lower.get(&lower) else { return false };
+ let all_caps = w.chars().filter(|c| c.is_alphabetic()).all(char::is_uppercase);
+ let first_cap = w.chars().next().is_some_and(char::is_uppercase) && w.chars().skip(1).all(|c| !c.is_uppercase());
+ forms.iter().any(|f| {
+ let f_lower = f.chars().all(|c| !c.is_uppercase());
+ // "the" → "The"/"THE"; "Paris" → "PARIS"; "NASA" stays as listed (exact match above).
+ all_caps || (f_lower && first_cap) || (first_cap && capitalize(f) == w)
+ })
+ }
+
+ /// Up to `max` suggestions for a misspelled word, nearest first (then most common), with the
+ /// word's case pattern applied.
+ pub fn suggest(&self, word: &str, max: usize) -> Vec<String> {
+ let w = normalize(word);
+ let lower = w.to_lowercase();
+ let lc: Vec<char> = lower.chars().collect();
+ let n = lc.len();
+ let max_d = if n <= 4 { 1 } else { 2 };
+ // Same letters in another order (transposed typing) ranks first among equal distances.
+ let mut sorted = lc.clone();
+ sorted.sort_unstable();
+ let anagram = |c: &str| {
+ let mut v: Vec<char> = c.chars().collect();
+ v.sort_unstable();
+ v == sorted
+ };
+ let mut found: Vec<(usize, bool, u8, &str)> = Vec::new();
+ let mut rows = Rows::default();
+ for len in n.saturating_sub(max_d)..=(n + max_d) {
+ let Some(bucket) = self.by_len.get(len) else { continue };
+ for (cand, cc, lvl) in bucket {
+ if let Some(d) = distance(&lc, cc, max_d, &mut rows) {
+ found.push((d, !anagram(cand), *lvl, cand));
+ }
+ }
+ }
+ found.sort();
+ let all_caps = w.chars().filter(|c| c.is_alphabetic()).all(char::is_uppercase) && w.chars().filter(|c| c.is_alphabetic()).count() > 1;
+ let first_cap = w.chars().next().is_some_and(char::is_uppercase);
+ let mut out: Vec<String> = Vec::new();
+ for (_, _, _, cand) in found {
+ // Common (lowercase) forms before proper nouns: "brwon" → "brown", then "Brown".
+ let mut forms: Vec<&String> = self.by_lower.get(cand).into_iter().flatten().collect();
+ forms.sort_by_key(|f| f.chars().any(char::is_uppercase));
+ for form in forms {
+ let s = if all_caps {
+ form.to_uppercase()
+ } else if first_cap {
+ capitalize(form)
+ } else {
+ form.clone()
+ };
+ if !out.contains(&s) && s != w {
+ out.push(s);
+ }
+ }
+ if out.len() >= max {
+ break;
+ }
+ }
+ out.truncate(max);
+ out
+ }
+
+ /// Misspelled words of `text` in order.
+ pub fn misspellings(&self, text: &str, user: &HashSet<String>) -> Vec<Misspelling> {
+ words(text)
+ .into_iter()
+ .filter(|(a, b)| !self.check(&text[*a..*b], user))
+ .map(|(a, b)| Misspelling { start: a, end: b, word: text[a..b].to_string() })
+ .collect()
+ }
+}
+
+/// Typographic apostrophes → `'`.
+fn normalize(w: &str) -> String {
+ w.replace(['\u{2019}', '\u{2018}', '\u{02BC}'], "'")
+}
+
+fn capitalize(w: &str) -> String {
+ let mut c = w.chars();
+ match c.next() {
+ Some(f) => f.to_uppercase().chain(c).collect(),
+ None => String::new(),
+ }
+}
+
+/// Byte ranges of the words in `text`: letters/digits with inner apostrophes (hyphens split).
+pub fn words(text: &str) -> Vec<(usize, usize)> {
+ let is_apos = |c: char| matches!(c, '\'' | '\u{2019}' | '\u{02BC}');
+ let mut out = Vec::new();
+ let mut start: Option<usize> = None;
+ let chars: Vec<(usize, char)> = text.char_indices().collect();
+ for (i, &(b, c)) in chars.iter().enumerate() {
+ let inner_apos = is_apos(c) && start.is_some() && chars.get(i + 1).is_some_and(|(_, n)| n.is_alphabetic());
+ if c.is_alphanumeric() || inner_apos {
+ start.get_or_insert(b);
+ } else if let Some(s) = start.take() {
+ out.push((s, b));
+ }
+ }
+ if let Some(s) = start {
+ out.push((s, text.len()));
+ }
+ out
+}
+
+/// Scratch rows for [`distance`].
+#[derive(Default)]
+struct Rows {
+ prev2: Vec<usize>,
+ prev: Vec<usize>,
+ cur: Vec<usize>,
+}
+
+/// Damerau–Levenshtein (optimal string alignment) distance, or None when above `max`.
+fn distance(a: &[char], b: &[char], max: usize, rows: &mut Rows) -> Option<usize> {
+ let (n, m) = (a.len(), b.len());
+ if n.abs_diff(m) > max {
+ return None;
+ }
+ let Rows { prev2, prev, cur } = rows;
+ prev2.clear();
+ prev2.resize(m + 1, 0);
+ prev.clear();
+ prev.extend(0..=m);
+ cur.clear();
+ cur.resize(m + 1, 0);
+ for i in 1..=n {
+ cur[0] = i;
+ let mut row_min = cur[0];
+ for j in 1..=m {
+ let cost = usize::from(a[i - 1] != b[j - 1]);
+ let mut v = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
+ if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
+ v = v.min(prev2[j - 2] + 1);
+ }
+ cur[j] = v;
+ row_min = row_min.min(v);
+ }
+ if row_min > max {
+ return None;
+ }
+ std::mem::swap(prev2, prev);
+ std::mem::swap(prev, cur);
+ }
+ (prev[m] <= max).then_some(prev[m])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn none() -> HashSet<String> {
+ HashSet::new()
+ }
+
+ #[test]
+ fn bundled_dictionary_loads() {
+ let d = Dictionary::english();
+ assert!(d.len() > 70_000, "{}", d.len());
+ for w in ["the", "The", "THE", "color", "colors", "running", "don't", "don’t", "Paris", "PARIS", "photographer's", "NASA"] {
+ assert!(d.check(w, &none()), "{w}");
+ }
+ for w in ["teh", "recieve", "paris", "Photograpy", "zxqv"] {
+ assert!(!d.check(w, &none()), "{w}");
+ }
+ // Numbers and symbols are never flagged.
+ assert!(d.check("2026", &none()) && d.check("B2B", &none()));
+ }
+
+ #[test]
+ fn suggestions_rank_by_distance_then_frequency() {
+ let d = Dictionary::english();
+ assert_eq!(d.suggest("teh", 3)[0], "the");
+ assert!(d.suggest("recieve", 5).contains(&"receive".to_string()));
+ assert_eq!(d.suggest("Wrold", 1), vec!["World".to_string()]);
+ assert_eq!(d.suggest("brwon", 1), vec!["brown".to_string()]);
+ assert_eq!(d.suggest("HELO", 5).first().map(|s| s.chars().all(|c| c.is_uppercase())), Some(true));
+ }
+
+ #[test]
+ fn misspellings_and_user_words() {
+ let d = Dictionary::from_list("#10\nhello\nworld\nParis\n");
+ let text = "Hello wrld, Paris paris photocraft 42x";
+ let m: Vec<String> = d.misspellings(text, &none()).into_iter().map(|m| m.word).collect();
+ assert_eq!(m, vec!["wrld", "paris", "photocraft"]);
+ let user: HashSet<String> = ["photocraft".to_string()].into();
+ assert_eq!(d.misspellings(text, &user).len(), 2);
+ let mm = &d.misspellings(text, &none())[0];
+ assert_eq!(&text[mm.start..mm.end], "wrld");
+ }
+
+ /// `cargo test --release -p photocraft-text -- --ignored --nocapture spell_timing`
+ #[test]
+ #[ignore]
+ fn spell_timing() {
+ let t = std::time::Instant::now();
+ let d = Dictionary::english();
+ let load = t.elapsed();
+ let t = std::time::Instant::now();
+ for w in ["recieve", "teh", "photograpy", "definately", "seperate", "wierd", "acommodate", "begining", "occurence", "untill"] {
+ let _ = d.suggest(w, 8);
+ }
+ eprintln!("load {load:?}, suggest {:?}/word", t.elapsed() / 10);
+ }
+
+ #[test]
+ fn tokenizer_and_distance() {
+ let t = "it's well-known 'quoted' café";
+ let w: Vec<&str> = words(t).into_iter().map(|(a, b)| &t[a..b]).collect();
+ assert_eq!(w, vec!["it's", "well", "known", "quoted", "café"]);
+ let c = |s: &str| s.chars().collect::<Vec<char>>();
+ let mut r = Rows::default();
+ assert_eq!(distance(&c("teh"), &c("the"), 2, &mut r), Some(1));
+ assert_eq!(distance(&c("teh"), &c("toe"), 2, &mut r), Some(2));
+ assert_eq!(distance(&c("teh"), &c("banana"), 2, &mut r), None);
+ }
+}
diff --git a/crates/ui-egui/src/analysis_ui.rs b/crates/ui-egui/src/analysis_ui.rs
new file mode 100644
index 000000000..a24bdc905
--- /dev/null
+++ b/crates/ui-egui/src/analysis_ui.rs
@@ -0,0 +1,959 @@
+//! Image › Analysis and Notes in the shell: the Ruler, Count and Note tools (eyedropper group),
+//! their canvas overlays and options bars, Window › Measurement Log and Window › Notes, and the
+//! Set Measurement Scale / Select Data Points / Place Scale Marker dialogs.
+//!
+//! Every change goes through engine commands (`image.analysis.*`, `count.*`, `notes.*`,
+//! `measurementLog.*`); this module only holds view state ([`AnalysisUi`], part of the
+//! serialisable UI state so the control channel can read and drive it).
+
+use egui::{Align2, Color32, CornerRadius, FontId, Pos2, RichText, Stroke, pos2, vec2};
+use photocraft_doc::{Document, Ruler};
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+use crate::state::Tool;
+use crate::theme::Tokens;
+
+/// What a pointer drag is doing (not serialised).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Drag {
+ /// New ruler line from a point.
+ RulerNew,
+ /// Moving a ruler handle: 0 start, 1 end, 2 protractor end.
+ RulerHandle(u8),
+ /// Moving count marker (group, index) from where it was.
+ Count(usize, usize, [f64; 2]),
+ /// Moving note `index`: grab offset from its position.
+ Note(usize, [f64; 2]),
+}
+
+/// View state of the analysis tools and panels.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct AnalysisUi {
+ /// Window › Measurement Log / Notes panels.
+ pub measurement_log: bool,
+ pub notes: bool,
+ /// Measurement Log rows selected (row ids).
+ pub log_selected: Vec<u64>,
+ /// Notes panel: the note shown (index).
+ pub note_selected: Option<usize>,
+ /// Note tool options: author and colour of new notes.
+ pub note_author: String,
+ pub note_color: [f32; 3],
+ /// Ruler options bar: show values in the measurement scale's units.
+ pub use_measurement_scale: bool,
+ /// Open dialog: (kind, fields). Kinds: "scale", "dataPoints", "scaleMarker".
+ pub dialog: Option<(String, Map<String, Value>)>,
+ #[serde(skip)]
+ pub drag: Option<Drag>,
+}
+
+impl Default for AnalysisUi {
+ fn default() -> Self {
+ Self { measurement_log: false, notes: false, log_selected: Vec::new(), note_selected: None, note_author: String::new(), note_color: [1.0, 1.0, 0.51], use_measurement_scale: false, dialog: None, drag: None }
+ }
+}
+
+const PANELS: [&str; 2] = ["window.panel.measurementLog", "window.panel.notes"];
+
+/// Menu ids handled here (live menu items).
+pub fn handles(id: &str) -> bool {
+ PANELS.contains(&id)
+}
+
+pub fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ match id {
+ "window.panel.measurementLog" => Some(app.ui.analysis.measurement_log),
+ "window.panel.notes" => Some(app.ui.analysis.notes),
+ "image.analysis.rulerTool" => Some(app.ui.tool == Tool::Ruler),
+ "image.analysis.countTool" => Some(app.ui.tool == Tool::Count),
+ _ => {
+ // View › Proof Setup simulations: checked while that proof is shown.
+ let kind = id.strip_prefix("view.proofSetup.").and_then(photocraft_engine::proof_sim::ProofKind::from_id)?;
+ let d = app.session.active()?;
+ let pv = app.session.color.proof(d.doc.id);
+ Some(pv.enabled && pv.setup.kind == kind)
+ }
+ }
+}
+
+fn no_params(p: &Value) -> bool {
+ p.as_object().is_none_or(|o| o.is_empty())
+}
+
+fn fields(v: Value) -> Map<String, Value> {
+ v.as_object().cloned().unwrap_or_default()
+}
+
+/// Menu front ends: panel toggles, tool selection, dialogs and pickers in front of the engine's
+/// analysis commands. `None` when `id` isn't ours (or the engine should run it directly).
+pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ let a = &mut app.ui.analysis;
+ match id {
+ "window.panel.measurementLog" | "window.panel.notes" => {
+ let slot = if id.ends_with("measurementLog") { &mut a.measurement_log } else { &mut a.notes };
+ *slot = params.get("show").and_then(Value::as_bool).unwrap_or(!*slot);
+ return Some(Ok(json!({"visible": *slot})));
+ }
+ _ => {}
+ }
+ if !no_params(params) {
+ return None;
+ }
+ let doc = app.session.active().map(|d| d.doc.clone());
+ Some(match id {
+ "image.analysis.rulerTool" => {
+ app.ui.tool = Tool::Ruler;
+ Ok(json!({"tool": "Ruler"}))
+ }
+ "image.analysis.countTool" => {
+ app.ui.tool = Tool::Count;
+ Ok(json!({"tool": "Count"}))
+ }
+ "image.analysis.setMeasurementScale" => {
+ let d = doc?;
+ let sc = &d.measurement.scale;
+ open(app, "scale", json!({"preset": if sc.is_default() { "default" } else { "custom" }, "pixelLength": sc.pixel_length, "logicalLength": sc.logical_length, "units": sc.units}))
+ }
+ "image.analysis.selectDataPoints" => {
+ let dp = serde_json::to_value(&app.session.analysis.data_points).unwrap_or_default();
+ open(app, "dataPoints", dp)
+ }
+ "image.analysis.placeScaleMarker" => {
+ let d = doc?;
+ let units = d.measurement.scale.units.clone();
+ open(app, "scaleMarker", json!({"length": suggested_length(&d), "units": units, "fontSize": 12.0, "displayText": true, "textPosition": "bottom", "color": "black"}))
+ }
+ "image.analysis.recordMeasurements" => {
+ // The current tool picks the source, as in Photoshop.
+ let source = match app.ui.tool {
+ Tool::Ruler => "ruler",
+ Tool::Count => "count",
+ _ => "auto",
+ };
+ let r = app.run(id, json!({"source": source}));
+ if r.is_ok() {
+ app.ui.analysis.measurement_log = true;
+ }
+ r
+ }
+ "file.import.notes" => {
+ let (name, bytes) = app.services.pick_open.as_mut().and_then(|f| f())?;
+ let r = photocraft_engine::notes_cmds::import_notes_from(&mut app.session, &name, &bytes).map_err(|e| e.to_string());
+ if r.is_ok() {
+ app.ui.analysis.notes = true;
+ app.sync_views();
+ }
+ r
+ }
+ "measurementLog.export" => export_log(app, None),
+ _ => return None,
+ })
+}
+
+fn open(app: &mut PhotocraftApp, kind: &str, f: Value) -> Result<Value, String> {
+ app.ui.analysis.dialog = Some((kind.to_string(), fields(f)));
+ Ok(json!({"dialog": kind}))
+}
+
+/// A "nice" bar length near a fifth of the image width (same rule as the engine default).
+fn suggested_length(d: &Document) -> f64 {
+ let target = f64::from(d.size.width) / 5.0 * d.measurement.scale.factor();
+ let e = 10f64.powf(target.log10().floor());
+ [5.0, 2.0, 1.0].into_iter().map(|m| m * e).find(|v| *v <= target).unwrap_or(e)
+}
+
+/// Export the Measurement Log (or the given rows) as CSV through the save picker.
+fn export_log(app: &mut PhotocraftApp, rows: Option<Vec<u64>>) -> Result<Value, String> {
+ let p = rows.map_or(json!({}), |r| json!({"rows": r}));
+ let csv = app.run("measurementLog.export", p)?;
+ let text = csv["csv"].as_str().unwrap_or_default().to_string();
+ let path = app.services.pick_save.as_mut().and_then(|f| f("Measurements.csv")).ok_or("cancelled")?;
+ let write = app.services.write.as_mut().ok_or("no writer configured")?;
+ write(&path, text.as_bytes())?;
+ Ok(json!({"path": path, "rows": csv["rows"]}))
+}
+
+// ------------------------------------------------------------------ tools
+
+fn tolerance(app: &PhotocraftApp) -> f64 {
+ 7.0 / f64::from(app.current_zoom().max(0.01))
+}
+
+fn dist(a: [f64; 2], b: [f64; 2]) -> f64 {
+ (a[0] - b[0]).hypot(a[1] - b[1])
+}
+
+/// Shift constrains to 45° steps around `from`.
+fn constrain(from: [f64; 2], to: [f64; 2], shift: bool) -> [f64; 2] {
+ if !shift {
+ return to;
+ }
+ let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
+ let a = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4;
+ let l = dx.hypot(dy);
+ [from[0] + l * a.cos(), from[1] + l * a.sin()]
+}
+
+fn set_ruler(app: &mut PhotocraftApp, r: Ruler) {
+ let _ = app.run("image.analysis.rulerTool", json!({"start": r.start, "end": r.end, "protractor": r.protractor}));
+}
+
+/// Pointer input for the Ruler, Count and Note tools. Returns true when consumed.
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
+ let tool = app.ui.tool;
+ if !matches!(tool, Tool::Ruler | Tool::Count | Tool::Note) {
+ return false;
+ }
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return true };
+ let tol = tolerance(app);
+ match (tool, ev) {
+ (Tool::Ruler, ToolEvent::Down { x, y, .. }) => {
+ let p = [x, y];
+ let cur = doc.measurement.ruler;
+ let near = |q: [f64; 2]| dist(p, q) <= tol;
+ match cur {
+ // ⌥-drag from an end point starts the protractor arm at that vertex.
+ Some(mut r) if mods.alt && (near(r.start) || near(r.end)) => {
+ if near(r.end) && !near(r.start) {
+ std::mem::swap(&mut r.start, &mut r.end);
+ }
+ r.protractor = Some(p);
+ set_ruler(app, r);
+ app.ui.analysis.drag = Some(Drag::RulerHandle(2));
+ }
+ Some(r) if r.protractor.is_some_and(near) => app.ui.analysis.drag = Some(Drag::RulerHandle(2)),
+ Some(r) if near(r.end) => app.ui.analysis.drag = Some(Drag::RulerHandle(1)),
+ Some(r) if near(r.start) => app.ui.analysis.drag = Some(Drag::RulerHandle(0)),
+ _ => {
+ set_ruler(app, Ruler { start: p, end: p, protractor: None });
+ app.ui.analysis.drag = Some(Drag::RulerNew);
+ }
+ }
+ }
+ (Tool::Ruler, ToolEvent::Move { x, y, .. }) => {
+ let (Some(drag), Some(mut r)) = (app.ui.analysis.drag, doc.measurement.ruler) else { return true };
+ match drag {
+ Drag::RulerNew | Drag::RulerHandle(1) => r.end = constrain(r.start, [x, y], mods.shift),
+ Drag::RulerHandle(0) => r.start = constrain(r.end, [x, y], mods.shift),
+ Drag::RulerHandle(_) => r.protractor = Some(constrain(r.start, [x, y], mods.shift)),
+ _ => return true,
+ }
+ set_ruler(app, r);
+ }
+ (Tool::Ruler, ToolEvent::Up { .. }) => {
+ if app.ui.analysis.drag.take() == Some(Drag::RulerNew) && doc.measurement.ruler.is_some_and(|r| dist(r.start, r.end) < 0.5) {
+ let _ = app.run("image.analysis.rulerTool", json!({"clear": true}));
+ }
+ }
+ (Tool::Count, ToolEvent::Down { x, y, .. }) => {
+ let hit = nearest_marker(&doc, [x, y], tol);
+ match hit {
+ Some((g, i)) if mods.alt => {
+ let _ = app.run("count.remove", json!({"group": g, "index": i}));
+ }
+ Some((g, i)) => app.ui.analysis.drag = Some(Drag::Count(g, i, [x, y])),
+ None if !mods.alt => {
+ let _ = app.run("count.add", json!({"x": x, "y": y}));
+ }
+ None => {}
+ }
+ }
+ (Tool::Count, ToolEvent::Up { x, y }) => {
+ if let Some(Drag::Count(g, i, from)) = app.ui.analysis.drag.take()
+ && dist(from, [x, y]) > 0.5
+ {
+ let _ = app.run("count.move", json!({"group": g, "index": i, "to": [x, y]}));
+ }
+ }
+ (Tool::Note, ToolEvent::Down { x, y, .. }) => {
+ let z = f64::from(app.current_zoom().max(0.01));
+ let hit = doc.notes.iter().rposition(|n| x >= n.position[0] && x <= n.position[0] + 16.0 / z && y >= n.position[1] && y <= n.position[1] + 20.0 / z);
+ match hit {
+ Some(i) => {
+ app.ui.analysis.note_selected = Some(i);
+ app.ui.analysis.notes = true;
+ app.ui.analysis.drag = Some(Drag::Note(i, [x - doc.notes[i].position[0], y - doc.notes[i].position[1]]));
+ }
+ None => {
+ let a = &app.ui.analysis;
+ let p = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": [a.note_color[0], a.note_color[1], a.note_color[2]]});
+ if let Ok(r) = app.run("notes.add", p) {
+ app.ui.analysis.note_selected = r["index"].as_u64().map(|v| v as usize);
+ app.ui.analysis.notes = true;
+ }
+ }
+ }
+ }
+ (Tool::Note, ToolEvent::Up { x, y }) => {
+ if let Some(Drag::Note(i, off)) = app.ui.analysis.drag.take() {
+ let to = [(x - off[0]).round(), (y - off[1]).round()];
+ if doc.notes.get(i).is_some_and(|n| dist(n.position, to) >= 1.0) {
+ let _ = app.run("notes.set", json!({"index": i, "x": to[0], "y": to[1]}));
+ }
+ }
+ }
+ _ => {}
+ }
+ true
+}
+
+fn nearest_marker(d: &Document, at: [f64; 2], tol: f64) -> Option<(usize, usize)> {
+ let mut best: Option<(f64, usize, usize)> = None;
+ for (gi, g) in d.measurement.count_groups.iter().enumerate().filter(|(_, g)| g.visible) {
+ for (pi, q) in g.points.iter().enumerate() {
+ let dd = dist(*q, at);
+ if dd <= tol && best.is_none_or(|b| dd < b.0) {
+ best = Some((dd, gi, pi));
+ }
+ }
+ }
+ best.map(|b| (b.1, b.2))
+}
+
+fn color32(c: [f32; 3]) -> Color32 {
+ Color32::from_rgb((c[0].clamp(0.0, 1.0) * 255.0) as u8, (c[1].clamp(0.0, 1.0) * 255.0) as u8, (c[2].clamp(0.0, 1.0) * 255.0) as u8)
+}
+
+fn handle(painter: &egui::Painter, p: Pos2) {
+ for (w, c) in [(3.0, Color32::BLACK), (1.0, Color32::WHITE)] {
+ painter.line_segment([p - vec2(5.0, 0.0), p + vec2(5.0, 0.0)], Stroke::new(w, c));
+ painter.line_segment([p - vec2(0.0, 5.0), p + vec2(0.0, 5.0)], Stroke::new(w, c));
+ }
+}
+
+/// Ruler line (while the Ruler tool is active), count markers and note icons.
+pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
+ let v = &app.ui.view;
+ if app.ui.tool == Tool::Ruler
+ && let Some(r) = doc.measurement.ruler
+ {
+ let s = xf.to_screen(r.start[0] as f32, r.start[1] as f32);
+ let e = xf.to_screen(r.end[0] as f32, r.end[1] as f32);
+ let mut segs = vec![[s, e]];
+ if let Some(q) = r.protractor {
+ segs.push([s, xf.to_screen(q[0] as f32, q[1] as f32)]);
+ }
+ for seg in &segs {
+ painter.line_segment(*seg, Stroke::new(3.0, Color32::from_black_alpha(160)));
+ painter.line_segment(*seg, Stroke::new(1.0, Color32::WHITE));
+ handle(painter, seg[1]);
+ }
+ handle(painter, s);
+ }
+ if v.shows(v.show.count) {
+ for g in doc.measurement.count_groups.iter().filter(|g| g.visible) {
+ let c = color32(g.color.to_rgb());
+ for (i, p) in g.points.iter().enumerate() {
+ let at = xf.to_screen(p[0] as f32, p[1] as f32);
+ painter.circle_filled(at, 1.0 + g.marker_size as f32, c);
+ let font = FontId::proportional(g.label_size as f32);
+ painter.text(at + vec2(2.0 + g.marker_size as f32, -1.0), Align2::LEFT_BOTTOM, format!("{}", i + 1), font, c);
+ }
+ }
+ }
+ if v.shows(v.show.notes) {
+ for (i, n) in doc.notes.iter().enumerate() {
+ let p = xf.to_screen(n.position[0] as f32, n.position[1] as f32);
+ let r = egui::Rect::from_min_size(p, vec2(16.0, 20.0));
+ let fill = color32(n.color.to_rgb());
+ painter.rect_filled(r, CornerRadius::same(2), fill);
+ let sel = app.ui.analysis.note_selected == Some(i);
+ painter.rect_stroke(r, CornerRadius::same(2), Stroke::new(if sel { 2.0 } else { 1.0 }, if sel { Color32::WHITE } else { Color32::from_black_alpha(200) }), egui::StrokeKind::Outside);
+ // Folded corner and text lines.
+ let ink = Color32::from_black_alpha(140);
+ painter.line_segment([r.right_top() + vec2(-5.0, 0.0), r.right_top() + vec2(0.0, 5.0)], Stroke::new(1.0, ink));
+ for k in 0..3 {
+ let y = r.top() + 7.0 + 4.0 * k as f32;
+ painter.line_segment([pos2(r.left() + 3.0, y), pos2(r.right() - 3.0, y)], Stroke::new(1.0, ink));
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------ options bars
+
+fn readout(ui: &mut egui::Ui, label: &str, value: Option<f64>) {
+ let t = Tokens::get(ui.ctx());
+ ui.label(RichText::new(label).color(t.text_dim).size(11.0));
+ ui.label(RichText::new(value.map_or(String::new(), |v| format!("{v:.2}"))).color(t.text).size(11.0).monospace());
+ ui.add_space(6.0);
+}
+
+/// Options bar of the Ruler, Count and Note tools. Returns true when drawn.
+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return matches!(tool, Tool::Ruler | Tool::Count | Tool::Note) };
+ match tool {
+ Tool::Ruler => {
+ let sc = doc.measurement.scale.clone();
+ let f = if app.ui.analysis.use_measurement_scale { sc.factor() } else { 1.0 };
+ let info = doc.measurement.ruler.map(|r| photocraft_engine::analysis_cmds::ruler_info(&r, &sc));
+ let g = |k: &str| info.as_ref().and_then(|i| i[k].as_f64());
+ readout(ui, "X:", g("x").map(|v| v * f));
+ readout(ui, "Y:", g("y").map(|v| v * f));
+ readout(ui, "W:", g("w").map(|v| v * f));
+ readout(ui, "H:", g("h").map(|v| v * f));
+ readout(ui, "A:", g("angle"));
+ readout(ui, "L1:", g("l1").map(|v| v * f));
+ readout(ui, "L2:", g("l2").map(|v| v * f));
+ crate::widgets::vline(ui, 22.0);
+ crate::widgets::checkbox(ui, &mut app.ui.analysis.use_measurement_scale, "Use Measurement Scale");
+ let has = doc.measurement.ruler.is_some();
+ if ui.add_enabled_ui(has, |ui| crate::widgets::secondary_button(ui, "Straighten Layer", 0.0)).inner.clicked() {
+ let _ = app.run("image.analysis.straightenLayer", json!({}));
+ }
+ if ui.add_enabled_ui(has, |ui| crate::widgets::secondary_button(ui, "Clear", 0.0)).inner.clicked() {
+ let _ = app.run("image.analysis.rulerTool", json!({"clear": true}));
+ }
+ true
+ }
+ Tool::Count => {
+ let t = Tokens::get(ui.ctx());
+ let m = &doc.measurement;
+ ui.label(RichText::new(format!("Count: {}", m.count_total())).color(t.text).size(11.0));
+ crate::widgets::vline(ui, 22.0);
+ if !m.count_groups.is_empty() {
+ let mut gi = m.active_count_group.min(m.count_groups.len() - 1);
+ let opts: Vec<(usize, &str)> = m.count_groups.iter().enumerate().map(|(i, g)| (i, g.name.as_str())).collect();
+ if crate::widgets::dropdown(ui, "count-group", &mut gi, &opts, 140.0) {
+ let _ = app.run("count.setGroup", json!({"group": gi, "active": true}));
+ }
+ let g = &m.count_groups[gi];
+ let eye = if g.visible { "eye" } else { "eye-off" };
+ if crate::icons::button(ui, eye, 22.0, false, "Toggle count group visibility").clicked() {
+ let _ = app.run("count.setGroup", json!({"group": gi, "visible": !g.visible}));
+ }
+ let mut rgb = g.color.to_rgb();
+ if ui.color_edit_button_rgb(&mut rgb).changed() {
+ let _ = app.run("count.setGroup", json!({"group": gi, "color": [rgb[0], rgb[1], rgb[2]], "coalesce": "count-color"}));
+ }
+ if crate::icons::button(ui, "trash", 22.0, false, "Delete count group").clicked() {
+ let _ = app.run("count.deleteGroup", json!({"group": gi}));
+ }
+ }
+ if crate::icons::button(ui, "folder-plus", 22.0, false, "Create a new count group").clicked() {
+ let _ = app.run("count.newGroup", json!({}));
+ }
+ if crate::widgets::secondary_button(ui, "Clear", 0.0).clicked() && m.count_total() > 0 {
+ let _ = app.run("count.clear", json!({}));
+ }
+ if let Some(g) = m.count_groups.get(m.active_count_group) {
+ crate::widgets::vline(ui, 22.0);
+ let (mut ms, mut ls) = (g.marker_size as f32, g.label_size as f32);
+ ui.label(RichText::new("Marker Size").color(t.text_dim).size(11.0));
+ let a = crate::widgets::value_field(ui, &mut ms, 1.0..=10.0, "", 40.0).changed();
+ ui.label(RichText::new("Label Size").color(t.text_dim).size(11.0));
+ let b = crate::widgets::value_field(ui, &mut ls, 8.0..=72.0, "", 44.0).changed();
+ if a || b {
+ let _ = app.run("count.setGroup", json!({"markerSize": ms.round(), "labelSize": ls.round()}));
+ }
+ }
+ true
+ }
+ Tool::Note => {
+ let t = Tokens::get(ui.ctx());
+ ui.label(RichText::new("Author:").color(t.text_dim).size(11.0));
+ ui.add(egui::TextEdit::singleline(&mut app.ui.analysis.note_author).desired_width(120.0));
+ ui.label(RichText::new("Color:").color(t.text_dim).size(11.0));
+ ui.color_edit_button_rgb(&mut app.ui.analysis.note_color);
+ if ui.add_enabled_ui(!doc.notes.is_empty(), |ui| crate::widgets::secondary_button(ui, "Clear All", 0.0)).inner.clicked() {
+ let _ = app.run("notes.delete", json!({"all": true}));
+ app.ui.analysis.note_selected = None;
+ }
+ if crate::icons::button(ui, "message-square", 22.0, app.ui.analysis.notes, "Show or hide the Notes panel").clicked() {
+ app.ui.analysis.notes = !app.ui.analysis.notes;
+ }
+ true
+ }
+ _ => false,
+ }
+}
+
+// ------------------------------------------------------------------ panels and dialogs
+
+fn float_frame(t: &Tokens) -> egui::Frame {
+ egui::Frame::NONE
+ .fill(t.card)
+ .stroke(Stroke::new(1.0, t.card_border))
+ .corner_radius(CornerRadius::same(t.radius_lg as u8))
+ .shadow(egui::Shadow { offset: [0, 10], blur: 30, spread: 0, color: t.shadow })
+ .inner_margin(egui::Margin::same(8))
+}
+
+/// Title row with a close button; returns true when closed.
+pub(crate) fn title_row(ui: &mut egui::Ui, title: &str) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let mut close = false;
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(title).color(t.text).size(12.0).strong());
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "x", 20.0, false, "Close").clicked() {
+ close = true;
+ }
+ });
+ });
+ crate::widgets::hairline(ui);
+ ui.add_space(4.0);
+ close
+}
+
+/// A floating panel window; `movable` follows Window › Workspace › Lock Workspace.
+pub(crate) fn panel_window(app: &PhotocraftApp, ctx: &egui::Context, id: &str, title: &str, offset: egui::Vec2, width: f32, body: impl FnOnce(&mut egui::Ui)) {
+ let t = Tokens::get(ctx);
+ let canvas = app.last_canvas_rect;
+ egui::Window::new(title)
+ .id(egui::Id::new(id))
+ .title_bar(false)
+ .resizable(false)
+ .movable(!app.session.prefs().workspace_locked)
+ .min_width(width)
+ .max_width(width)
+ .frame(float_frame(&t))
+ .default_pos(pos2((canvas.right() - width - 16.0 + offset.x).max(canvas.left() + 8.0), canvas.top() + offset.y))
+ .show(ctx, |ui| {
+ ui.set_width(width);
+ ui.set_max_width(width);
+ body(ui);
+ });
+}
+
+/// Draws the open panels and dialogs.
+pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if app.ui.analysis.measurement_log {
+ let mut act: Option<(&str, Value)> = None;
+ let mut close = false;
+ let rows = app.session.analysis.log.clone();
+ let mut sel = app.ui.analysis.log_selected.clone();
+ let t = Tokens::get(ctx);
+ panel_window(app, ctx, "measurement-log", "Measurement Log", vec2(-300.0, 470.0), 620.0, |ui| {
+ close = title_row(ui, "Measurement Log");
+ ui.horizontal(|ui| {
+ if crate::widgets::secondary_button(ui, "Record Measurements", 0.0).clicked() {
+ act = Some(("record", Value::Null));
+ }
+ if crate::widgets::secondary_button(ui, "Select All", 0.0).clicked() {
+ sel = rows.iter().map(|r| r.id).collect();
+ }
+ if crate::widgets::secondary_button(ui, "Deselect All", 0.0).clicked() {
+ sel.clear();
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "trash", 22.0, false, "Delete selected measurements").clicked() && !sel.is_empty() {
+ act = Some(("measurementLog.delete", json!({"rows": sel.clone()})));
+ }
+ if crate::icons::button(ui, "file", 22.0, false, "Export selected measurements (CSV)").clicked() {
+ act = Some(("export", json!(sel.clone())));
+ }
+ });
+ });
+ let cols: Vec<&str> = photocraft_engine::analysis_cmds::log_columns(&rows).into_iter().filter(|c| *c != "histogram").collect();
+ egui::ScrollArea::both().max_height(220.0).max_width(620.0).show(ui, |ui| {
+ egui::Grid::new("mlog-grid").striped(true).spacing(vec2(10.0, 2.0)).show(ui, |ui| {
+ for c in &cols {
+ let name = photocraft_engine::analysis_cmds::COLUMNS.iter().find(|x| x.0 == *c).map_or(*c, |x| x.1);
+ ui.label(RichText::new(name).color(t.text_dim).size(10.5).strong());
+ }
+ ui.end_row();
+ for r in &rows {
+ let on = sel.contains(&r.id);
+ for (k, c) in cols.iter().enumerate() {
+ let v = r.values.get(*c).map(|v| match v {
+ Value::String(s) => s.clone(),
+ Value::Null => String::new(),
+ other => other.to_string(),
+ });
+ let txt = RichText::new(v.unwrap_or_default()).size(10.5).color(if on { t.accent_text } else { t.text });
+ let resp = if k == 0 { ui.selectable_label(on, txt) } else { ui.label(txt) };
+ if k == 0 && resp.clicked() {
+ if on {
+ sel.retain(|x| *x != r.id);
+ } else {
+ sel.push(r.id);
+ }
+ }
+ }
+ ui.end_row();
+ }
+ });
+ });
+ });
+ app.ui.analysis.log_selected = sel;
+ if close {
+ app.ui.analysis.measurement_log = false;
+ }
+ match act {
+ Some(("record", _)) => {
+ let _ = crate::menus::invoke(app, ctx, "image.analysis.recordMeasurements", json!({}));
+ }
+ Some(("export", rows)) => {
+ let ids: Vec<u64> = rows.as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
+ if let Err(e) = export_log(app, (!ids.is_empty()).then_some(ids))
+ && e != "cancelled"
+ {
+ app.ui.status = e;
+ }
+ }
+ Some((id, p)) => {
+ if app.run(id, p).is_ok() {
+ app.ui.analysis.log_selected.clear();
+ }
+ }
+ None => {}
+ }
+ }
+ if app.ui.analysis.notes {
+ notes_panel(app, ctx);
+ }
+ if app.ui.analysis.dialog.is_some() {
+ dialog(app, ctx);
+ }
+}
+
+fn notes_panel(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let notes = app.session.active().map(|d| d.doc.notes.clone()).unwrap_or_default();
+ let n = notes.len();
+ let mut sel = app.ui.analysis.note_selected.filter(|i| *i < n).or((n > 0).then_some(0));
+ let mut close = false;
+ let mut edit: Option<Value> = None;
+ let mut delete = false;
+ let t = Tokens::get(ctx);
+ panel_window(app, ctx, "notes-panel", "Notes", vec2(-40.0, 300.0), 260.0, |ui| {
+ close = title_row(ui, "Notes");
+ match sel {
+ None => {
+ ui.label(RichText::new("Click with the Note tool to add a note.").color(t.text_dim).size(11.0));
+ }
+ Some(i) => {
+ let note = &notes[i];
+ ui.label(RichText::new(if note.author.is_empty() { "No author".to_string() } else { note.author.clone() }).color(t.text_dim).size(11.0));
+ let mut text = note.text.clone();
+ if ui.add(egui::TextEdit::multiline(&mut text).desired_rows(6).desired_width(f32::INFINITY)).changed() {
+ edit = Some(json!({"index": i, "text": text, "coalesce": format!("note-{i}")}));
+ }
+ }
+ }
+ crate::widgets::hairline(ui);
+ ui.horizontal(|ui| {
+ if ui.add_enabled_ui(n > 1, |ui| crate::icons::button(ui, "chevrons-left", 22.0, false, "Previous note")).inner.clicked() {
+ sel = sel.map(|i| (i + n - 1) % n);
+ }
+ if ui.add_enabled_ui(n > 1, |ui| crate::icons::button(ui, "chevrons-right", 22.0, false, "Next note")).inner.clicked() {
+ sel = sel.map(|i| (i + 1) % n);
+ }
+ ui.label(RichText::new(sel.map_or("0 of 0".into(), |i| format!("{} of {n}", i + 1))).color(t.text_dim).size(11.0));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.add_enabled_ui(sel.is_some(), |ui| crate::icons::button(ui, "trash", 22.0, false, "Delete note")).inner.clicked() {
+ delete = true;
+ }
+ });
+ });
+ });
+ app.ui.analysis.note_selected = sel;
+ if let Some(p) = edit {
+ let _ = app.run("notes.set", p);
+ }
+ if delete
+ && let Some(i) = sel
+ && app.run("notes.delete", json!({"index": i})).is_ok()
+ {
+ app.ui.analysis.note_selected = (n > 1).then(|| i.min(n - 2));
+ }
+ if close {
+ app.ui.analysis.notes = false;
+ }
+}
+
+fn num_field(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str, range: std::ops::RangeInclusive<f32>, suffix: &str) {
+ let t = Tokens::get(ui.ctx());
+ ui.horizontal(|ui| {
+ ui.add_sized(vec2(110.0, 18.0), egui::Label::new(RichText::new(label).color(t.text_dim).size(11.0)));
+ let mut v = f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ if crate::widgets::value_field(ui, &mut v, range, suffix, 80.0).changed() {
+ f.insert(key.into(), json!(v));
+ }
+ });
+}
+
+fn choice(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str, opts: &[(&str, &str)]) {
+ let t = Tokens::get(ui.ctx());
+ ui.horizontal(|ui| {
+ ui.add_sized(vec2(110.0, 18.0), egui::Label::new(RichText::new(label).color(t.text_dim).size(11.0)));
+ let mut cur = f.get(key).and_then(Value::as_str).unwrap_or(opts[0].0).to_string();
+ let list: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.to_string(), *l)).collect();
+ if crate::widgets::dropdown(ui, &format!("an-{key}"), &mut cur, &list, 120.0) {
+ f.insert(key.into(), json!(cur));
+ }
+ });
+}
+
+/// The params the open dialog's OK runs with (engine command, params).
+pub fn dialog_command(kind: &str, f: &Map<String, Value>) -> Option<(&'static str, Value)> {
+ Some(match kind {
+ "scale" => {
+ if f.get("preset").and_then(Value::as_str) == Some("default") {
+ ("image.analysis.setMeasurementScale", json!({"preset": "default"}))
+ } else {
+ ("image.analysis.setMeasurementScale", json!({"preset": "custom", "pixelLength": f.get("pixelLength"), "logicalLength": f.get("logicalLength"), "units": f.get("units")}))
+ }
+ }
+ "dataPoints" => ("image.analysis.selectDataPoints", json!({"selection": f.get("selection"), "ruler": f.get("ruler"), "count": f.get("count")})),
+ "scaleMarker" => ("image.analysis.placeScaleMarker", json!({"length": f.get("length"), "fontSize": f.get("fontSize"), "displayText": f.get("displayText"), "textPosition": f.get("textPosition"), "color": f.get("color")})),
+ _ => return None,
+ })
+}
+
+fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let Some((kind, mut f)) = app.ui.analysis.dialog.clone() else { return };
+ let t = Tokens::get(ctx);
+ let title = match kind.as_str() {
+ "scale" => "Measurement Scale",
+ "dataPoints" => "Select Data Points",
+ _ => "Measurement Scale Marker",
+ };
+ let mut result: Option<bool> = None;
+ egui::Window::new(title)
+ .id(egui::Id::new("analysis-dialog"))
+ .collapsible(false)
+ .resizable(false)
+ .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))
+ .frame(float_frame(&t))
+ .show(ctx, |ui| {
+ ui.label(RichText::new(title).color(t.text).size(13.0).strong());
+ crate::widgets::hairline(ui);
+ ui.add_space(6.0);
+ match kind.as_str() {
+ "scale" => {
+ choice(ui, &mut f, "preset", "Presets:", &[("custom", "Custom"), ("default", "Default")]);
+ let custom = f.get("preset").and_then(Value::as_str) != Some("default");
+ ui.add_enabled_ui(custom, |ui| {
+ num_field(ui, &mut f, "pixelLength", "Pixel Length:", 0.001..=1e7, "");
+ num_field(ui, &mut f, "logicalLength", "Logical Length:", 0.0001..=1e7, "");
+ ui.horizontal(|ui| {
+ ui.add_sized(vec2(110.0, 18.0), egui::Label::new(RichText::new("Logical Units:").color(t.text_dim).size(11.0)));
+ let mut u = f.get("units").and_then(Value::as_str).unwrap_or("pixels").to_string();
+ if ui.add(egui::TextEdit::singleline(&mut u).desired_width(80.0)).changed() {
+ f.insert("units".into(), json!(u));
+ }
+ });
+ });
+ let (pl, ll) = (f.get("pixelLength").and_then(Value::as_f64).unwrap_or(1.0), f.get("logicalLength").and_then(Value::as_f64).unwrap_or(1.0));
+ let u = f.get("units").and_then(Value::as_str).unwrap_or("pixels");
+ let text = if custom { format!("{pl} pixels = {ll:.4} {u}") } else { "1 pixels = 1.0000 pixels".into() };
+ ui.label(RichText::new(text).color(t.text_dim).size(11.0));
+ }
+ "dataPoints" => {
+ ui.horizontal_top(|ui| {
+ for (source, label) in [("selection", "Selections"), ("ruler", "Ruler Tool"), ("count", "Count Tool")] {
+ ui.vertical(|ui| {
+ ui.label(RichText::new(label).color(t.text).size(11.0).strong());
+ let mut list: Vec<String> = f.get(source).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(String::from).collect()).unwrap_or_default();
+ let mut changed = false;
+ for key in photocraft_engine::analysis_cmds::available(source) {
+ let name = photocraft_engine::analysis_cmds::COLUMNS.iter().find(|c| c.0 == key).map_or(key, |c| c.1);
+ let mut on = list.iter().any(|x| x == key);
+ if crate::widgets::checkbox(ui, &mut on, name).changed() {
+ list.retain(|x| x != key);
+ if on {
+ list.push(key.to_string());
+ }
+ changed = true;
+ }
+ }
+ if changed {
+ f.insert(source.into(), json!(list));
+ }
+ });
+ ui.add_space(12.0);
+ }
+ });
+ }
+ _ => {
+ let units = f.get("units").and_then(Value::as_str).unwrap_or("pixels").to_string();
+ num_field(ui, &mut f, "length", "Length:", 0.0001..=1e7, &units);
+ num_field(ui, &mut f, "fontSize", "Font Size:", 1.0..=1000.0, "pt");
+ let mut show = f.get("displayText").and_then(Value::as_bool).unwrap_or(true);
+ if crate::widgets::checkbox(ui, &mut show, "Display Text").changed() {
+ f.insert("displayText".into(), json!(show));
+ }
+ choice(ui, &mut f, "textPosition", "Text Position:", &[("bottom", "Bottom"), ("top", "Top")]);
+ choice(ui, &mut f, "color", "Color:", &[("black", "Black"), ("white", "White")]);
+ }
+ }
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::widgets::primary_button(ui, "OK", 70.0).clicked() {
+ result = Some(true);
+ }
+ if crate::widgets::secondary_button(ui, "Cancel", 70.0).clicked() {
+ result = Some(false);
+ }
+ });
+ });
+ });
+ match result {
+ Some(true) => {
+ app.ui.analysis.dialog = None;
+ if let Some((id, p)) = dialog_command(&kind, &f) {
+ let _ = app.run(id, p);
+ }
+ }
+ Some(false) => app.ui.analysis.dialog = None,
+ None => app.ui.analysis.dialog = Some((kind, f)),
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ fn app() -> (PhotocraftApp, egui::Context) {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
+ (app, egui::Context::default())
+ }
+
+ /// Draw `f` for a few frames (fonts load on the first).
+ pub(crate) fn render(app: &mut PhotocraftApp, ctx: &egui::Context, f: fn(&mut PhotocraftApp, &egui::Context)) {
+ PhotocraftApp::setup_context(ctx, Default::default());
+ for _ in 0..3 {
+ let mut o = ctx.run_ui(Default::default(), |ui| f(app, ui.ctx()));
+ o.textures_delta.clear();
+ }
+ }
+
+ fn down(app: &mut PhotocraftApp, x: f64, y: f64, m: egui::Modifiers) {
+ crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m);
+ }
+ fn mv(app: &mut PhotocraftApp, x: f64, y: f64, m: egui::Modifiers) {
+ crate::canvas::tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m);
+ }
+ fn up(app: &mut PhotocraftApp, x: f64, y: f64) {
+ crate::canvas::tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE);
+ }
+
+ fn ruler(app: &PhotocraftApp) -> Option<Ruler> {
+ app.session.active().unwrap().doc.measurement.ruler
+ }
+
+ #[test]
+ fn menu_selects_tools_and_toggles_panels() {
+ let (mut app, ctx) = app();
+ crate::menus::invoke(&mut app, &ctx, "image.analysis.rulerTool", json!({})).unwrap();
+ assert_eq!(app.ui.tool, Tool::Ruler);
+ assert_eq!(checked(&app, "image.analysis.rulerTool"), Some(true));
+ crate::menus::invoke(&mut app, &ctx, "image.analysis.countTool", json!({})).unwrap();
+ assert_eq!(app.ui.tool, Tool::Count);
+ crate::menus::invoke(&mut app, &ctx, "window.panel.measurementLog", json!({})).unwrap();
+ assert!(app.ui.analysis.measurement_log);
+ crate::menus::invoke(&mut app, &ctx, "window.panel.notes", json!({"show": true})).unwrap();
+ assert!(app.ui.analysis.notes);
+ let items = crate::menus::menu_items(&app);
+ for id in ["window.panel.measurementLog", "window.panel.notes", "image.analysis.setMeasurementScale", "image.analysis.placeScaleMarker", "file.import.notes", "view.proofSetup.workingCyanPlate"] {
+ assert!(items.iter().any(|i| i.id == id && i.enabled), "{id} live");
+ }
+ }
+
+ #[test]
+ fn ruler_drag_protractor_and_clear() {
+ let (mut app, _) = app();
+ app.ui.tool = Tool::Ruler;
+ let none = egui::Modifiers::NONE;
+ down(&mut app, 10.0, 10.0, none);
+ mv(&mut app, 60.0, 10.0, none);
+ up(&mut app, 60.0, 10.0);
+ assert_eq!(ruler(&app).map(|r| r.end), Some([60.0, 10.0]));
+ // Drag the end point with ⇧: constrained to 45°.
+ down(&mut app, 60.0, 10.0, none);
+ mv(&mut app, 12.0, 52.0, egui::Modifiers::SHIFT);
+ up(&mut app, 12.0, 52.0);
+ let r = ruler(&app).unwrap();
+ assert!((r.end[0] - 10.0).abs() < 1e-6, "vertical: {r:?}");
+ // ⌥-drag from the start point: protractor arm.
+ down(&mut app, 10.0, 10.0, egui::Modifiers::ALT);
+ mv(&mut app, 60.0, 10.0, none);
+ up(&mut app, 60.0, 10.0);
+ let info = photocraft_engine::analysis_cmds::ruler_info(&ruler(&app).unwrap(), &Default::default());
+ assert!((info["angle"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}");
+ // A click without a drag far away starts a new line and clears it.
+ down(&mut app, 150.0, 80.0, none);
+ up(&mut app, 150.0, 80.0);
+ assert!(ruler(&app).is_none());
+ assert_eq!(app.session.active().unwrap().history.past_len(), 0, "the ruler adds no history");
+ }
+
+ #[test]
+ fn count_tool_add_move_remove() {
+ let (mut app, _) = app();
+ app.ui.tool = Tool::Count;
+ down(&mut app, 20.0, 20.0, egui::Modifiers::NONE);
+ up(&mut app, 20.0, 20.0);
+ down(&mut app, 50.0, 50.0, egui::Modifiers::NONE);
+ up(&mut app, 50.0, 50.0);
+ let pts = |app: &PhotocraftApp| app.session.active().unwrap().doc.measurement.count_groups[0].points.clone();
+ assert_eq!(pts(&app).len(), 2);
+ // Drag marker 1.
+ down(&mut app, 20.5, 20.5, egui::Modifiers::NONE);
+ up(&mut app, 30.0, 25.0);
+ assert_eq!(pts(&app)[0], [30.0, 25.0]);
+ // ⌥-click removes.
+ down(&mut app, 50.0, 50.0, egui::Modifiers::ALT);
+ up(&mut app, 50.0, 50.0);
+ assert_eq!(pts(&app).len(), 1);
+ }
+
+ #[test]
+ fn note_tool_and_panel_state() {
+ let (mut app, ctx) = app();
+ app.ui.tool = Tool::Note;
+ app.ui.analysis.note_author = "QA".into();
+ down(&mut app, 30.0, 40.0, egui::Modifiers::NONE);
+ up(&mut app, 30.0, 40.0);
+ let n = app.session.active().unwrap().doc.notes.clone();
+ assert_eq!(n.len(), 1);
+ assert_eq!(n[0].author, "QA");
+ assert!(app.ui.analysis.notes && app.ui.analysis.note_selected == Some(0));
+ // Drag the icon.
+ down(&mut app, 32.0, 42.0, egui::Modifiers::NONE);
+ up(&mut app, 62.0, 52.0);
+ assert_eq!(app.session.active().unwrap().doc.notes[0].position, [60.0, 50.0]);
+ // The panel renders without panicking.
+ render(&mut app, &ctx, windows);
+ }
+
+ #[test]
+ fn dialogs_open_and_run_their_commands() {
+ let (mut app, ctx) = app();
+ let r = crate::menus::invoke(&mut app, &ctx, "image.analysis.setMeasurementScale", json!({})).unwrap();
+ assert_eq!(r["dialog"], "scale");
+ let (kind, mut f) = app.ui.analysis.dialog.clone().unwrap();
+ f.insert("preset".into(), json!("custom"));
+ f.insert("pixelLength".into(), json!(40));
+ f.insert("logicalLength".into(), json!(1));
+ f.insert("units".into(), json!("cm"));
+ let (id, p) = dialog_command(&kind, &f).unwrap();
+ app.run(id, p).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.measurement.scale.units, "cm");
+ crate::menus::invoke(&mut app, &ctx, "image.analysis.placeScaleMarker", json!({})).unwrap();
+ let (kind, f) = app.ui.analysis.dialog.clone().unwrap();
+ assert_eq!(f["length"], 1.0);
+ let (id, p) = dialog_command(&kind, &f).unwrap();
+ app.run(id, p).unwrap();
+ crate::menus::invoke(&mut app, &ctx, "image.analysis.selectDataPoints", json!({})).unwrap();
+ let (kind, mut f) = app.ui.analysis.dialog.clone().unwrap();
+ f.insert("ruler".into(), json!(["label", "length"]));
+ let (id, p) = dialog_command(&kind, &f).unwrap();
+ app.run(id, p).unwrap();
+ assert_eq!(app.session.analysis.data_points.ruler, ["label", "length"]);
+ // Record from the Count tool records counts and opens the log.
+ app.ui.tool = Tool::Count;
+ crate::menus::invoke(&mut app, &ctx, "image.analysis.recordMeasurements", json!({})).unwrap();
+ assert!(app.ui.analysis.measurement_log);
+ assert_eq!(app.session.analysis.log.last().unwrap().values["source"], "Count Tool");
+ render(&mut app, &ctx, windows);
+ }
+}
diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs
new file mode 100644
index 000000000..eed50d750
--- /dev/null
+++ b/crates/ui-egui/src/camera_raw_ui.rs
@@ -0,0 +1,472 @@
+//! Filter › Camera Raw Filter…: a large dialog like Adobe Camera Raw's (preview on the left,
+//! edit panels on the right: Basic, Curve, Detail, Color Mixer, Color Grading, Effects).
+//!
+//! The preview runs [`photocraft_algo::camera_raw::develop`] on a CPU proxy of the layer
+//! (≤ 900 px, `pixel_scale` keeps pixel radii true to the full image), recomputed when a
+//! control changes. OK runs `filter.cameraRaw` with the non-default settings, so the result is
+//! one history step (or a smart filter on a smart object) and exactly replayable.
+//!
+//! Control channel: `ui.menu.invoke {"id":"filter.cameraRaw","params":{"ui":{"set":{…},
+//! "commit":true | "cancel":true}}}`; the reply describes the dialog.
+
+use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};
+use photocraft_algo::camera_raw::{CameraRaw, Wheel, curve_lut};
+use photocraft_doc::LayerId;
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+use crate::widgets;
+
+const PROXY_SIDE: usize = 900;
+const PANEL_W: f32 = 330.0;
+const BANDS: [&str; 8] = ["Red", "Orange", "Yellow", "Green", "Aqua", "Blue", "Purple", "Magenta"];
+
+pub struct CameraRawDialog {
+ pub layer: LayerId,
+ layer_name: String,
+ pub params: CameraRaw,
+ /// Proxy pixels (straight RGBA) and size.
+ proxy: Vec<[f32; 4]>,
+ pw: usize,
+ ph: usize,
+ full_w: usize,
+ float: bool,
+ tex: Option<TextureHandle>,
+ before_tex: Option<TextureHandle>,
+ dirty: bool,
+ pub show_before: bool,
+ mixer_tab: usize,
+ pub render_ms: f64,
+}
+
+impl CameraRawDialog {
+ pub fn describe(&self) -> Value {
+ json!({"layer": self.layer.0, "params": serde_json::to_value(&self.params).unwrap_or(Value::Null), "proxy": [self.pw, self.ph], "renderMs": self.render_ms, "before": self.show_before})
+ }
+
+ /// Params for the engine: only the settings that differ from the defaults.
+ pub fn command_params(&self) -> Value {
+ let full = serde_json::to_value(&self.params).unwrap_or(json!({}));
+ let def = serde_json::to_value(CameraRaw::default()).unwrap_or(json!({}));
+ let mut out = serde_json::Map::new();
+ if let (Value::Object(f), Value::Object(d)) = (full, def) {
+ for (k, v) in f {
+ if k != "pixelScale" && d.get(&k) != Some(&v) {
+ out.insert(k, v);
+ }
+ }
+ }
+ Value::Object(out)
+ }
+
+ fn image(px: &[[f32; 4]], w: usize, h: usize) -> egui::ColorImage {
+ let enc = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
+ egui::ColorImage::new([w, h], px.iter().map(|q| Color32::from_rgba_unmultiplied(enc(q[0]), enc(q[1]), enc(q[2]), enc(q[3]))).collect())
+ }
+
+ fn render(&mut self, ctx: &egui::Context) {
+ let t0 = crate::gpu_canvas::now_ms();
+ let mut px = self.proxy.clone();
+ let mut p = self.params.clone();
+ p.pixel_scale = (self.pw as f32 / self.full_w.max(1) as f32).min(1.0);
+ photocraft_algo::camera_raw::develop(&mut px, self.pw, self.ph, &p, self.float);
+ let img = Self::image(&px, self.pw, self.ph);
+ match &mut self.tex {
+ Some(t) => t.set(img, egui::TextureOptions::LINEAR),
+ None => self.tex = Some(ctx.load_texture("camera-raw-after", img, egui::TextureOptions::LINEAR)),
+ }
+ if self.before_tex.is_none() {
+ self.before_tex = Some(ctx.load_texture("camera-raw-before", Self::image(&self.proxy, self.pw, self.ph), egui::TextureOptions::LINEAR));
+ }
+ self.render_ms = crate::gpu_canvas::now_ms() - t0;
+ self.dirty = false;
+ }
+}
+
+/// Opens the dialog on the active layer.
+pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
+ 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)?;
+ let st = app.session.active().ok_or("no document")?;
+ let canvas = st.doc.bounds();
+ let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default();
+ let area = surf.content_bounds().intersect(&canvas);
+ let area = if area.is_empty() { canvas } else { area };
+ let (w, h) = (area.width() as usize, area.height() as usize);
+ let k = w.max(h).div_ceil(PROXY_SIDE).max(1);
+ let (pw, ph) = (w.div_ceil(k), h.div_ceil(k));
+ let mut proxy = vec![[0.0f32; 4]; pw * ph];
+ let mut row = vec![[0.0f32; 4]; w];
+ for py in 0..ph {
+ // Box-average k×k blocks.
+ let mut acc = vec![[0.0f32; 5]; pw];
+ for dy in 0..k {
+ let y = area.y0 + (py * k + dy).min(h - 1) as i32;
+ surf.read_rgba_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row);
+ for (x, q) in row.iter().enumerate() {
+ let a = &mut acc[x / k];
+ for c in 0..4 {
+ a[c] += q[c];
+ }
+ a[4] += 1.0;
+ }
+ }
+ for (x, a) in acc.iter().enumerate() {
+ proxy[py * pw + x] = [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]];
+ }
+ }
+ let float = surf.format().sample == photocraft_color::SampleType::F32;
+ let mut d = CameraRawDialog { layer, layer_name: name, params: CameraRaw::default(), proxy, pw, ph, full_w: w, float, tex: None, before_tex: None, dirty: true, show_before: false, mixer_tab: 1, render_ms: 0.0 };
+ d.render(ctx);
+ app.camera_raw = Some(d);
+ Ok(())
+}
+
+/// Menu / control-channel entry point. `None` when the call isn't for this dialog.
+pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if id != "filter.cameraRaw" {
+ return None;
+ }
+ let empty = params.as_object().is_none_or(|o| o.is_empty());
+ if empty {
+ return Some(open(app, ctx).map(|_| app.camera_raw.as_ref().map(|d| d.describe()).unwrap_or(Value::Null)));
+ }
+ let ui = params.get("ui")?;
+ if app.camera_raw.is_none()
+ && let Err(e) = open(app, ctx)
+ {
+ return Some(Err(e));
+ }
+ if let Some(set) = ui.get("set") {
+ let d = app.camera_raw.as_mut()?;
+ 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 {
+ c.insert(k.clone(), v.clone());
+ }
+ }
+ match serde_json::from_value::<CameraRaw>(cur) {
+ Ok(p) => {
+ d.params = p;
+ d.render(ctx);
+ }
+ Err(e) => return Some(Err(format!("bad Camera Raw settings: {e}"))),
+ }
+ }
+ if let Some(b) = ui.get("before").and_then(Value::as_bool)
+ && let Some(d) = app.camera_raw.as_mut()
+ {
+ d.show_before = b;
+ }
+ if ui.get("cancel").and_then(Value::as_bool) == Some(true) {
+ app.camera_raw = None;
+ return Some(Ok(json!({"cancelled": true})));
+ }
+ if ui.get("commit").and_then(Value::as_bool) == Some(true) {
+ return Some(commit(app));
+ }
+ Some(Ok(app.camera_raw.as_ref().map(|d| d.describe()).unwrap_or(Value::Null)))
+}
+
+fn commit(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let d = app.camera_raw.take().ok_or("Camera Raw isn't open")?;
+ let mut p = d.command_params();
+ p["layer"] = json!(d.layer.0);
+ app.run("filter.cameraRaw", p)
+}
+
+fn temp_stops() -> Vec<Color32> {
+ vec![Color32::from_rgb(70, 120, 230), Color32::from_rgb(200, 200, 200), Color32::from_rgb(235, 200, 60)]
+}
+fn tint_stops() -> Vec<Color32> {
+ vec![Color32::from_rgb(70, 190, 80), Color32::from_rgb(200, 200, 200), Color32::from_rgb(210, 80, 200)]
+}
+
+/// One labelled slider; marks the dialog dirty when it moves.
+fn row(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive<f32>, grad: Option<&[Color32]>) {
+ let r = widgets::slider_row(ui, label, v, range, "", grad);
+ if r.changed() {
+ *dirty = true;
+ }
+ if r.double_clicked() {
+ *v = 0.0;
+ *dirty = true;
+ }
+}
+
+fn section(ui: &mut egui::Ui, title: &str, open: bool, body: impl FnOnce(&mut egui::Ui)) {
+ egui::CollapsingHeader::new(egui::RichText::new(title).font(FontId::proportional(13.0))).default_open(open).show(ui, body);
+}
+
+fn wheel(ui: &mut egui::Ui, dirty: &mut bool, title: &str, w: &mut Wheel) {
+ widgets::section_label(ui, title);
+ let hs = widgets::hue_stops();
+ row(ui, dirty, "Hue", &mut w.hue, 0.0..=360.0, Some(&hs));
+ row(ui, dirty, "Saturation", &mut w.sat, 0.0..=100.0, None);
+ row(ui, dirty, "Luminance", &mut w.lum, -100.0..=100.0, None);
+}
+
+/// Small point-curve editor (master channel): click to add, drag to move, right-click to delete.
+fn curve_editor(ui: &mut egui::Ui, p: &mut CameraRaw, dirty: &mut bool) {
+ let t = Tokens::get(ui.ctx());
+ let side = ui.available_width().min(260.0);
+ let (rect, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click_and_drag());
+ let painter = ui.painter_at(rect);
+ painter.rect_filled(rect, 2.0, t.field);
+ for i in 1..4 {
+ let f = i as f32 / 4.0;
+ painter.line_segment([pos2(rect.left() + f * side, rect.top()), pos2(rect.left() + f * side, rect.bottom())], Stroke::new(1.0, t.separator));
+ painter.line_segment([pos2(rect.left(), rect.top() + f * side), pos2(rect.right(), rect.top() + f * side)], Stroke::new(1.0, t.separator));
+ }
+ let to_screen = |x: f32, y: f32| pos2(rect.left() + x / 255.0 * side, rect.bottom() - y / 255.0 * side);
+ let from_screen = |q: Pos2| [((q.x - rect.left()) / side * 255.0).clamp(0.0, 255.0), ((rect.bottom() - q.y) / side * 255.0).clamp(0.0, 255.0)];
+ if p.point_curve.len() < 2 {
+ p.point_curve = vec![[0.0, 0.0], [255.0, 255.0]];
+ }
+ // Interaction.
+ let drag_id = ui.id().with("cr-curve-drag");
+ let mut dragging: Option<usize> = ui.data(|d| d.get_temp(drag_id));
+ if let Some(pos) = resp.interact_pointer_pos() {
+ let q = from_screen(pos);
+ if resp.drag_started() || resp.clicked() {
+ let near = p.point_curve.iter().position(|c| (to_screen(c[0], c[1]) - pos).length() < 8.0);
+ if resp.secondary_clicked() {
+ if let Some(i) = near.filter(|i| *i != 0 && *i + 1 != p.point_curve.len()) {
+ p.point_curve.remove(i);
+ *dirty = true;
+ }
+ } else {
+ dragging = Some(near.unwrap_or_else(|| {
+ p.point_curve.push(q);
+ p.point_curve.sort_by(|a, b| a[0].total_cmp(&b[0]));
+ *dirty = true;
+ p.point_curve.iter().position(|c| *c == q).unwrap_or(0)
+ }));
+ }
+ }
+ if resp.dragged()
+ && let Some(i) = dragging
+ {
+ let n = p.point_curve.len();
+ let lo = if i == 0 { 0.0 } else { p.point_curve[i - 1][0] + 1.0 };
+ let hi = if i + 1 == n { 255.0 } else { p.point_curve[i + 1][0] - 1.0 };
+ p.point_curve[i] = [q[0].clamp(lo, hi.max(lo)), q[1]];
+ *dirty = true;
+ }
+ }
+ if resp.drag_stopped() {
+ dragging = None;
+ }
+ ui.data_mut(|d| d.insert_temp(drag_id, dragging));
+ // Curve (point curve after the parametric one).
+ let lut = curve_lut(&p.point_curve, 256);
+ let pts: Vec<Pos2> = (0..256).map(|i| to_screen(i as f32, lut[i] * 255.0)).collect();
+ painter.add(egui::Shape::line(pts, Stroke::new(1.5, t.text)));
+ for c in &p.point_curve {
+ painter.circle_stroke(to_screen(c[0], c[1]), 4.0, Stroke::new(1.5, t.accent));
+ }
+}
+
+pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if app.camera_raw.is_none() {
+ return;
+ }
+ let t = Tokens::get(ctx);
+ let screen = ctx.content_rect();
+ let mut action: Option<&str> = None;
+ egui::Area::new(egui::Id::new("camera-raw-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
+ let Some(d) = app.camera_raw.as_mut() else { return };
+ if d.dirty {
+ d.render(ctx);
+ }
+ let (full, _) = ui.allocate_exact_size(screen.size(), Sense::click());
+ let painter = ui.painter().clone();
+ painter.rect_filled(full, 0.0, t.chrome);
+ let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0));
+ painter.rect_filled(title, 0.0, t.dock);
+ painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator));
+ painter.text(title.center(), Align2::CENTER_CENTER, format!("Camera Raw Filter ({})", d.layer_name), FontId::proportional(13.0), t.text);
+ let footer_h = 48.0;
+ let body = ERect::from_min_max(pos2(full.left(), title.bottom()), pos2(full.right(), full.bottom() - footer_h));
+ // Preview.
+ let view = ERect::from_min_max(body.min, pos2(body.right() - PANEL_W, body.bottom())).shrink(16.0);
+ painter.rect_filled(view, 0.0, t.canvas);
+ let tex = if d.show_before { d.before_tex.as_ref() } else { d.tex.as_ref() };
+ if let Some(tex) = tex {
+ let s = (view.width() / d.pw as f32).min(view.height() / d.ph as f32);
+ let r = ERect::from_center_size(view.center(), vec2(d.pw as f32 * s, d.ph as f32 * s));
+ widgets::checker(&painter, r, 8.0);
+ painter.image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ // Panels.
+ let right = ERect::from_min_max(pos2(body.right() - PANEL_W, body.top()), body.max);
+ painter.rect_filled(right, 0.0, t.dock);
+ painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator));
+ let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 10.0))));
+ let mut dirty = false;
+ egui::ScrollArea::vertical().id_salt("camera-raw-props").show(&mut props, |ui| {
+ ui.spacing_mut().item_spacing.y = 4.0;
+ let p = &mut d.params;
+ let (ts, tn) = (temp_stops(), tint_stops());
+ section(ui, "Basic", true, |ui| {
+ widgets::section_label(ui, "White Balance: As Shot");
+ row(ui, &mut dirty, "Temperature", &mut p.temperature, -100.0..=100.0, Some(&ts));
+ row(ui, &mut dirty, "Tint", &mut p.tint, -100.0..=100.0, Some(&tn));
+ row(ui, &mut dirty, "Exposure", &mut p.exposure, -5.0..=5.0, None);
+ row(ui, &mut dirty, "Contrast", &mut p.contrast, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Highlights", &mut p.highlights, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Shadows", &mut p.shadows, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Whites", &mut p.whites, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Blacks", &mut p.blacks, -100.0..=100.0, None);
+ widgets::hairline(ui);
+ row(ui, &mut dirty, "Texture", &mut p.texture, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Clarity", &mut p.clarity, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Dehaze", &mut p.dehaze, -100.0..=100.0, None);
+ widgets::hairline(ui);
+ row(ui, &mut dirty, "Vibrance", &mut p.vibrance, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Saturation", &mut p.saturation, -100.0..=100.0, None);
+ });
+ section(ui, "Curve", false, |ui| {
+ curve_editor(ui, p, &mut dirty);
+ row(ui, &mut dirty, "Highlights", &mut p.curve_highlights, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Lights", &mut p.curve_lights, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Darks", &mut p.curve_darks, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Shadows", &mut p.curve_shadows, -100.0..=100.0, None);
+ });
+ section(ui, "Detail", false, |ui| {
+ widgets::section_label(ui, "Sharpening");
+ row(ui, &mut dirty, "Amount", &mut p.sharpen_amount, 0.0..=150.0, None);
+ row(ui, &mut dirty, "Radius", &mut p.sharpen_radius, 0.5..=3.0, None);
+ row(ui, &mut dirty, "Detail", &mut p.sharpen_detail, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Masking", &mut p.sharpen_masking, 0.0..=100.0, None);
+ widgets::section_label(ui, "Noise Reduction");
+ row(ui, &mut dirty, "Luminance", &mut p.noise_luminance, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Luminance Detail", &mut p.noise_luminance_detail, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Color", &mut p.noise_color, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Color Detail", &mut p.noise_color_detail, 0.0..=100.0, None);
+ });
+ section(ui, "Color Mixer", false, |ui| {
+ ui.horizontal(|ui| {
+ for (i, name) in ["Hue", "Saturation", "Luminance"].iter().enumerate() {
+ if widgets::pill_tab(ui, name, d.mixer_tab == i).clicked() {
+ d.mixer_tab = i;
+ }
+ }
+ });
+ let arr = match d.mixer_tab {
+ 0 => &mut p.hsl_hue,
+ 1 => &mut p.hsl_sat,
+ _ => &mut p.hsl_lum,
+ };
+ for (k, name) in BANDS.iter().enumerate() {
+ let c = photocraft_algo::camera_raw::HSL_BANDS[k];
+ let base = hue_color(c);
+ let grad = [Color32::from_gray(128), base];
+ row(ui, &mut dirty, name, &mut arr[k], -100.0..=100.0, Some(&grad));
+ }
+ });
+ section(ui, "Color Grading", false, |ui| {
+ wheel(ui, &mut dirty, "Shadows", &mut p.grade_shadows);
+ wheel(ui, &mut dirty, "Midtones", &mut p.grade_midtones);
+ wheel(ui, &mut dirty, "Highlights", &mut p.grade_highlights);
+ wheel(ui, &mut dirty, "Global", &mut p.grade_global);
+ row(ui, &mut dirty, "Blending", &mut p.grade_blending, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Balance", &mut p.grade_balance, -100.0..=100.0, None);
+ });
+ section(ui, "Effects", false, |ui| {
+ widgets::section_label(ui, "Grain");
+ row(ui, &mut dirty, "Amount", &mut p.grain_amount, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Size", &mut p.grain_size, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Roughness", &mut p.grain_roughness, 0.0..=100.0, None);
+ widgets::section_label(ui, "Vignetting");
+ let mut style = p.vignette_style.clone();
+ if widgets::dropdown(ui, "cr-vig-style", &mut style, &[("highlightPriority".to_string(), "Highlight Priority"), ("colorPriority".to_string(), "Color Priority"), ("paintOverlay".to_string(), "Paint Overlay")], 200.0) {
+ p.vignette_style = style;
+ dirty = true;
+ }
+ row(ui, &mut dirty, "Amount", &mut p.vignette_amount, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Midpoint", &mut p.vignette_midpoint, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Roundness", &mut p.vignette_roundness, -100.0..=100.0, None);
+ row(ui, &mut dirty, "Feather", &mut p.vignette_feather, 0.0..=100.0, None);
+ row(ui, &mut dirty, "Highlights", &mut p.vignette_highlights, 0.0..=100.0, None);
+ });
+ });
+ d.dirty |= dirty;
+ // Footer.
+ let foot = ERect::from_min_max(pos2(full.left(), full.bottom() - footer_h), full.max);
+ painter.rect_filled(foot, 0.0, t.dock);
+ painter.line_segment([foot.left_top(), foot.right_top()], Stroke::new(1.0, t.separator));
+ let mut fu = ui.new_child(egui::UiBuilder::new().max_rect(foot.shrink2(vec2(16.0, 9.0))).layout(egui::Layout::right_to_left(egui::Align::Center)));
+ if widgets::primary_button(&mut fu, "OK", 90.0).clicked() {
+ action = Some("ok");
+ }
+ if widgets::secondary_button(&mut fu, "Cancel", 90.0).clicked() {
+ action = Some("cancel");
+ }
+ fu.add_space(12.0);
+ widgets::checkbox(&mut fu, &mut d.show_before, "Before (Y)");
+ fu.label(egui::RichText::new(format!("{:.0} ms", d.render_ms)).color(t.text_faint));
+ });
+ if ctx.input(|i| i.key_pressed(egui::Key::Y))
+ && let Some(d) = app.camera_raw.as_mut()
+ {
+ d.show_before = !d.show_before;
+ }
+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ action = Some("cancel");
+ }
+ match action {
+ Some("ok") => {
+ if let Err(e) = commit(app) {
+ app.ui.status = e;
+ }
+ }
+ Some("cancel") => app.camera_raw = None,
+ _ => {}
+ }
+}
+
+fn hue_color(h: f32) -> Color32 {
+ let h6 = (h.rem_euclid(360.0)) / 60.0;
+ let x = 1.0 - ((h6 % 2.0) - 1.0).abs();
+ let (r, g, b) = match h6 as u32 {
+ 0 => (1.0, x, 0.0),
+ 1 => (x, 1.0, 0.0),
+ 2 => (0.0, 1.0, x),
+ 3 => (0.0, x, 1.0),
+ 4 => (x, 0.0, 1.0),
+ _ => (1.0, 0.0, x),
+ };
+ Color32::from_rgb((r * 220.0) as u8, (g * 220.0) as u8, (b * 220.0) as u8)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dialog_drives_the_engine() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("edit.fill", json!({"color": "#808080"})).unwrap();
+ let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap();
+ assert_eq!(r["proxy"], json!([64, 48]));
+ let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "vignetteAmount": -40}}})).unwrap().unwrap();
+ assert_eq!(r["params"]["exposure"], 1.0);
+ assert_eq!(app.camera_raw.as_ref().unwrap().command_params(), json!({"exposure": 1.0, "vignetteAmount": -40.0}));
+ let before = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 24);
+ menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap();
+ assert!(app.camera_raw.is_none());
+ let after = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 24);
+ assert!(after[0] > before[0] + 0.1, "{before:?} → {after:?}");
+ // Cancel leaves the document alone.
+ menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap();
+ let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap();
+ assert_eq!(r["cancelled"], true);
+ assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": "x"}}})).unwrap().is_err());
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index c48bed5cb..6891f2642 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -372,7 +372,7 @@ pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let live: Vec<u64> = app.session.documents().iter().flat_map(|st| [st.doc.id.0, st.doc.id.0 ^ (1u64 << 61), st.doc.id.0 ^ (1u64 << 62)]).collect();
gpu.retain(&live);
}
- if app.session.documents().is_empty() {
+ if app.ui.chrome.shows_home(app.session.documents().len()) {
start_screen(app, ui);
return;
}
@@ -885,6 +885,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
crate::rulers::draw_guides(app, &painter, &xf, &doc);
}
draw_drag_preview(app, &painter, &xf);
+ draw_transform_controls(app, &painter, &xf);
crate::snap_ui::draw(app, &painter, &xf);
if border == photocraft_engine::prefs::CanvasBorder::Line {
painter.rect_stroke(img_rect, 0.0, Stroke::new(1.0, Color32::from_gray(20)), egui::StrokeKind::Outside);
@@ -894,6 +895,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
crate::distort_ui::draw_overlay(app, &painter, &xf);
crate::retouch_ui::draw_source_marker(app, &painter, &xf);
crate::vector_ui::draw_overlay(app, &painter, &xf, &doc);
+ crate::analysis_ui::draw_overlay(app, &painter, &xf);
+ crate::slice_ui::draw_overlay(app, &painter, &xf);
// Tool cursors (Photoshop-style).
let guide_hover = response.hover_pos().filter(|_| tool == Tool::Move).and_then(|p| {
let d = xf.to_doc(p);
@@ -1082,10 +1085,39 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,
}
}
+/// Move tool › Show Transform Controls: the active layer's bounding box with its eight handles.
+fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ if app.ui.tool != Tool::Move || !app.ui.tool_options.move_show_transform || app.ui.transform.is_some() || app.drag.is_some() {
+ return;
+ }
+ let Some(st) = app.session.active() else { return };
+ let Some(l) = st.active_layer.and_then(|id| st.doc.layer(id)) else { return };
+ if crate::doc_props_ui::is_background(&st.doc, l) {
+ return;
+ }
+ let (id, Some(surf)) = (l.id.0, l.surface().cloned()) else { return };
+ let b = app.cached_bounds(id, &surf);
+ if b.is_empty() {
+ return;
+ }
+ let r = Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32));
+ let accent = crate::theme::Tokens::get(painter.ctx()).accent;
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Middle);
+ for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] {
+ let h = Rect::from_center_size(p, vec2(7.0, 7.0));
+ painter.rect_filled(h, 0.0, Color32::WHITE);
+ painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside);
+ }
+}
+
fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
draw_tool_state(app, painter, xf, painter.ctx().input(|i| i.pointer.hover_pos()));
let Some(d) = &app.drag else { return };
- let last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start);
+ let mut last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start);
+ if matches!(d.tool, Tool::RectMarquee | Tool::EllipseMarquee) {
+ let o = &app.ui.tool_options;
+ last = crate::chrome_ui::marquee_end(&o.marquee_style, o.marquee_width as f64, o.marquee_height as f64, false, d.start, last);
+ }
match d.tool {
Tool::Brush | Tool::Eraser => {
let c = if d.tool == Tool::Eraser { [1.0, 1.0, 1.0, 0.6] } else { app.session.tools.foreground };
@@ -1112,7 +1144,7 @@ fn draw_drag_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXfor
Tool::Line => {
painter.line_segment([xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32)], Stroke::new(1.0, crate::theme::Tokens::get(painter.ctx()).accent));
}
- Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon => {
+ Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::CustomShape => {
let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32));
if matches!(d.tool, Tool::EllipseMarquee | Tool::EllipseShape) {
painter.add(egui::Shape::ellipse_stroke(r.center(), r.size() / 2.0, Stroke::new(1.0, Color32::WHITE)));
@@ -1163,6 +1195,16 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
if crate::distort_ui::pointer(app, ev, mods) {
return;
}
+ // Window › Modifier Keys: sticky Shift/⌘/⌥ act as held keys.
+ let mods = crate::workspace_ui::sticky_mods(app, mods);
+ // Ruler, Count and Note tools.
+ if crate::analysis_ui::pointer(app, ev, mods) {
+ return;
+ }
+ // Slice and Slice Select tools.
+ if crate::slice_ui::pointer(app, ev, mods) {
+ return;
+ }
let tool = app.ui.tool;
// Move tool over a guide drags the guide (off the canvas deletes it).
match ev {
@@ -1171,6 +1213,12 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
app.guide_drag = Some(crate::rulers::GuideDrag { vertical, index: Some(i), pos: if vertical { x } else { y } });
return;
}
+ // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first.
+ if app.ui.tool_options.move_auto_select != mods.command {
+ let target = app.ui.tool_options.move_target.clone();
+ let mode = if mods.shift { "add" } else { "replace" };
+ let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode}));
+ }
}
ToolEvent::Move { x, y, .. } => {
if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) {
@@ -1281,6 +1329,9 @@ fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {
let _ = app.run("paint.stroke", json!({ "points": pts, "erase": d.tool == Tool::Eraser, "smoothing": 0.3, "target": paint_target(app) }));
}
Tool::RectMarquee | Tool::EllipseMarquee => {
+ let o = &app.ui.tool_options;
+ let e = crate::chrome_ui::marquee_end(&o.marquee_style, o.marquee_width as f64, o.marquee_height as f64, false, d.start, [end[0], end[1]]);
+ let end = [e[0], e[1], 1.0];
let (x0, y0) = (d.start[0].min(end[0]).floor(), d.start[1].min(end[1]).floor());
let (x1, y1) = (d.start[0].max(end[0]).ceil(), d.start[1].max(end[1]).ceil());
if x1 - x0 < 2.0 || y1 - y0 < 2.0 {
@@ -1301,7 +1352,8 @@ fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {
} else {
"replace"
};
- let _ = app.run("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "ellipse": d.tool == Tool::EllipseMarquee}));
+ let (aa, feather) = (app.ui.tool_options.anti_alias, app.ui.tool_options.feather);
+ let _ = app.run("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "ellipse": d.tool == Tool::EllipseMarquee, "antiAlias": aa, "feather": feather}));
}
Tool::Lasso => {
let pts: Vec<[f64; 2]> = d.points.iter().map(|p| [p[0], p[1]]).collect();
diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rs
index c38b4e0be..0145ed08a 100644
--- a/crates/ui-egui/src/channels_panel.rs
+++ b/crates/ui-egui/src/channels_panel.rs
@@ -55,8 +55,10 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let quick = doc.quick_mask.is_some();
let ctx = ui.ctx().clone();
let thumbs = app.channel_thumbs(&ctx);
- let mut rows = vec![Row::Composite];
- if colors > 1 {
+ // Multichannel images are their ink channels only (no composite or colour rows).
+ let multichannel = doc.mode == photocraft_doc::ColorMode::Multichannel;
+ let mut rows = if multichannel { Vec::new() } else { vec![Row::Composite] };
+ if colors > 1 && !multichannel {
rows.extend((0..colors).map(Row::Color));
}
rows.extend((0..doc.channels.len()).map(Row::Alpha));
diff --git a/crates/ui-egui/src/chrome_ui.rs b/crates/ui-egui/src/chrome_ui.rs
new file mode 100644
index 000000000..366a1b3ff
--- /dev/null
+++ b/crates/ui-egui/src/chrome_ui.rs
@@ -0,0 +1,229 @@
+//! Photoshop 2026 window chrome details: the status bar's info field and its "Show" menu, and the
+//! Home button at the start of the options bar.
+
+use egui::{RichText, Sense, Stroke, vec2};
+use photocraft_doc::{Document, LayerContent};
+use serde::{Deserialize, Serialize};
+
+use crate::theme::Tokens;
+use crate::{PhotocraftApp, icons, widgets};
+
+/// Shell-only chrome state (serialised with the UI state, so `ui.inspect` reports it).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ChromeState {
+ /// What the status bar shows next to the zoom field (one of [`STATUS_INFO`] keys).
+ pub status_info: String,
+ /// Home screen shown over the open documents (Options bar › Home); holds the document count
+ /// when it was opened, so opening or creating a document leaves it.
+ pub home: Option<usize>,
+}
+
+impl ChromeState {
+ /// Is the Home screen up, given the current number of open documents?
+ pub fn shows_home(&self, documents: usize) -> bool {
+ documents == 0 || self.home == Some(documents)
+ }
+}
+
+impl Default for ChromeState {
+ fn default() -> Self {
+ Self { status_info: "dimensions".into(), home: None }
+ }
+}
+
+/// The status bar "Show" menu, in Photoshop's order: (key, menu label).
+pub const STATUS_INFO: &[(&str, &str)] = &[
+ ("sizes", "Document Sizes"),
+ ("profile", "Document Profile"),
+ ("dimensions", "Document Dimensions"),
+ ("measurementScale", "Measurement Scale"),
+ ("scratch", "Scratch Sizes"),
+ ("efficiency", "Efficiency"),
+ ("tool", "Current Tool"),
+ ("layers", "Layer Count"),
+];
+
+/// Photoshop's compact byte format: "10.3M", "412.5K".
+pub fn fmt_bytes(b: u64) -> String {
+ let b = b as f64;
+ if b >= 1024.0 * 1024.0 * 1024.0 {
+ format!("{:.1}G", b / (1024.0 * 1024.0 * 1024.0))
+ } else if b >= 1024.0 * 1024.0 {
+ format!("{:.1}M", b / (1024.0 * 1024.0))
+ } else {
+ format!("{:.1}K", b / 1024.0)
+ }
+}
+
+/// Flattened size and layered size in bytes ("Doc: flat/layered").
+pub fn document_sizes(doc: &Document) -> (u64, u64) {
+ let bpc = (doc.depth.bits() / 8).max(1) as u64;
+ let channels = doc.mode.color_channels().max(1) as u64;
+ let flat = doc.size.width as u64 * doc.size.height as u64 * channels * bpc;
+ let mut layered = 0u64;
+ for (_, _, l) in doc.walk() {
+ if let LayerContent::Raster(s) = &l.content {
+ // Layers carry transparency on top of the colour channels; clip to the canvas.
+ let r = s.tile_bounds().intersect(&doc.bounds());
+ layered += r.width() as u64 * r.height() as u64 * (channels + 1) * bpc;
+ }
+ }
+ (flat, layered.max(flat))
+}
+
+/// The status bar text for `key` (Photoshop wording).
+pub fn status_info_text(doc: &Document, key: &str, tool: &str, profile: &str) -> String {
+ let bits = doc.depth.bits();
+ match key {
+ "sizes" => {
+ let (flat, layered) = document_sizes(doc);
+ format!("Doc: {}/{}", fmt_bytes(flat), fmt_bytes(layered))
+ }
+ "profile" => format!("{profile} ({bits}bpc)"),
+ "measurementScale" => "1 pixel = 1.0000 pixels".into(),
+ "scratch" => {
+ let (_, layered) = document_sizes(doc);
+ format!("Scratch: {}", fmt_bytes(layered))
+ }
+ "efficiency" => "Efficiency: 100%".into(),
+ "tool" => tool.to_string(),
+ "layers" => {
+ let n = doc.layer_count();
+ format!("{n} {}", if n == 1 { "Layer" } else { "Layers" })
+ }
+ _ => format!("{} px x {} px ({} ppi)", doc.size.width, doc.size.height, widgets::fmt_num(doc.resolution_dpi as f64)),
+ }
+}
+
+fn profile_name(doc: &Document) -> String {
+ if doc.icc_profile.is_none() {
+ return format!("Untagged {}", crate::canvas::mode_label(doc));
+ }
+ photocraft_engine::color_cmds::document_profile(doc).description.clone()
+}
+
+/// Status bar body (Pro): zoom %, the chosen info field and its ">" menu, then status messages.
+pub fn status_bar_pro(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let (Some(st), Some(i)) = (app.session.active(), app.session.active_index()) else {
+ ui.label(RichText::new("No document").color(t.text_dim));
+ return;
+ };
+ let text = status_info_text(&st.doc, &app.ui.chrome.status_info, app.ui.tool.label(), &profile_name(&st.doc));
+ let mut pct = app.ui.views[i].zoom * 100.0;
+ if widgets::value_field(ui, &mut pct, 1.0..=3200.0, "%", 64.0).changed() {
+ app.ui.views[i].zoom = pct / 100.0;
+ app.ui.views[i].fit_pending = false;
+ }
+ ui.add_space(12.0);
+ ui.label(RichText::new(text).color(t.text_dim).size(12.0));
+ let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(r, t.radius_sm, t.hover);
+ }
+ icons::paint(ui, r, "chevron-right", 11.0, t.text_dim);
+ let resp = resp.on_hover_text("Show");
+ egui::Popup::menu(&resp).show(|ui| {
+ ui.set_min_width(200.0);
+ for (key, label) in STATUS_INFO {
+ let on = app.ui.chrome.status_info == *key;
+ if ui.add(egui::Button::selectable(on, *label)).clicked() {
+ app.ui.chrome.status_info = (*key).to_string();
+ ui.close();
+ }
+ }
+ });
+ if !app.ui.status.is_empty() {
+ let (r, _) = ui.allocate_exact_size(vec2(17.0, 16.0), Sense::hover());
+ ui.painter().line_segment([r.center_top(), r.center_bottom()], Stroke::new(1.0, t.separator));
+ let is_err = app.ui.status_error || app.ui.status.starts_with("Couldn");
+ ui.label(RichText::new(&app.ui.status).color(if is_err { t.warning } else { t.text_faint }));
+ }
+}
+
+/// Home button at the very start of Photoshop 2026's options bar: toggles the Home (start)
+/// screen over the open documents, which stay open.
+pub fn home_button(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let n = app.session.documents().len();
+ let on = app.ui.chrome.shows_home(n);
+ if icons::button(ui, "house", 26.0, on && n > 0, "Home").clicked() && n > 0 {
+ app.ui.chrome.home = if on { None } else { Some(n) };
+ }
+}
+
+/// Marquee drag end point under the options-bar Style (Normal, Fixed Ratio, Fixed Size) and Shift
+/// (square/circle while drawing with Normal style), Photoshop behaviour.
+pub fn marquee_end(style: &str, w: f64, h: f64, shift: bool, start: [f64; 2], end: [f64; 2]) -> [f64; 2] {
+ let (dx, dy) = (end[0] - start[0], end[1] - start[1]);
+ let (sx, sy) = (if dx < 0.0 { -1.0 } else { 1.0 }, if dy < 0.0 { -1.0 } else { 1.0 });
+ match style {
+ "fixedSize" => [start[0] + sx * w.max(1.0), start[1] + sy * h.max(1.0)],
+ "fixedRatio" if w > 0.0 && h > 0.0 => {
+ // The larger drag extent wins; the other follows the ratio.
+ let k = (dx.abs() / w).max(dy.abs() / h);
+ [start[0] + sx * k * w, start[1] + sy * k * h]
+ }
+ _ if shift => {
+ let m = dx.abs().max(dy.abs());
+ [start[0] + sx * m, start[1] + sy * m]
+ }
+ _ => end,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn doc() -> Document {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 2400, "height": 1500, "resolution": 72, "background": "white"})).unwrap();
+ (*s.active().unwrap().doc).clone()
+ }
+
+ #[test]
+ fn default_status_shows_dimensions_like_photoshop() {
+ let d = doc();
+ assert_eq!(ChromeState::default().status_info, "dimensions");
+ assert_eq!(status_info_text(&d, "dimensions", "", ""), "2400 px x 1500 px (72 ppi)");
+ assert_eq!(status_info_text(&d, "layers", "", ""), "1 Layer");
+ assert_eq!(status_info_text(&d, "tool", "Brush Tool", ""), "Brush Tool");
+ assert!(status_info_text(&d, "profile", "", "sRGB IEC61966-2.1").ends_with("(8bpc)"));
+ }
+
+ #[test]
+ fn document_sizes_match_photoshop_rounding() {
+ let d = doc();
+ // 2400 x 1500 x 3 bytes = 10.3M flattened, as Photoshop shows.
+ assert_eq!(status_info_text(&d, "sizes", "", ""), "Doc: 10.3M/13.7M");
+ assert_eq!(fmt_bytes(512 * 1024), "512.0K");
+ }
+
+ #[test]
+ fn home_screen_closes_when_a_document_opens() {
+ let mut c = ChromeState::default();
+ assert!(c.shows_home(0));
+ assert!(!c.shows_home(2));
+ c.home = Some(2);
+ assert!(c.shows_home(2));
+ assert!(!c.shows_home(3));
+ }
+
+ #[test]
+ fn marquee_styles_constrain_the_drag() {
+ assert_eq!(marquee_end("normal", 1.0, 1.0, false, [10.0, 10.0], [40.0, 20.0]), [40.0, 20.0]);
+ assert_eq!(marquee_end("normal", 1.0, 1.0, true, [10.0, 10.0], [40.0, 20.0]), [40.0, 40.0]);
+ assert_eq!(marquee_end("fixedSize", 64.0, 32.0, false, [10.0, 10.0], [5.0, 50.0]), [-54.0, 42.0]);
+ assert_eq!(marquee_end("fixedRatio", 2.0, 1.0, false, [0.0, 0.0], [10.0, 30.0]), [60.0, 30.0]);
+ }
+
+ #[test]
+ fn every_status_key_has_text() {
+ let d = doc();
+ for (k, _) in STATUS_INFO {
+ assert!(!status_info_text(&d, k, "x", "p").is_empty());
+ }
+ }
+}
diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs
new file mode 100644
index 000000000..eeadb9848
--- /dev/null
+++ b/crates/ui-egui/src/color_picker_ui.rs
@@ -0,0 +1,362 @@
+//! Photoshop's Color Picker (Foreground / Background Color) dialog: a 2D colour field and a slider
+//! for the selected component (H, S, B, R, G or B radio), new/current swatches, and HSB, RGB, Lab,
+//! CMYK and hex fields. The colour lives in the dialog fields (`color` as `#rrggbb`, plus the HSB
+//! floats so hue survives greys), so `ui.dialog.set` drives it; OK runs `tools.setColors`.
+
+use egui::{Color32, Mesh, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::DialogKind;
+use crate::theme::Tokens;
+use crate::widgets;
+
+/// Radio components, Photoshop order: H, S, B, R, G, B.
+pub const MODES: &[(&str, &str)] = &[("h", "H:"), ("s", "S:"), ("v", "B:"), ("r", "R:"), ("g", "G:"), ("b", "B:")];
+
+pub fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] {
+ let h = (h.rem_euclid(360.0)) / 60.0;
+ let c = v * s;
+ let x = c * (1.0 - (h % 2.0 - 1.0).abs());
+ let (r, g, b) = match h as u32 {
+ 0 => (c, x, 0.0),
+ 1 => (x, c, 0.0),
+ 2 => (0.0, c, x),
+ 3 => (0.0, x, c),
+ 4 => (x, 0.0, c),
+ _ => (c, 0.0, x),
+ };
+ let m = v - c;
+ [r + m, g + m, b + m]
+}
+
+pub fn rgb_to_hsv(c: [f32; 3]) -> [f32; 3] {
+ let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));
+ let d = mx - mn;
+ let h = if d <= 0.0 {
+ 0.0
+ } else if mx == c[0] {
+ 60.0 * ((c[1] - c[2]) / d).rem_euclid(6.0)
+ } else if mx == c[1] {
+ 60.0 * ((c[2] - c[0]) / d + 2.0)
+ } else {
+ 60.0 * ((c[0] - c[1]) / d + 4.0)
+ };
+ [h, if mx <= 0.0 { 0.0 } else { d / mx }, mx]
+}
+
+pub fn hex(c: [f32; 3]) -> String {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ format!("#{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2]))
+}
+
+pub fn parse_hex(s: &str) -> Option<[f32; 3]> {
+ let h = s.trim().trim_start_matches('#');
+ if h.len() != 6 {
+ return None;
+ }
+ let c = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok().map(|v| f32::from(v) / 255.0);
+ Some([c(0)?, c(2)?, c(4)?])
+}
+
+/// The colour at field position (x, y) in 0..1 (y down) for `mode` with the slider at `z` (0..1),
+/// given the current HSV/RGB (used for the components the field doesn't vary).
+pub fn field_color(mode: &str, z: f32, x: f32, y: f32) -> [f32; 3] {
+ match mode {
+ "s" => hsv_to_rgb(x * 360.0, z, 1.0 - y),
+ "v" => hsv_to_rgb(x * 360.0, 1.0 - y, z),
+ "r" => [z, 1.0 - y, x],
+ "g" => [1.0 - y, z, x],
+ "b" => [x, 1.0 - y, z],
+ _ => hsv_to_rgb(z * 360.0, x, 1.0 - y),
+ }
+}
+
+/// Field position and slider value of a colour in `mode` (inverse of [`field_color`]).
+pub fn locate(mode: &str, hsv: [f32; 3], rgb: [f32; 3]) -> (f32, f32, f32) {
+ let h = hsv[0] / 360.0;
+ match mode {
+ "s" => (h, 1.0 - hsv[2], hsv[1]),
+ "v" => (h, 1.0 - hsv[1], hsv[2]),
+ "r" => (rgb[2], 1.0 - rgb[1], rgb[0]),
+ "g" => (rgb[2], 1.0 - rgb[0], rgb[1]),
+ "b" => (rgb[0], 1.0 - rgb[1], rgb[2]),
+ _ => (hsv[1], 1.0 - hsv[2], h),
+ }
+}
+
+/// Colour for slider position `z` (0..1) in `mode`, other components from the current colour.
+fn slider_color(mode: &str, z: f32, hsv: [f32; 3], rgb: [f32; 3]) -> [f32; 3] {
+ match mode {
+ "s" => hsv_to_rgb(hsv[0], z, hsv[2]),
+ "v" => hsv_to_rgb(hsv[0], hsv[1], z),
+ "r" => [z, rgb[1], rgb[2]],
+ "g" => [rgb[0], z, rgb[2]],
+ "b" => [rgb[0], rgb[1], z],
+ _ => hsv_to_rgb(z * 360.0, 1.0, 1.0),
+ }
+}
+
+fn c32(c: [f32; 3]) -> Color32 {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))
+}
+
+/// Open the picker for the foreground or background colour.
+pub fn open(app: &mut PhotocraftApp, target: &str) -> u64 {
+ let c = if target == "background" { app.session.tools.background } else { app.session.tools.foreground };
+ let rgb = [c[0], c[1], c[2]];
+ let hsv = rgb_to_hsv(rgb);
+ let mut f = Map::new();
+ f.insert("__colorPicker".into(), json!(target));
+ f.insert("__label".into(), json!(if target == "background" { "Color Picker (Background Color)" } else { "Color Picker (Foreground Color)" }));
+ f.insert("color".into(), json!(hex(rgb)));
+ f.insert("__orig".into(), json!(hex(rgb)));
+ f.insert("__hsv".into(), json!(hsv));
+ f.insert("__mode".into(), json!("h"));
+ f.insert("__webOnly".into(), json!(false));
+ app.ui.open_dialog(DialogKind::Command, f)
+}
+
+pub fn owns(f: &Map<String, Value>) -> bool {
+ f.contains_key("__colorPicker")
+}
+
+/// Current colour as (rgb, hsv), keeping the stored hue/saturation when they still match `color`.
+pub fn current(f: &Map<String, Value>) -> ([f32; 3], [f32; 3]) {
+ let rgb = f.get("color").and_then(Value::as_str).and_then(parse_hex).unwrap_or([0.0; 3]);
+ let stored: Option<[f32; 3]> = f.get("__hsv").and_then(|v| serde_json::from_value(v.clone()).ok());
+ let hsv = match stored {
+ Some(h) if hex(hsv_to_rgb(h[0], h[1], h[2])) == hex(rgb) => h,
+ _ => rgb_to_hsv(rgb),
+ };
+ (rgb, hsv)
+}
+
+fn set_rgb(f: &mut Map<String, Value>, rgb: [f32; 3], hsv: Option<[f32; 3]>) {
+ let web = f.get("__webOnly").and_then(Value::as_bool).unwrap_or(false);
+ let rgb = if web { rgb.map(|v| (v * 5.0).round() / 5.0) } else { rgb };
+ f.insert("color".into(), json!(hex(rgb)));
+ f.insert("__hsv".into(), json!(hsv.filter(|_| !web).unwrap_or_else(|| rgb_to_hsv(rgb))));
+}
+
+fn grid_mesh(rect: Rect, n: usize, color: impl Fn(f32, f32) -> [f32; 3]) -> Mesh {
+ let mut m = Mesh::default();
+ for j in 0..=n {
+ for i in 0..=n {
+ let (x, y) = (i as f32 / n as f32, j as f32 / n as f32);
+ m.colored_vertex(pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height()), c32(color(x, y)));
+ }
+ }
+ let w = (n + 1) as u32;
+ for j in 0..n as u32 {
+ for i in 0..n as u32 {
+ let a = j * w + i;
+ m.add_triangle(a, a + 1, a + w + 1);
+ m.add_triangle(a, a + w + 1, a + w);
+ }
+ }
+ m
+}
+
+pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let mode = f.get("__mode").and_then(Value::as_str).unwrap_or("h").to_string();
+ let (rgb, hsv) = current(f);
+ let (fx, fy, fz) = locate(&mode, hsv, rgb);
+ ui.horizontal_top(|ui| {
+ // Colour field.
+ let (field, resp) = ui.allocate_exact_size(vec2(256.0, 256.0), Sense::click_and_drag());
+ ui.painter().add(grid_mesh(field, 32, |x, y| field_color(&mode, fz, x, y)));
+ ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
+ let marker = pos2(field.left() + fx * field.width(), field.top() + fy * field.height());
+ ui.painter().circle_stroke(marker, 5.0, Stroke::new(1.5, if hsv[2] > 0.6 && hsv[1] < 0.4 { Color32::BLACK } else { Color32::WHITE }));
+ if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
+ let (x, y) = (((p.x - field.left()) / field.width()).clamp(0.0, 1.0), ((p.y - field.top()) / field.height()).clamp(0.0, 1.0));
+ let c = field_color(&mode, fz, x, y);
+ let h = match mode.as_str() {
+ "h" => Some([fz * 360.0, x, 1.0 - y]),
+ "s" => Some([x * 360.0, fz, 1.0 - y]),
+ "v" => Some([x * 360.0, 1.0 - y, fz]),
+ _ => None,
+ };
+ set_rgb(f, c, h);
+ }
+ ui.add_space(6.0);
+ // Component slider (hue runs 360° at the top to 0° at the bottom, like Photoshop).
+ let (strip, sresp) = ui.allocate_exact_size(vec2(20.0, 256.0), Sense::click_and_drag());
+ ui.painter().add(grid_mesh(strip, 32, |_, y| slider_color(&mode, 1.0 - y, hsv, rgb)));
+ let sy = strip.top() + (1.0 - fz) * strip.height();
+ for (x, dir) in [(strip.left() - 1.0, 1.0f32), (strip.right() + 1.0, -1.0)] {
+ let tri = vec![pos2(x, sy), pos2(x - 6.0 * dir, sy - 4.0), pos2(x - 6.0 * dir, sy + 4.0)];
+ ui.painter().add(egui::Shape::convex_polygon(tri, t.text, Stroke::NONE));
+ }
+ if let Some(p) = sresp.interact_pointer_pos().filter(|_| sresp.dragged() || sresp.clicked()) {
+ let z = 1.0 - ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0);
+ let h = match mode.as_str() {
+ "h" => Some([z * 360.0, hsv[1], hsv[2]]),
+ "s" => Some([hsv[0], z, hsv[2]]),
+ "v" => Some([hsv[0], hsv[1], z]),
+ _ => None,
+ };
+ let c = h.map_or_else(|| slider_color(&mode, z, hsv, rgb), |h| hsv_to_rgb(h[0], h[1], h[2]));
+ set_rgb(f, c, h);
+ }
+ ui.add_space(14.0);
+ ui.vertical(|ui| {
+ // new / current swatches.
+ ui.label(egui::RichText::new("new").size(11.0).color(t.text_dim));
+ let (sw, _) = ui.allocate_exact_size(vec2(64.0, 72.0), Sense::hover());
+ let orig = f.get("__orig").and_then(Value::as_str).and_then(parse_hex).unwrap_or(rgb);
+ ui.painter().rect_filled(Rect::from_min_size(sw.min, vec2(64.0, 36.0)), 0.0, c32(rgb));
+ let cur = Rect::from_min_size(sw.min + vec2(0.0, 36.0), vec2(64.0, 36.0));
+ ui.painter().rect_filled(cur, 0.0, c32(orig));
+ ui.painter().rect_stroke(sw, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
+ let click_cur = ui.interact(cur, ui.id().with("cp-current"), Sense::click());
+ if click_cur.on_hover_text("Click to restore the current colour").clicked() {
+ set_rgb(f, orig, None);
+ }
+ ui.label(egui::RichText::new("current").size(11.0).color(t.text_dim));
+ ui.add_space(10.0);
+ let mut web = f.get("__webOnly").and_then(Value::as_bool).unwrap_or(false);
+ if widgets::checkbox(ui, &mut web, "Only Web Colors").changed() {
+ f.insert("__webOnly".into(), json!(web));
+ set_rgb(f, rgb, None);
+ }
+ });
+ ui.add_space(10.0);
+ ui.vertical(|ui| fields(ui, f, &mode, rgb, hsv));
+ });
+}
+
+/// Component radios and numeric fields: HSB, RGB, Lab, CMYK and hex.
+fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, rgb: [f32; 3], hsv: [f32; 3]) {
+ let t = Tokens::get(ui.ctx());
+ let lab = photocraft_color::convert::srgb_to_lab(rgb);
+ let cmyk = photocraft_color::convert::rgb_to_cmyk(rgb);
+ let mut edit: Option<([f32; 3], Option<[f32; 3]>)> = None;
+ let mut new_mode: Option<&str> = None;
+ egui::Grid::new("cp-fields").num_columns(4).spacing([6.0, 4.0]).show(ui, |ui| {
+ let vals = [hsv[0], hsv[1] * 100.0, hsv[2] * 100.0, rgb[0] * 255.0, rgb[1] * 255.0, rgb[2] * 255.0];
+ let units = ["°", "%", "%", "", "", ""];
+ let ranges = [0.0..=360.0, 0.0..=100.0, 0.0..=100.0, 0.0..=255.0, 0.0..=255.0, 0.0..=255.0];
+ for i in 0..6 {
+ let (key, label) = MODES[i];
+ let on = mode == key;
+ let (r, resp) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::click());
+ ui.painter().circle_stroke(r.center(), 5.5, Stroke::new(1.2, if on { t.accent } else { t.text_faint }));
+ if on {
+ ui.painter().circle_filled(r.center(), 3.0, t.accent);
+ }
+ if resp.clicked() {
+ new_mode = Some(key);
+ }
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ let mut v = vals[i].round();
+ if widgets::value_field(ui, &mut v, ranges[i].clone(), "", 54.0).changed() {
+ let (mut h, mut c) = (hsv, rgb);
+ if i < 3 {
+ h[i] = if i == 0 { v } else { v / 100.0 };
+ c = hsv_to_rgb(h[0], h[1], h[2]);
+ edit = Some((c, Some(h)));
+ } else {
+ c[i - 3] = v / 255.0;
+ edit = Some((c, None));
+ }
+ }
+ ui.label(egui::RichText::new(units[i]).color(t.text_faint));
+ ui.end_row();
+ }
+ for (i, (label, v, range)) in [("L:", lab[0], 0.0..=100.0), ("a:", lab[1], -128.0..=127.0), ("b:", lab[2], -128.0..=127.0)].into_iter().enumerate() {
+ ui.label("");
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ let mut x = v.round();
+ if widgets::value_field(ui, &mut x, range, "", 54.0).changed() {
+ let mut l = lab;
+ l[i] = x;
+ edit = Some((photocraft_color::convert::lab_to_srgb(l).map(|c| c.clamp(0.0, 1.0)), None));
+ }
+ ui.label("");
+ ui.end_row();
+ }
+ for (i, label) in ["C:", "M:", "Y:", "K:"].into_iter().enumerate() {
+ ui.label("");
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ let mut x = (cmyk[i] * 100.0).round();
+ if widgets::value_field(ui, &mut x, 0.0..=100.0, "", 54.0).changed() {
+ let mut k = cmyk;
+ k[i] = x / 100.0;
+ edit = Some((photocraft_color::convert::cmyk_to_rgb(k).map(|c| c.clamp(0.0, 1.0)), None));
+ }
+ ui.label(egui::RichText::new("%").color(t.text_faint));
+ ui.end_row();
+ }
+ ui.label("");
+ ui.label(egui::RichText::new("#").color(t.text_dim));
+ let mut h = hex(rgb).trim_start_matches('#').to_string();
+ let r = ui.add(egui::TextEdit::singleline(&mut h).desired_width(54.0).font(crate::theme::mono(12.0)));
+ if r.changed()
+ && let Some(c) = parse_hex(&h)
+ {
+ edit = Some((c, None));
+ }
+ ui.end_row();
+ });
+ if let Some(m) = new_mode {
+ f.insert("__mode".into(), json!(m));
+ }
+ if let Some((c, h)) = edit {
+ set_rgb(f, c, h);
+ }
+}
+
+/// OK: set the foreground or background colour.
+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ let target = f.get("__colorPicker").and_then(Value::as_str).unwrap_or("foreground");
+ let color = f.get("color").and_then(Value::as_str).unwrap_or("#000000");
+ app.run("tools.setColors", json!({ target: color }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hsv_round_trips() {
+ for c in [[1.0, 0.0, 0.0], [0.2, 0.6, 0.4], [0.5, 0.5, 0.5], [0.0, 0.0, 1.0], [0.9, 0.8, 0.1]] {
+ let h = rgb_to_hsv(c);
+ let back = hsv_to_rgb(h[0], h[1], h[2]);
+ for i in 0..3 {
+ assert!((back[i] - c[i]).abs() < 1e-5, "{c:?} -> {h:?} -> {back:?}");
+ }
+ }
+ assert_eq!(hex([1.0, 0.5, 0.0]), "#ff8000");
+ assert_eq!(parse_hex("#FF8000").map(hex).as_deref(), Some("#ff8000"));
+ }
+
+ #[test]
+ fn field_and_locate_are_inverse_in_every_mode() {
+ let rgb = [0.8, 0.3, 0.2];
+ let hsv = rgb_to_hsv(rgb);
+ for (m, _) in MODES {
+ let (x, y, z) = locate(m, hsv, rgb);
+ let c = field_color(m, z, x, y);
+ assert_eq!(hex(c), hex(rgb), "mode {m}");
+ }
+ }
+
+ #[test]
+ fn hue_survives_grey_and_ok_sets_the_colour() {
+ let mut f = Map::new();
+ f.insert("color".into(), json!("#808080"));
+ f.insert("__hsv".into(), json!([200.0, 0.0, 128.0 / 255.0]));
+ assert_eq!(current(&f).1[0], 200.0);
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ let id = open(&mut app, "background");
+ let d = app.ui.dialog_mut(id).unwrap();
+ d.fields.insert("color".into(), json!("#3366cc"));
+ let fields = d.fields.clone();
+ confirm(&mut app, &fields).unwrap();
+ assert_eq!(hex([app.session.tools.background[0], app.session.tools.background[1], app.session.tools.background[2]]), "#3366cc");
+ }
+}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index c32ae74e1..b30b25722 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -9,7 +9,7 @@
//! - `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size)
//! - `ui.set {tool?, panels?, zoom?, center?, dark?}`: change UI state
//! - `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree
-//! - `ui.dialog.open {kind, fields?}` / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`
+//! - `ui.dialog.open {kind, fields?}` (kinds: newDocument, about, layerStyle {effect?}, colorPicker {target: foreground|background}, command {command}) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`
//! - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
//! - `ui.pointer {events: [{kind: down|move|up, x, y, pressure?}], modifiers?}`: drive the active tool in document coordinates
//! - `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points
@@ -160,6 +160,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
None => err("no active layer"),
};
}
+ "colorPicker" | "ColorPicker" => {
+ let target = if s("target") == Some("background") { "background" } else { "foreground" };
+ return ok(json!({"dialog": crate::color_picker_ui::open(app, target)}));
+ }
"command" | "Command" => {
let Some(cmd) = s("command") else { return err("command dialogs need `command`") };
let label = photocraft_engine::commands::find(cmd).map(|c| c.label).unwrap_or(cmd);
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index a6d67768c..56f29a907 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -19,13 +19,26 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
if let Some(w) = wide {
ui.set_min_width(w.min(460.0));
}
- ui.set_max_width(wide.unwrap_or(if d.kind == DialogKind::LayerStyle || d.fields.contains_key("__export") { 600.0 } else { 440.0 }));
+ if d.kind == DialogKind::NewDocument {
+ ui.set_min_width(800.0);
+ }
+ ui.set_max_width(wide.unwrap_or(if d.kind == DialogKind::NewDocument {
+ 800.0
+ } else if d.kind == DialogKind::LayerStyle || d.fields.contains_key("__export") || crate::color_picker_ui::owns(&d.fields) {
+ 600.0
+ } else {
+ 440.0
+ }));
+ if let Some(w) = crate::file_ui::dialog_width(&d.fields) {
+ ui.set_min_width(w);
+ ui.set_max_width(w);
+ }
ui.label(egui::RichText::new(&title).font(crate::theme::semibold(15.0)));
ui.add_space(4.0);
crate::widgets::hairline(ui);
ui.add_space(8.0);
match d.kind {
- DialogKind::NewDocument => new_document(ui, &mut fields),
+ DialogKind::NewDocument => crate::new_doc_ui::body(ui, &mut fields),
DialogKind::About => {
ui.label("PhotoCraft — an open-source, native image editor written in Rust.");
ui.label(format!("Version {}", photocraft_engine::build_info::long_version()));
@@ -38,6 +51,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
ui.add_space(10.0);
ui.weak("egui · wgpu · photocraft-engine");
}
+ DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields),
+ DialogKind::Command if crate::color_picker_ui::owns(&fields) => crate::color_picker_ui::body(ui, &mut fields),
DialogKind::Command if crate::prefs_ui::owns(&fields) => crate::prefs_ui::body(app, ui, &mut fields),
DialogKind::Command if fields.contains_key("__export") => crate::export_dialog::body(app, ui, &mut fields),
DialogKind::Command if fields.contains_key("__sizing") => crate::sizing::body(ui, &mut fields),
@@ -61,13 +76,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
"Create"
} else if d.fields.contains_key("__export") {
"Export"
+ } else if let Some(l) = crate::file_ui::ok_label(&d.fields) {
+ l
} else {
"OK"
};
if crate::widgets::primary_button(ui, ok_label, 84.0).clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
outcome = Some(true);
}
- if crate::widgets::secondary_button(ui, "Cancel", 84.0).clicked() {
+ if crate::widgets::secondary_button(ui, if d.kind == DialogKind::NewDocument { "Close" } else { "Cancel" }, 84.0).clicked() {
outcome = Some(false);
}
}
@@ -107,12 +124,14 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?;
match d.kind {
DialogKind::NewDocument => {
- let r = app.run("file.new", Value::Object(d.fields));
+ let r = app.run("file.new", crate::new_doc_ui::command_params(&d.fields));
if let Some(i) = app.session.active_index() {
app.ui.views[i].fit_pending = true;
}
r
}
+ DialogKind::Command if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields),
+ DialogKind::Command if crate::color_picker_ui::owns(&d.fields) => crate::color_picker_ui::confirm(app, &d.fields),
DialogKind::Command if crate::prefs_ui::owns(&d.fields) => crate::prefs_ui::confirm(app, &d.fields),
DialogKind::Command if d.fields.contains_key("__export") => crate::export_dialog::confirm(app, &d.fields),
DialogKind::Command => {
@@ -126,49 +145,6 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
}
}
-fn new_document(ui: &mut egui::Ui, f: &mut serde_json::Map<String, Value>) {
- egui::Grid::new("newdoc").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
- ui.label("Name");
- let mut name = f.get("name").and_then(Value::as_str).unwrap_or("Untitled-1").to_string();
- if ui.text_edit_singleline(&mut name).changed() {
- f.insert("name".into(), json!(name));
- }
- ui.end_row();
- for (key, label) in [("width", "Width"), ("height", "Height")] {
- ui.label(label);
- let mut v = f.get(key).and_then(Value::as_u64).unwrap_or(1024) as u32;
- if ui.add(egui::DragValue::new(&mut v).range(1..=300_000).suffix(" px")).changed() {
- f.insert(key.into(), json!(v));
- }
- ui.end_row();
- }
- ui.label("Color Mode");
- let mut mode = f.get("mode").and_then(Value::as_str).unwrap_or("rgb").to_string();
- crate::widgets::dropdown(ui, "nd-mode", &mut mode, &[("rgb".to_string(), "RGB Color"), ("gray".to_string(), "Grayscale"), ("cmyk".to_string(), "CMYK Color"), ("lab".to_string(), "Lab Color")], 150.0);
- f.insert("mode".into(), json!(mode));
- ui.end_row();
- ui.label("Bit Depth");
- let mut depth = f.get("depth").and_then(Value::as_u64).unwrap_or(8);
- crate::widgets::dropdown(ui, "nd-depth", &mut depth, &[(8u64, "8 bit"), (16, "16 bit"), (32, "32 bit")], 150.0);
- f.insert("depth".into(), json!(depth));
- ui.end_row();
- ui.label("Background");
- let mut bg = f.get("background").and_then(Value::as_str).unwrap_or("white").to_string();
- crate::widgets::dropdown(ui, "nd-bg", &mut bg, &[("white".to_string(), "White"), ("black".to_string(), "Black"), ("transparent".to_string(), "Transparent")], 150.0);
- f.insert("background".into(), json!(bg));
- ui.end_row();
- });
- ui.horizontal(|ui| {
- ui.weak("Presets:");
- for (label, w, h) in [("HD", 1920, 1080), ("4K", 3840, 2160), ("Square", 2048, 2048), ("A4 300ppi", 2480, 3508)] {
- if ui.small_button(label).clicked() {
- f.insert("width".into(), json!(w));
- f.insert("height".into(), json!(h));
- }
- }
- });
-}
-
fn command_fields(ui: &mut egui::Ui, f: &mut serde_json::Map<String, Value>) {
let kind = f.get("__kind").and_then(Value::as_str).unwrap_or_default().to_string();
for &(key, label, min, max, default) in crate::panels::adjustment_sliders(&kind) {
diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs
index caddeaf8f..ffd77ff3b 100644
--- a/crates/ui-egui/src/distort_ui.rs
+++ b/crates/ui-egui/src/distort_ui.rs
@@ -23,6 +23,8 @@ pub struct Distort {
pub liquify: Option<crate::liquify_ui::LiquifyDialog>,
pub puppet: Option<crate::puppet_ui::PuppetSession>,
pub perspective: Option<crate::perspective_ui::PerspSession>,
+ /// Filter Gallery dialog (gallery_ui).
+ pub gallery: Option<crate::gallery_ui::GalleryDialog>,
}
impl Distort {
@@ -36,6 +38,7 @@ impl Distort {
"liquify": self.liquify.as_ref().map(|d| d.describe()),
"puppet": self.puppet.as_ref().map(|p| p.describe()),
"perspective": self.perspective.as_ref().map(|p| p.describe()),
+ "gallery": self.gallery.as_ref().map(|g| g.describe()),
})
}
}
@@ -99,6 +102,8 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val
let empty = params.as_object().is_none_or(|o| o.is_empty());
let ui = params.get("ui");
match id {
+ "filter.filterGallery" if empty => Some(crate::gallery_ui::open(app).map(|_| json!({"gallery": app.distort.describe()["gallery"]}))),
+ "filter.filterGallery" if ui.is_some() && app.distort.gallery.is_some() => Some(crate::gallery_ui::control(app, ui.unwrap_or(&Value::Null))),
"filter.liquify" if empty => Some(crate::liquify_ui::open(app, ctx).map(|_| json!({"liquify": app.distort.describe()["liquify"]}))),
"filter.liquify" if ui.is_some() && app.distort.liquify.is_some() => Some(crate::liquify_ui::control(app, ui.unwrap_or(&Value::Null))),
"edit.puppetWarp" | "layer.smartObjects.puppetWarp" if empty => Some(crate::puppet_ui::begin(app, ctx, id).map(|_| json!({"puppet": app.distort.describe()["puppet"]}))),
@@ -132,6 +137,14 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
use egui::{Key, Modifiers};
let enter = |ctx: &egui::Context| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter));
let esc = |ctx: &egui::Context| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
+ if app.distort.gallery.is_some() {
+ if enter(ctx) {
+ let _ = crate::gallery_ui::commit(app);
+ } else if esc(ctx) {
+ app.distort.gallery = None;
+ }
+ return true;
+ }
if app.distort.liquify.is_some() {
if enter(ctx) {
crate::liquify_ui::commit(app);
@@ -184,8 +197,11 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool {
false
}
-/// Full-window dialogs (Liquify).
+/// Full-window dialogs (Liquify, Filter Gallery).
pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if app.distort.gallery.is_some() {
+ crate::gallery_ui::show(app, ctx);
+ }
if app.distort.liquify.is_some() {
crate::liquify_ui::show(app, ctx);
}
diff --git a/crates/ui-egui/src/doc_props_ui.rs b/crates/ui-egui/src/doc_props_ui.rs
new file mode 100644
index 000000000..9264a1ff4
--- /dev/null
+++ b/crates/ui-egui/src/doc_props_ui.rs
@@ -0,0 +1,294 @@
+//! Properties panel › Document: what Photoshop shows when nothing (or the Background layer) is
+//! selected. Canvas size and orientation, resolution, colour mode and bit depth, and the
+//! Rulers & Grids toggles. Every edit dispatches an engine or view command, so the panel stays thin.
+
+use egui::{Align2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2};
+use photocraft_doc::{ColorMode, Document, Layer, LayerContent, LayerId, SampleType};
+use serde_json::{Value, json};
+
+use crate::theme::Tokens;
+use crate::{PhotocraftApp, icons, widgets};
+
+/// Photoshop's Background layer: the locked, opaque raster layer at the bottom of the stack.
+pub fn is_background(doc: &Document, l: &Layer) -> bool {
+ l.name == "Background" && l.locks.transparency && matches!(l.content, LayerContent::Raster(_)) && doc.layers.first().is_some_and(|b| b.id == l.id)
+}
+
+/// Does the Properties panel show the Document view? (No layer selected, or the Background layer.)
+pub fn shows_document(doc: &Document, active: Option<LayerId>) -> bool {
+ match active.and_then(|id| doc.layer(id)) {
+ None => true,
+ Some(l) => is_background(doc, l),
+ }
+}
+
+/// Image › Mode command id and label per colour mode, in Photoshop's dropdown order.
+pub const MODES: &[(ColorMode, &str, &str)] = &[
+ (ColorMode::Bitmap, "Bitmap", "image.mode.bitmap"),
+ (ColorMode::Grayscale, "Grayscale", "image.mode.grayscale"),
+ (ColorMode::Duotone, "Duotone", "image.mode.duotone"),
+ (ColorMode::Indexed, "Indexed Color", "image.mode.indexedColor"),
+ (ColorMode::Rgb, "RGB Color", "image.mode.rgb"),
+ (ColorMode::Cmyk, "CMYK Color", "image.mode.cmyk"),
+ (ColorMode::Lab, "Lab Color", "image.mode.lab"),
+ (ColorMode::Multichannel, "Multichannel", "image.mode.multichannel"),
+];
+
+pub const DEPTHS: &[(SampleType, &str, &str)] =
+ &[(SampleType::U8, "8 Bits/Channel", "image.mode.bits8"), (SampleType::U16, "16 Bits/Channel", "image.mode.bits16"), (SampleType::F32, "32 Bits/Channel", "image.mode.bits32")];
+
+/// Ruler units offered in the Rulers & Grids dropdown (`unitsAndRulers.rulers` values).
+pub const UNITS: &[(&str, &str)] = &[("pixels", "Pixels"), ("inches", "Inches"), ("cm", "Centimeters"), ("mm", "Millimeters"), ("points", "Points"), ("picas", "Picas"), ("percent", "Percent")];
+
+/// `image.canvasSize` params for a new width/height, keeping the aspect ratio when linked.
+pub fn canvas_resize_params(old: (u32, u32), new_w: Option<f32>, new_h: Option<f32>, linked: bool) -> Option<Value> {
+ let (ow, oh) = (old.0 as f32, old.1 as f32);
+ let (mut w, mut h) = (new_w.unwrap_or(ow).round().max(1.0), new_h.unwrap_or(oh).round().max(1.0));
+ if linked {
+ if new_w.is_some() {
+ h = (w * oh / ow).round().max(1.0);
+ } else if new_h.is_some() {
+ w = (h * ow / oh).round().max(1.0);
+ }
+ }
+ ((w, h) != (ow, oh)).then(|| json!({"width": w, "height": h, "anchor": "center"}))
+}
+
+/// Collapsible section header with a chevron, Photoshop Properties style. Returns whether it is open.
+fn section(ui: &mut egui::Ui, id: &str, title: &str) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let key = egui::Id::new(("doc-props-section", id));
+ let mut open = ui.data(|d| d.get_temp::<bool>(key)).unwrap_or(true);
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
+ icons::paint(ui, Rect::from_center_size(pos2(r.left() + 7.0, r.center().y), vec2(12.0, 12.0)), if open { "chevron-down" } else { "chevron-right" }, 11.0, t.text_dim);
+ ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::LEFT_CENTER, title, crate::theme::semibold(12.0), t.text);
+ if resp.clicked() {
+ open = !open;
+ ui.data_mut(|d| d.insert_temp(key, open));
+ }
+ open
+}
+
+/// Right-aligned field label in a fixed-width column.
+fn field_label(ui: &mut egui::Ui, s: &str, w: f32) {
+ let t = Tokens::get(ui.ctx());
+ let (r, _) = ui.allocate_exact_size(vec2(w, 22.0), Sense::hover());
+ ui.painter().text(pos2(r.right() - 4.0, r.center().y), Align2::RIGHT_CENTER, s, egui::FontId::proportional(12.0), t.text_dim);
+}
+
+/// A number field that only reports a committed value (drag released, Enter, focus lost).
+fn committed_field(ui: &mut egui::Ui, id: &str, current: f32, suffix: &str) -> Option<f32> {
+ let key = egui::Id::new(("doc-props-field", id));
+ let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);
+ let r = widgets::value_field(ui, &mut v, 1.0..=300_000.0, suffix, 74.0);
+ if r.dragged() || r.has_focus() {
+ ui.data_mut(|d| d.insert_temp(key, v));
+ return None;
+ }
+ ui.data_mut(|d| d.remove::<f32>(key));
+ (r.drag_stopped() || r.lost_focus() || r.changed()).then_some(v).filter(|v| (*v - current).abs() >= 0.5)
+}
+
+/// A disabled-looking field (Photoshop greys Canvas X/Y for documents without artboards).
+fn dim_field(ui: &mut egui::Ui, text: &str) {
+ let t = Tokens::get(ui.ctx());
+ let (r, _) = ui.allocate_exact_size(vec2(74.0, 24.0), Sense::hover());
+ ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.field_border.gamma_multiply(0.6)), StrokeKind::Inside);
+ ui.painter().text(r.left_center() + vec2(6.0, 0.0), Align2::LEFT_CENTER, text, crate::theme::mono(12.0), t.text_faint);
+}
+
+pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let Some(st) = app.session.active() else { return };
+ let (w, h, mode, depth, dpi) = (st.doc.size.width, st.doc.size.height, st.doc.mode, st.doc.depth, st.doc.resolution_dpi);
+ let has_bg = st.doc.layers.first().is_some_and(|l| is_background(&st.doc, l));
+ let mut run: Vec<(String, Value)> = Vec::new();
+ ui.horizontal(|ui| {
+ let (r, _) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::hover());
+ ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ icons::paint(ui, r, "file", 15.0, t.icon);
+ ui.label(RichText::new("Document").color(t.text));
+ });
+ ui.add_space(4.0);
+ widgets::hairline(ui);
+ ui.add_space(2.0);
+ let label_w = 44.0;
+ if section(ui, "canvas", "Canvas") {
+ let link_key = egui::Id::new("doc-props-link");
+ let linked = ui.data(|d| d.get_temp::<bool>(link_key)).unwrap_or(false);
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ ui.vertical(|ui| {
+ ui.add_space(14.0);
+ if icons::button(ui, if linked { "link" } else { "unlink" }, 22.0, linked, "Link width and height").clicked() {
+ ui.data_mut(|d| d.insert_temp(link_key, !linked));
+ }
+ });
+ ui.vertical(|ui| {
+ ui.horizontal(|ui| {
+ field_label(ui, "W", 18.0);
+ if let Some(v) = committed_field(ui, "w", w as f32, "px") {
+ run.extend(canvas_resize_params((w, h), Some(v), None, linked).map(|p| ("image.canvasSize".to_string(), p)));
+ }
+ field_label(ui, "X", 22.0);
+ dim_field(ui, "0 px");
+ });
+ ui.horizontal(|ui| {
+ field_label(ui, "H", 18.0);
+ if let Some(v) = committed_field(ui, "h", h as f32, "px") {
+ run.extend(canvas_resize_params((w, h), None, Some(v), linked).map(|p| ("image.canvasSize".to_string(), p)));
+ }
+ field_label(ui, "Y", 22.0);
+ dim_field(ui, "0 px");
+ });
+ });
+ });
+ ui.horizontal(|ui| {
+ ui.add_space(label_w + 6.0);
+ ui.spacing_mut().item_spacing.x = 2.0;
+ let portrait = h > w;
+ if icons::button(ui, "rectangle-vertical", 26.0, portrait, "Portrait").clicked() && !portrait && w != h {
+ run.push(("image.canvasSize".into(), json!({"width": h, "height": w, "anchor": "center"})));
+ }
+ if icons::button(ui, "rectangle-horizontal", 26.0, !portrait, "Landscape").clicked() && portrait {
+ run.push(("image.canvasSize".into(), json!({"width": h, "height": w, "anchor": "center"})));
+ }
+ });
+ ui.add_space(2.0);
+ ui.horizontal(|ui| {
+ ui.add_space(label_w + 6.0);
+ ui.label(RichText::new(format!("Resolution: {} pixels/inch", widgets::fmt_num(dpi as f64))).color(t.text));
+ });
+ ui.add_space(2.0);
+ ui.horizontal(|ui| {
+ field_label(ui, "Mode", label_w);
+ let mut m = mode;
+ let opts: Vec<(ColorMode, &str)> = MODES.iter().map(|(m, l, _)| (*m, *l)).collect();
+ if widgets::dropdown(ui, "doc-props-mode", &mut m, &opts, 150.0)
+ && let Some((_, _, id)) = MODES.iter().find(|(x, _, _)| *x == m)
+ {
+ run.push(((*id).to_string(), Value::Null));
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.add_space(label_w + 8.0);
+ let mut d = depth;
+ let opts: Vec<(SampleType, &str)> = DEPTHS.iter().map(|(d, l, _)| (*d, *l)).collect();
+ if widgets::dropdown(ui, "doc-props-depth", &mut d, &opts, 150.0)
+ && let Some((_, _, id)) = DEPTHS.iter().find(|(x, _, _)| *x == d)
+ {
+ run.push(((*id).to_string(), Value::Null));
+ }
+ });
+ ui.horizontal(|ui| {
+ field_label(ui, "Fill", label_w);
+ let (r, _) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::hover());
+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ // The canvas fill is only editable for documents without a Background layer.
+ ui.add_enabled_ui(!has_bg, |ui| {
+ let mut f = 0u8;
+ widgets::dropdown(ui, "doc-props-fill", &mut f, &[(0u8, "Background Color")], 124.0);
+ });
+ });
+ ui.add_space(4.0);
+ }
+ widgets::hairline(ui);
+ ui.add_space(2.0);
+ if section(ui, "rulers", "Rulers & Grids") {
+ ui.horizontal(|ui| {
+ ui.add_space(8.0);
+ ui.spacing_mut().item_spacing.x = 6.0;
+ let pixel_grid = crate::view_cmds::checked(app, "view.show.pixelGrid").unwrap_or(false);
+ for (icon, tip, id, on) in [("ruler", "Rulers (⌘R)", "view.rulers", app.ui.extras.rulers), ("grid-3x3", "Grid (⌘')", "view.show.grid", app.ui.extras.grid), ("grid-2x2", "Pixel Grid", "view.show.pixelGrid", pixel_grid)] {
+ if icons::button(ui, icon, 26.0, on, tip).clicked() {
+ run.push((id.to_string(), Value::Null));
+ }
+ }
+ ui.add_space(8.0);
+ let mut unit = app.session.prefs().units_and_rulers.rulers.name().to_string();
+ let opts: Vec<(String, &str)> = UNITS.iter().map(|(k, l)| (k.to_string(), *l)).collect();
+ if widgets::dropdown(ui, "doc-props-units", &mut unit, &opts, 96.0) {
+ run.push(("prefs.set".into(), json!({"path": "unitsAndRulers.rulers", "value": unit})));
+ }
+ });
+ ui.add_space(4.0);
+ }
+ widgets::hairline(ui);
+ ui.add_space(2.0);
+ if section(ui, "guides", "Guides") {
+ ui.horizontal(|ui| {
+ ui.add_space(8.0);
+ ui.spacing_mut().item_spacing.x = 6.0;
+ for (icon, tip, id) in [("eye", "Show Guides (⌘;)", "view.show.guides"), ("lock", "Lock Guides", "view.lockGuides")] {
+ let on = if id == "view.lockGuides" { app.ui.extras.lock_guides } else { app.ui.extras.guides };
+ if icons::button(ui, icon, 26.0, on, tip).clicked() {
+ run.push((id.to_string(), Value::Null));
+ }
+ }
+ for (label, id) in [("New Guide…", "view.newGuide"), ("Clear", "view.clearGuides")] {
+ if crate::menus::is_enabled(app, id) && widgets::secondary_button(ui, label, 0.0).clicked() {
+ run.push((id.to_string(), Value::Null));
+ }
+ }
+ });
+ }
+ let ctx = ui.ctx().clone();
+ for (id, params) in run {
+ let params = if params.is_null() { json!({}) } else { params };
+ if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::Document;
+
+ fn doc_with_background() -> photocraft_engine::Session {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap();
+ s
+ }
+
+ #[test]
+ fn background_selection_shows_document() {
+ let mut s = doc_with_background();
+ let st = s.active().unwrap();
+ let bg = st.doc.layers[0].id;
+ assert!(is_background(&st.doc, &st.doc.layers[0]));
+ assert!(shows_document(&st.doc, Some(bg)));
+ assert!(shows_document(&st.doc, None));
+ s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap();
+ let st = s.active().unwrap();
+ let ink = st.active_layer.unwrap();
+ assert!(!shows_document(&st.doc, Some(ink)));
+ assert!(!is_background(&st.doc, st.doc.layer(ink).unwrap()));
+ }
+
+ #[test]
+ fn transparent_documents_have_no_background() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap();
+ let st = s.active().unwrap();
+ let d: &Document = &st.doc;
+ assert!(d.layers.iter().all(|l| !is_background(d, l)));
+ }
+
+ #[test]
+ fn canvas_resize_keeps_ratio_when_linked() {
+ assert_eq!(canvas_resize_params((2400, 1500), Some(1200.0), None, true), Some(json!({"width": 1200.0, "height": 750.0, "anchor": "center"})));
+ assert_eq!(canvas_resize_params((2400, 1500), None, Some(3000.0), true), Some(json!({"width": 4800.0, "height": 3000.0, "anchor": "center"})));
+ assert_eq!(canvas_resize_params((2400, 1500), Some(1000.0), None, false), Some(json!({"width": 1000.0, "height": 1500.0, "anchor": "center"})));
+ assert_eq!(canvas_resize_params((2400, 1500), Some(2400.2), None, false), None);
+ }
+
+ #[test]
+ fn document_dropdowns_map_to_live_mode_commands() {
+ for id in MODES.iter().map(|m| m.2).chain(DEPTHS.iter().map(|d| d.2)) {
+ assert!(photocraft_engine::commands::find(id).is_some(), "{id} is not an engine command");
+ }
+ }
+}
diff --git a/crates/ui-egui/src/enable_rules.rs b/crates/ui-egui/src/enable_rules.rs
new file mode 100644
index 000000000..32fc4c80b
--- /dev/null
+++ b/crates/ui-egui/src/enable_rules.rs
@@ -0,0 +1,111 @@
+//! Photoshop menu enablement the engine's per-command checks don't express: the Background layer
+//! (no styles, masks, clipping, arranging, transforms without a selection), layer-kind specific
+//! items (Rasterize ›, Combine Shapes ›), and single-layer documents (Merge Visible, Flatten Image).
+//! Applied on top of `menus::is_enabled`, so menus, shortcuts and the Layers context menu grey the
+//! same items Photoshop greys.
+
+use photocraft_doc::{Document, Layer, LayerContent};
+
+/// Commands Photoshop greys while the Background layer is the active layer.
+fn background_blocks(id: &str, has_selection: bool) -> bool {
+ let prefixes = ["layer.layerMask.", "layer.vectorMask.", "layer.arrange.", "layer.matting."];
+ if prefixes.iter().any(|p| id.starts_with(p)) {
+ return true;
+ }
+ if id.starts_with("layer.layerStyle.") {
+ // Global Light and Hide All Effects are document-wide.
+ return !matches!(id, "layer.layerStyle.globalLight" | "layer.layerStyle.hideAllEffects" | "layer.layerStyle.copyLayerStyle");
+ }
+ // Transforms need a selection on the Background (they then move the selected pixels).
+ if !has_selection && (id == "edit.freeTransform" || (id.starts_with("edit.transform.") && id != "edit.transform.again")) {
+ return true;
+ }
+ matches!(
+ id,
+ "layer.createClippingMask"
+ | "layer.releaseClippingMask"
+ | "layer.mergeDown"
+ | "layer.lockLayers"
+ | "layer.maskAllObjects"
+ | "edit.contentAwareScale"
+ | "edit.puppetWarp"
+ | "edit.perspectiveWarp"
+ )
+}
+
+/// Commands that only apply to some layer kinds.
+fn kind_blocks(id: &str, l: &Layer) -> bool {
+ let c = &l.content;
+ match id {
+ "layer.rasterize.type" | "layer.rasterize.rasterizeType" => !matches!(c, LayerContent::Text(_)),
+ "layer.rasterize.shape" | "layer.rasterize.rasterizeShape" => !matches!(c, LayerContent::Shape(_)),
+ "layer.rasterize.fillContent" => !matches!(c, LayerContent::Fill(_)),
+ "layer.rasterize.smartObject" => !matches!(c, LayerContent::Smart(_)),
+ "layer.rasterize.vectorMask" => l.vector_mask.is_none(),
+ "layer.rasterize.layer" => matches!(c, LayerContent::Raster(_) | LayerContent::Group(_) | LayerContent::Adjustment(_)) && l.vector_mask.is_none() && l.effects.items.is_empty(),
+ "layer.layerStyle.copyLayerStyle" | "layer.layerStyle.clear" => l.effects.items.is_empty(),
+ _ => id.starts_with("layer.combineShapes.") && !matches!(c, LayerContent::Shape(_)),
+ }
+}
+
+/// Is `id` greyed in Photoshop for this document state, regardless of the engine's own check?
+pub fn disabled_for(doc: &Document, active: Option<&Layer>, id: &str) -> bool {
+ let only_background = doc.layers.len() == 1 && doc.layers.first().is_some_and(|b| crate::doc_props_ui::is_background(doc, b));
+ if only_background && matches!(id, "layer.mergeVisible" | "layer.flattenImage" | "layer.mergeLayers" | "layer.rasterize.allLayers") {
+ return true;
+ }
+ if id == "layer.delete.hiddenLayers" && doc.walk().iter().all(|(_, _, l)| l.visible) {
+ return true;
+ }
+ let Some(l) = active else { return false };
+ if crate::doc_props_ui::is_background(doc, l) && background_blocks(id, doc.selection.is_some()) {
+ return true;
+ }
+ kind_blocks(id, l)
+}
+
+pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool {
+ let Some(st) = app.session.active() else { return false };
+ let active = st.active_layer.and_then(|a| st.doc.layer(a));
+ disabled_for(&st.doc, active, id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn session() -> photocraft_engine::Session {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();
+ s
+ }
+
+ fn off(s: &photocraft_engine::Session, id: &str) -> bool {
+ let st = s.active().unwrap();
+ disabled_for(&st.doc, st.active_layer.and_then(|a| st.doc.layer(a)), id)
+ }
+
+ #[test]
+ fn background_greys_styles_masks_and_transforms() {
+ let mut s = session();
+ for id in ["layer.layerStyle.dropShadow", "layer.layerMask.revealAll", "layer.arrange.bringForward", "layer.mergeDown", "edit.freeTransform", "edit.transform.scale", "layer.flattenImage", "layer.mergeVisible", "layer.createClippingMask", "layer.rasterize.layer", "layer.combineShapes.unite", "layer.delete.hiddenLayers"] {
+ assert!(off(&s, id), "{id} should be greyed on a lone Background");
+ }
+ assert!(!off(&s, "layer.layerStyle.globalLight"));
+ // A selection makes Free Transform available on the Background.
+ s.execute("select.all", json!({})).unwrap();
+ assert!(!off(&s, "edit.freeTransform"));
+ }
+
+ #[test]
+ fn ordinary_layers_keep_their_items() {
+ let mut s = session();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ for id in ["layer.layerStyle.dropShadow", "layer.layerMask.revealAll", "layer.mergeDown", "edit.freeTransform", "layer.flattenImage"] {
+ assert!(!off(&s, id), "{id}");
+ }
+ assert!(off(&s, "layer.rasterize.type"));
+ assert!(off(&s, "layer.layerStyle.copyLayerStyle"));
+ }
+}
diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs
index ee4b7cb72..a61d9c965 100644
--- a/crates/ui-egui/src/export_dialog.rs
+++ b/crates/ui-egui/src/export_dialog.rs
@@ -197,8 +197,27 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
Ok(json!({"path": path, "bytes": bytes.len()}))
}
-/// File › Export › Quick Export as PNG: current settings-free PNG next to the document.
+/// File › Export › Quick Export as PNG: the format, quality, metadata, colour space and location
+/// from File › Export › Export Preferences (engine `file.export.quickExport`). On the web (no
+/// file system) it falls back to a PNG download through the export service.
pub fn quick_export_png(app: &mut PhotocraftApp) -> Result<Value, String> {
+ if !cfg!(target_arch = "wasm32") {
+ let prefs = app.session.prefs().export.clone();
+ let fmt = serde_json::to_value(prefs.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into());
+ let same = serde_json::to_value(prefs.quick_export_location).ok().is_some_and(|v| v == "sameFolder");
+ let saved = app.session.active().is_some_and(|d| d.path.is_some());
+ let p = if same && saved {
+ json!({})
+ } else {
+ let st = app.session.active().ok_or("no document")?;
+ let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a).to_string();
+ let path = app.services.pick_save.as_mut().and_then(|p| p(&format!("{stem}.{fmt}"))).ok_or("cancelled")?;
+ json!({"path": path})
+ };
+ let r = app.run("file.export.quickExport", p)?;
+ app.ui.status = format!("Exported {}", r["path"].as_str().unwrap_or_default());
+ return Ok(r);
+ }
let mut f = Map::new();
f.insert("format".into(), json!("png"));
f.insert("transparency".into(), json!(true));
diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs
new file mode 100644
index 000000000..931ae1f3c
--- /dev/null
+++ b/crates/ui-egui/src/file_ui.rs
@@ -0,0 +1,625 @@
+//! Front ends of the File-menu commands added with slices: the Save for Web (Legacy) dialog
+//! (Original / Optimized / 2-Up / 4-Up previews, GIF / PNG-8 / PNG-24 / JPEG / WBMP settings,
+//! image size, per-slice output), the Print dialog (page preview with position, scale, marks;
+//! colour handling), and form dialogs for Contact Sheet II, Create Droplet, Statistics, Script
+//! Events Manager, Package and Paths to Illustrator. Every OK runs the engine command with the
+//! dialog's fields, so the control channel can drive them with `ui.dialog.set` / `confirm`.
+
+use std::sync::Arc;
+
+use photocraft_engine::web_cmds::{self, Optimized, WebSettings};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::DialogKind;
+use crate::theme::Tokens;
+
+fn no_params(p: &Value) -> bool {
+ p.as_object().is_none_or(|o| o.is_empty())
+}
+
+fn default_dir(app: &PhotocraftApp) -> String {
+ app.session.active().and_then(|d| d.path.as_deref()).and_then(|p| p.rfind(['/', '\\']).map(|i| p[..i].to_string())).unwrap_or_else(|| ".".into())
+}
+
+fn doc_stem(app: &PhotocraftApp) -> String {
+ app.session.active().map(|d| d.doc.name.rsplit_once('.').map_or(d.doc.name.clone(), |(a, _)| a.to_string())).unwrap_or_else(|| "Untitled".into())
+}
+
+/// A generic form dialog for `command` (rendered by `view_cmds::form_body`).
+fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choices: Value) -> Value {
+ let mut f = Map::new();
+ f.insert("__command".into(), json!(command));
+ f.insert("__label".into(), json!(label));
+ f.insert("__form".into(), json!(true));
+ f.insert("__choices".into(), choices);
+ if let Value::Object(m) = fields {
+ f.extend(m);
+ }
+ json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)})
+}
+
+/// Menu items fronted here (dialogs before the engine command). `None` when not ours.
+pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if !no_params(params) {
+ return None;
+ }
+ let dir = default_dir(app);
+ let stem = doc_stem(app);
+ Some(Ok(match id {
+ "file.export.saveForWebLegacy" => {
+ app.session.active()?;
+ json!({"dialog": open_web(app)})
+ }
+ "file.print" => {
+ app.session.active()?;
+ json!({"dialog": open_print(app)})
+ }
+ "file.printOneCopy" if app.session.file_menu.last_print.is_none() => {
+ app.session.active()?;
+ json!({"dialog": open_print(app)})
+ }
+ "file.export.exportPreferences" => return crate::prefs_ui::invoke(app, ctx, "edit.preferences.export", &json!({})),
+ "file.automate.contactSheetII" => form(
+ app,
+ id,
+ "Contact Sheet II",
+ json!({"input": dir, "units": "inches", "width": 8.0, "height": 10.0, "resolution": 300.0, "mode": "rgb", "depth": 8, "columns": 5, "rows": 6, "placeAcrossFirst": true, "autoSpacing": true, "rotateForBestFit": false, "caption": true, "font": photocraft_text::fonts::DEFAULT_FAMILY, "fontSize": 12.0, "flatten": false}),
+ json!({"units": ["inches", "cm", "pixels"], "mode": ["rgb", "gray", "cmyk", "lab"]}),
+ ),
+ "file.automate.createDroplet" => {
+ let a = &app.ui.actions;
+ let action = a.selected.and_then(|i| a.list.get(i)).or(a.list.first());
+ let Some(action) = action else {
+ return Some(Err("record an action in the Actions panel first".into()));
+ };
+ let steps: Vec<Value> = action.steps.iter().map(|(id, p)| json!([id, p])).collect();
+ let name = action.name.clone();
+ form(app, id, "Create Droplet", json!({"path": format!("{dir}/{name}.pcdroplet"), "name": name, "steps": steps, "output": format!("{dir}/droplet-output"), "format": "same"}), json!({"format": ["same", "png", "jpg", "psd", "tiff"]}))
+ }
+ "file.scripts.statistics" => {
+ let modes: Vec<&str> = photocraft_doc::StackMode::ALL.iter().map(|m| m.id()).collect();
+ form(app, id, "Image Statistics", json!({"mode": "median", "input": dir, "align": false}), json!({"mode": modes}))
+ }
+ "file.scripts.browse" => {
+ let (name, bytes) = app.services.pick_open.as_mut().and_then(|f| f())?;
+ let r = app.run(id, json!({"script": String::from_utf8_lossy(&bytes)}));
+ if r.is_ok() {
+ app.ui.status = format!("Ran script {name}");
+ }
+ return Some(r);
+ }
+ "file.scripts.scriptEventsManager" => {
+ let enabled = app.session.prefs().script_events.enabled;
+ let events: Vec<&str> = photocraft_engine::automate_cmds::EVENTS.iter().map(|e| e.0).collect();
+ form(app, id, "Script Events Manager", json!({"enabled": enabled, "event": "openDocument", "script": "", "name": ""}), json!({"event": events}))
+ }
+ "file.package" => form(app, id, "Package", json!({"dir": dir}), json!({})),
+ "file.export.pathsToIllustrator" => {
+ let mut names = vec!["all".to_string()];
+ if let Some(d) = app.session.active() {
+ if d.doc.work_path.is_some() {
+ names.push("work".into());
+ }
+ names.extend(d.doc.paths.iter().map(|p| p.name.clone()));
+ }
+ form(app, id, "Export Paths to File", json!({"path": format!("{dir}/{stem}.ai"), "paths": "all"}), json!({"paths": names}))
+ }
+ _ => return None,
+ }))
+}
+
+/// Checked state of toggle items owned here.
+pub fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ match id {
+ "view.lockSlices" => Some(app.session.file_menu.slices_locked),
+ "file.generate.imageAssets" => Some(app.session.active().is_some_and(|d| app.session.file_menu.image_assets.contains(&d.doc.id))),
+ _ => None,
+ }
+}
+
+/// Dialogs whose body and confirm live here.
+pub fn owns(f: &Map<String, Value>) -> bool {
+ f.contains_key("__web") || f.contains_key("__print")
+}
+
+pub fn dialog_width(f: &Map<String, Value>) -> Option<f32> {
+ if f.contains_key("__web") {
+ Some(900.0)
+ } else if f.contains_key("__print") {
+ Some(720.0)
+ } else {
+ None
+ }
+}
+
+pub fn ok_label(f: &Map<String, Value>) -> Option<&'static str> {
+ if f.contains_key("__web") {
+ Some("Save…")
+ } else if f.contains_key("__print") {
+ Some("Print")
+ } else {
+ None
+ }
+}
+
+pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ if f.contains_key("__web") {
+ web_body(app, ui, f);
+ } else {
+ print_body(app, ui, f);
+ }
+}
+
+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ if f.contains_key("__web") { web_confirm(app, f) } else { print_confirm(app, f) }
+}
+
+fn params(f: &Map<String, Value>) -> Value {
+ Value::Object(f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect())
+}
+
+fn s(f: &Map<String, Value>, k: &str, d: &str) -> String {
+ f.get(k).and_then(Value::as_str).unwrap_or(d).to_string()
+}
+fn n(f: &Map<String, Value>, k: &str, d: f64) -> f64 {
+ f.get(k).and_then(Value::as_f64).unwrap_or(d)
+}
+fn b(f: &Map<String, Value>, k: &str, d: bool) -> bool {
+ f.get(k).and_then(Value::as_bool).unwrap_or(d)
+}
+
+// ---------- Save for Web ----------
+
+const WEB_FORMATS: [(&str, &str); 5] = [("gif", "GIF"), ("png8", "PNG-8"), ("png24", "PNG-24"), ("jpeg", "JPEG"), ("wbmp", "WBMP")];
+
+pub fn open_web(app: &mut PhotocraftApp) -> u64 {
+ let mut f = Map::new();
+ f.insert("__web".into(), json!(true));
+ f.insert("__label".into(), json!("Save for Web (Legacy)"));
+ f.insert("__view".into(), json!("2up"));
+ // Start from the last settings, like Photoshop.
+ let last = app.session.file_menu.last_web.clone().unwrap_or_else(|| json!({"format": "jpeg", "quality": 60}));
+ if let Value::Object(m) = last {
+ for (k, v) in m {
+ if !matches!(k.as_str(), "path" | "dir") {
+ f.insert(k, v);
+ }
+ }
+ }
+ for (k, v) in [("format", json!("jpeg")), ("quality", json!(60)), ("palette", json!("selective")), ("colors", json!(128)), ("dither", json!("diffusion")), ("ditherAmount", json!(88)), ("transparency", json!(true)), ("matte", json!("#ffffff")), ("interlaced", json!(false)), ("progressive", json!(false)), ("optimized", json!(true)), ("embedIcc", json!(false)), ("convertToSrgb", json!(true)), ("metadata", json!("copyright")), ("percent", json!(100.0)), ("webSnap", json!(0))] {
+ f.entry(k.to_string()).or_insert(v);
+ }
+ app.ui.open_dialog(DialogKind::Command, f)
+}
+
+/// Settings variants shown in 4-Up (current, then two smaller alternatives).
+fn variants(p: &Value) -> Vec<Value> {
+ let mut out = vec![p.clone()];
+ let fmt = p["format"].as_str().unwrap_or("jpeg");
+ for k in [2.0, 4.0] {
+ let mut v = p.clone();
+ if fmt == "jpeg" {
+ v["quality"] = json!((p["quality"].as_f64().unwrap_or(60.0) / k).round().max(1.0));
+ } else if fmt == "gif" || fmt == "png8" {
+ v["colors"] = json!((p["colors"].as_f64().unwrap_or(128.0) / k).round().max(2.0));
+ } else {
+ v["format"] = json!(if k == 2.0 { "png8" } else { "gif" });
+ v["colors"] = json!(256 / k as u32);
+ }
+ out.push(v);
+ }
+ out
+}
+
+type WebCache = (String, Arc<egui::TextureHandle>, Option<(usize, Option<usize>, &'static str)>);
+
+/// Renders one preview pane: the original (`None`) or an optimised variant.
+fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option<&Value>, full_px: f64) {
+ let t = Tokens::get(ui.ctx());
+ let Some(st) = app.session.active() else { return };
+ let doc = st.doc.clone();
+ let rev = st.revision;
+ // The proxy: the export size, at most 640 px on the long side.
+ let base = p.cloned().unwrap_or_else(|| json!({}));
+ let size_sig = format!("{}|{}|{}", base["percent"], base["width"], base["height"]);
+ let wkey = egui::Id::new(("web-proxy", doc.id.0, rev, size_sig.clone()));
+ let proxy: Option<(Arc<Vec<[f32; 4]>>, u32, u32, f64)> = ui.data(|d| d.get_temp(wkey));
+ let (px, w, h, ratio) = match proxy {
+ Some(v) => v,
+ None => {
+ let pct = base["percent"].as_f64().unwrap_or(100.0).max(1.0) / 100.0;
+ let (fw, fh) = (f64::from(doc.size.width) * pct, f64::from(doc.size.height) * pct);
+ let k = (640.0 / fw.max(fh)).min(1.0);
+ let st = WebSettings::default();
+ let Ok((wd, _, _)) = web_cmds::web_document(&doc, &json!({"width": (fw * k).round().max(1.0), "height": (fh * k).round().max(1.0), "resample": "bilinear"}), &st) else { return };
+ let buf = photocraft_compose::flatten(&wd);
+ let v = (Arc::new(buf.px), wd.size.width, wd.size.height, (fw * fh) / (f64::from(wd.size.width) * f64::from(wd.size.height)).max(1.0));
+ ui.data_mut(|d| d.insert_temp(wkey, v.clone()));
+ v
+ }
+ };
+ let sig = format!("{}{}", size_sig, p.map(|v| v.to_string()).unwrap_or_else(|| "original".into()));
+ let key = egui::Id::new(("web-pane", doc.id.0, rev, sig.clone()));
+ let cached: Option<WebCache> = ui.data(|d| d.get_temp(key));
+ let (tex, info) = match cached.filter(|c| c.0 == sig) {
+ Some((_, tex, info)) => (tex, info),
+ None => {
+ let (rgba, info) = match p {
+ None => (px.iter().flat_map(|q| q.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect::<Vec<u8>>(), None),
+ Some(p) => match WebSettings::from_params(p, "preview").and_then(|st| web_cmds::optimize(&px, w as usize, photocraft_geom::Rect::new(0, 0, w as i32, h as i32), &st, None, None, 72.0, true)) {
+ Ok(Optimized { preview, bytes, colors, ext, .. }) => (preview, Some(((bytes.len() as f64 * ratio) as usize, colors, ext))),
+ Err(_) => (vec![0; (w * h * 4) as usize], None),
+ },
+ };
+ let img = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &rgba);
+ let tex = Arc::new(ui.ctx().load_texture("web-pane", img, egui::TextureOptions::LINEAR));
+ ui.data_mut(|d| d.insert_temp(key, (sig, tex.clone(), info)));
+ (tex, info)
+ }
+ };
+ ui.vertical(|ui| {
+ let (r, _) = ui.allocate_exact_size(size - egui::vec2(0.0, 34.0), egui::Sense::hover());
+ crate::widgets::checker(ui.painter(), r, 8.0);
+ let ts = tex.size_vec2();
+ let k = (r.width() / ts.x).min(r.height() / ts.y).min(1.0);
+ let ir = egui::Rect::from_center_size(r.center(), ts * k);
+ ui.painter().image(tex.id(), ir, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
+ ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
+ let _ = full_px;
+ let (l1, l2) = match (p, info) {
+ (None, _) => ("Original".to_string(), format!("{} · {} × {} px", doc.name, doc.size.width, doc.size.height)),
+ (Some(_), Some((bytes, colors, ext))) => {
+ // Photoshop's download estimate at 56.6 Kbps.
+ let secs = (bytes as f64 * 8.0 / 56_600.0).ceil();
+ (format!("{} {}", ext.to_uppercase(), crate::sizing::human_bytes(bytes as f64)), format!("{secs} sec @ 56.6 Kbps{}", colors.map(|c| format!(" · {c} colors")).unwrap_or_default()))
+ }
+ (Some(_), None) => ("—".into(), String::new()),
+ };
+ ui.label(egui::RichText::new(l1).color(t.text).size(11.5));
+ ui.label(egui::RichText::new(l2).color(t.text_dim).size(11.0));
+ });
+}
+
+fn dropdown_str(ui: &mut egui::Ui, id: &str, f: &mut Map<String, Value>, key: &str, opts: &[(&str, &str)], w: f32) {
+ let mut v = s(f, key, opts.first().map_or("", |o| o.0));
+ let o: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.to_string(), *l)).collect();
+ if crate::widgets::dropdown(ui, id, &mut v, &o, w) {
+ f.insert(key.into(), json!(v));
+ }
+}
+
+fn check(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str, d: bool) {
+ let mut v = b(f, key, d);
+ crate::widgets::checkbox(ui, &mut v, label);
+ f.insert(key.into(), json!(v));
+}
+
+fn number(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str, range: std::ops::RangeInclusive<f32>, unit: &str, d: f64) {
+ let t = Tokens::get(ui.ctx());
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ let mut v = n(f, key, d) as f32;
+ crate::widgets::value_field(ui, &mut v, range, unit, 64.0);
+ f.insert(key.into(), json!(v.round()));
+ });
+}
+
+fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
+ ui.horizontal(|ui| {
+ let mut view = s(f, "__view", "2up");
+ for (k, l) in [("original", "Original"), ("optimized", "Optimized"), ("2up", "2-Up"), ("4up", "4-Up")] {
+ if ui.selectable_label(view == k, l).clicked() {
+ view = k.into();
+ }
+ }
+ f.insert("__view".into(), json!(view));
+ });
+ ui.add_space(4.0);
+ let p = params(f);
+ let full_px = f64::from(doc.size.width) * f64::from(doc.size.height);
+ ui.horizontal_top(|ui| {
+ // Previews.
+ let area = egui::vec2(600.0, 470.0);
+ ui.vertical(|ui| {
+ ui.set_width(area.x);
+ match s(f, "__view", "2up").as_str() {
+ "original" => web_pane(app, ui, area, None, full_px),
+ "optimized" => web_pane(app, ui, area, Some(&p), full_px),
+ "2up" => {
+ ui.horizontal(|ui| {
+ web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), None, full_px);
+ web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), Some(&p), full_px);
+ });
+ }
+ _ => {
+ let v = variants(&p);
+ let cell = egui::vec2(area.x / 2.0 - 4.0, area.y / 2.0 - 2.0);
+ ui.horizontal(|ui| {
+ web_pane(app, ui, cell, None, full_px);
+ web_pane(app, ui, cell, Some(&v[0]), full_px);
+ });
+ ui.horizontal(|ui| {
+ web_pane(app, ui, cell, Some(&v[1]), full_px);
+ web_pane(app, ui, cell, Some(&v[2]), full_px);
+ });
+ }
+ }
+ });
+ ui.add_space(10.0);
+ // Settings.
+ ui.vertical(|ui| {
+ ui.set_width(250.0);
+ ui.label(egui::RichText::new("Preset").color(t.text_dim));
+ let mut preset = s(f, "__preset", "");
+ let mut opts: Vec<(String, &str)> = vec![("".into(), "[Unnamed]")];
+ opts.extend(web_cmds::PRESETS.iter().map(|p| (p.to_string(), *p)));
+ if crate::widgets::dropdown(ui, "web-preset", &mut preset, &opts, 230.0) && !preset.is_empty() {
+ if let Some(Value::Object(m)) = web_cmds::preset_settings(&preset).map(|st| st.to_params()) {
+ f.extend(m);
+ }
+ f.insert("__preset".into(), json!(preset));
+ }
+ ui.add_space(4.0);
+ dropdown_str(ui, "web-format", f, "format", &WEB_FORMATS, 230.0);
+ ui.add_space(4.0);
+ let fmt = s(f, "format", "jpeg");
+ match fmt.as_str() {
+ "gif" | "png8" => {
+ dropdown_str(ui, "web-palette", f, "palette", &[("perceptual", "Perceptual"), ("selective", "Selective"), ("adaptive", "Adaptive"), ("restrictive", "Restrictive (Web)"), ("exact", "Exact")], 150.0);
+ number(ui, f, "colors", "Colors", 2.0..=256.0, "", 128.0);
+ dropdown_str(ui, "web-dither", f, "dither", &[("none", "No Dither"), ("diffusion", "Diffusion"), ("pattern", "Pattern"), ("noise", "Noise")], 150.0);
+ number(ui, f, "ditherAmount", "Dither", 0.0..=100.0, "%", 88.0);
+ check(ui, f, "transparency", "Transparency", true);
+ check(ui, f, "interlaced", "Interlaced", false);
+ number(ui, f, "webSnap", "Web Snap", 0.0..=100.0, "%", 0.0);
+ }
+ "jpeg" => {
+ number(ui, f, "quality", "Quality", 0.0..=100.0, "", 60.0);
+ check(ui, f, "progressive", "Progressive", false);
+ check(ui, f, "optimized", "Optimized", true);
+ check(ui, f, "embedIcc", "Embed Color Profile", false);
+ }
+ "wbmp" => {
+ dropdown_str(ui, "web-dither", f, "dither", &[("none", "No Dither"), ("diffusion", "Diffusion"), ("pattern", "Pattern")], 150.0);
+ }
+ _ => {
+ check(ui, f, "transparency", "Transparency", true);
+ check(ui, f, "interlaced", "Interlaced", false);
+ }
+ }
+ if fmt != "png24" || !b(f, "transparency", true) {
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Matte").color(t.text_dim));
+ let mut m = s(f, "matte", "#ffffff");
+ if ui.add(egui::TextEdit::singleline(&mut m).desired_width(80.0)).changed() {
+ f.insert("matte".into(), json!(m));
+ }
+ });
+ }
+ ui.add_space(6.0);
+ check(ui, f, "convertToSrgb", "Convert to sRGB", true);
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Metadata").color(t.text_dim));
+ dropdown_str(ui, "web-meta", f, "metadata", &[("none", "None"), ("copyright", "Copyright"), ("copyrightAndContact", "Copyright and Contact Info"), ("all", "All")], 160.0);
+ });
+ ui.add_space(8.0);
+ ui.label(egui::RichText::new("Image Size").font(crate::theme::semibold(12.0)).color(t.text));
+ number(ui, f, "percent", "Percent", 1.0..=1000.0, "%", 100.0);
+ let pct = n(f, "percent", 100.0) / 100.0;
+ ui.label(egui::RichText::new(format!("W: {} px H: {} px", (f64::from(doc.size.width) * pct).round(), (f64::from(doc.size.height) * pct).round())).color(t.text_dim).size(11.5));
+ let nslices = photocraft_doc::slices::resolve(&doc).len();
+ if !doc.slices.is_empty() {
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new(format!("{nslices} slices")).color(t.text_dim));
+ check(ui, f, "html", "Save HTML and Images", true);
+ dropdown_str(ui, "web-slices", f, "slices", &[("all", "All Slices"), ("user", "All User Slices")], 150.0);
+ }
+ });
+ });
+}
+
+fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ let mut p = params(f);
+ let doc = app.session.active().ok_or("no document")?.doc.clone();
+ let has_slices = !doc.slices.is_empty();
+ if p.get("path").is_none() && p.get("dir").is_none() {
+ let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?;
+ let base = photocraft_doc::slices::base_name(&doc);
+ let suggested = if has_slices && b(f, "html", true) { format!("{base}.html") } else { format!("{base}.{}", st.format.ext()) };
+ let path = app.services.pick_save.as_mut().and_then(|pick| pick(&suggested)).ok_or("cancelled")?;
+ if has_slices {
+ let dir = path.rfind(['/', '\\']).map(|i| path[..i].to_string()).unwrap_or_else(|| ".".into());
+ p["dir"] = json!(dir);
+ p["html"] = json!(b(f, "html", true));
+ } else {
+ p["path"] = json!(path);
+ }
+ }
+ let r = app.run("file.export.saveForWebLegacy", p)?;
+ app.ui.status = format!("Saved for Web: {} file(s)", r["files"].as_array().map_or(0, Vec::len));
+ Ok(r)
+}
+
+// ---------- Print ----------
+
+pub fn open_print(app: &mut PhotocraftApp) -> u64 {
+ let mut f = Map::new();
+ f.insert("__print".into(), json!(true));
+ f.insert("__label".into(), json!("PhotoCraft Print Settings"));
+ if let Some(Value::Object(m)) = app.session.file_menu.last_print.clone() {
+ f.extend(m);
+ }
+ for (k, v) in [("printer", json!("")), ("copies", json!(1)), ("paper", json!("letter")), ("orientation", json!("portrait")), ("colorHandling", json!("printerManages")), ("printerProfile", json!("coated-cmyk")), ("intent", json!("relative")), ("bpc", json!(true)), ("center", json!(true)), ("top", json!(0.0)), ("left", json!(0.0)), ("scale", json!(100.0)), ("scaleToFit", json!(false)), ("cornerCropMarks", json!(false)), ("centerCropMarks", json!(false)), ("registrationMarks", json!(false)), ("description", json!(false)), ("labels", json!(false)), ("output", json!(""))] {
+ f.entry(k.to_string()).or_insert(v);
+ }
+ app.ui.open_dialog(DialogKind::Command, f)
+}
+
+fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
+ let p = params(f);
+ ui.horizontal_top(|ui| {
+ // Page preview.
+ let (area, _) = ui.allocate_exact_size(egui::vec2(330.0, 420.0), egui::Sense::hover());
+ ui.painter().rect_filled(area, 0.0, t.canvas);
+ match photocraft_engine::print_cmds::layout(&doc, &p, "file.print") {
+ Ok(l) => {
+ let (pw, ph) = l.paper;
+ let k = ((area.width() - 20.0) / pw as f32).min((area.height() - 20.0) / ph as f32);
+ let page = egui::Rect::from_center_size(area.center(), egui::vec2(pw as f32 * k, ph as f32 * k));
+ ui.painter().rect_filled(page, 0.0, egui::Color32::WHITE);
+ ui.painter().rect_stroke(page, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
+ let (x, y, w, h) = l.rect;
+ let img = egui::Rect::from_min_size(egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), egui::vec2(w as f32 * k, h as f32 * k));
+ let key = egui::Id::new(("print-thumb", doc.id.0, app.session.active().map_or(0, |d| d.revision)));
+ let tex: Option<Arc<egui::TextureHandle>> = ui.data(|d| d.get_temp(key));
+ let tex = tex.unwrap_or_else(|| {
+ let th = photocraft_compose::thumbnail(&doc, 400);
+ let ci = egui::ColorImage::from_rgba_unmultiplied([th.width as usize, th.height as usize], &th.pixels);
+ let tx = Arc::new(ui.ctx().load_texture("print-thumb", ci, egui::TextureOptions::LINEAR));
+ ui.data_mut(|d| d.insert_temp(key, tx.clone()));
+ tx
+ });
+ let clip = ui.painter().with_clip_rect(page);
+ clip.image(tex.id(), img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
+ let mark = egui::Stroke::new(1.0, egui::Color32::BLACK);
+ if l.marks.corner_crop {
+ for (c, dx, dy) in [(img.left_top(), -1.0, -1.0), (img.right_top(), 1.0, -1.0), (img.left_bottom(), -1.0, 1.0), (img.right_bottom(), 1.0, 1.0)] {
+ clip.line_segment([c + egui::vec2(dx * 3.0, 0.0), c + egui::vec2(dx * 12.0, 0.0)], mark);
+ clip.line_segment([c + egui::vec2(0.0, dy * 3.0), c + egui::vec2(0.0, dy * 12.0)], mark);
+ }
+ }
+ if l.marks.registration {
+ for c in [img.center_top() - egui::vec2(0.0, 9.0), img.center_bottom() + egui::vec2(0.0, 9.0), img.left_center() - egui::vec2(9.0, 0.0), img.right_center() + egui::vec2(9.0, 0.0)] {
+ clip.circle_stroke(c, 3.5, mark);
+ }
+ }
+ ui.painter().text(area.left_bottom() + egui::vec2(6.0, -6.0), egui::Align2::LEFT_BOTTOM, format!("Scale {:.1}%", l.scale * 100.0), egui::FontId::proportional(11.0), t.text_dim);
+ }
+ Err(e) => {
+ ui.painter().text(area.center(), egui::Align2::CENTER_CENTER, e.to_string(), egui::FontId::proportional(12.0), t.text_dim);
+ }
+ }
+ ui.add_space(12.0);
+ ui.vertical(|ui| {
+ ui.set_width(340.0);
+ let head = |ui: &mut egui::Ui, s: &str| {
+ ui.add_space(4.0);
+ ui.label(egui::RichText::new(s).font(crate::theme::semibold(12.0)).color(t.text));
+ };
+ head(ui, "Printer Setup");
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Printer").color(t.text_dim));
+ let mut pr = s(f, "printer", "");
+ if ui.add(egui::TextEdit::singleline(&mut pr).hint_text("Default printer").desired_width(180.0)).changed() {
+ f.insert("printer".into(), json!(pr));
+ }
+ });
+ number(ui, f, "copies", "Copies", 1.0..=999.0, "", 1.0);
+ ui.horizontal(|ui| {
+ let papers: Vec<(&str, &str)> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0, p.0)).collect();
+ dropdown_str(ui, "print-paper", f, "paper", &papers, 110.0);
+ dropdown_str(ui, "print-orient", f, "orientation", &[("portrait", "Portrait"), ("landscape", "Landscape")], 110.0);
+ });
+ head(ui, "Color Management");
+ dropdown_str(ui, "print-color", f, "colorHandling", &[("printerManages", "Printer Manages Colors"), ("photocraftManages", "PhotoCraft Manages Colors"), ("noColorManagement", "No Color Management")], 240.0);
+ if s(f, "colorHandling", "") == "photocraftManages" {
+ dropdown_str(ui, "print-profile", f, "printerProfile", &[("coated-cmyk", "Coated CMYK"), ("srgb", "sRGB IEC61966-2.1"), ("adobe-rgb-compat", "Adobe RGB (1998) compatible"), ("display-p3", "Display P3"), ("gray-gamma-2.2", "Gray Gamma 2.2")], 240.0);
+ ui.horizontal(|ui| {
+ dropdown_str(ui, "print-intent", f, "intent", &[("perceptual", "Perceptual"), ("relative", "Relative Colorimetric"), ("saturation", "Saturation"), ("absolute", "Absolute Colorimetric")], 170.0);
+ check(ui, f, "bpc", "Black Point Compensation", true);
+ });
+ }
+ head(ui, "Position and Size");
+ check(ui, f, "center", "Center", true);
+ if !b(f, "center", true) {
+ ui.horizontal(|ui| {
+ number(ui, f, "top", "Top", 0.0..=100.0, "in", 0.0);
+ number(ui, f, "left", "Left", 0.0..=100.0, "in", 0.0);
+ });
+ }
+ check(ui, f, "scaleToFit", "Scale to Fit Media", false);
+ if !b(f, "scaleToFit", false) {
+ number(ui, f, "scale", "Scale", 1.0..=1000.0, "%", 100.0);
+ }
+ head(ui, "Printing Marks");
+ ui.horizontal(|ui| {
+ check(ui, f, "cornerCropMarks", "Corner Crop Marks", false);
+ check(ui, f, "centerCropMarks", "Center Crop Marks", false);
+ });
+ ui.horizontal(|ui| {
+ check(ui, f, "registrationMarks", "Registration Marks", false);
+ check(ui, f, "description", "Description", false);
+ check(ui, f, "labels", "Labels", false);
+ });
+ head(ui, "Save as PDF");
+ let mut out = s(f, "output", "");
+ if ui.add(egui::TextEdit::singleline(&mut out).hint_text("(print to the printer)").desired_width(300.0)).changed() {
+ f.insert("output".into(), json!(out));
+ }
+ });
+ });
+}
+
+fn print_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ let r = app.run("file.print", params(f))?;
+ app.ui.status = if r["sent"] == json!(true) { format!("Sent to the printer ({})", r["spooler"].as_str().unwrap_or("")) } else { format!("Printed to {}", r["pdf"].as_str().unwrap_or("")) };
+ Ok(r)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app() -> (PhotocraftApp, egui::Context) {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap();
+ (app, egui::Context::default())
+ }
+
+ #[test]
+ fn save_for_web_dialog_runs_the_command() {
+ let (mut app, ctx) = app();
+ let r = crate::menus::invoke(&mut app, &ctx, "file.export.saveForWebLegacy", json!({})).unwrap();
+ let id = r["dialog"].as_u64().unwrap();
+ let dir = std::env::temp_dir().join(format!("pc-webui-{}", std::process::id()));
+ let path = dir.join("web.gif").to_string_lossy().into_owned();
+ let d = app.ui.dialog_mut(id).unwrap();
+ d.fields.insert("format".into(), json!("gif"));
+ d.fields.insert("path".into(), json!(path));
+ let r = crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(r["files"][0], json!(path));
+ assert!(std::fs::read(&path).unwrap().starts_with(b"GIF89a"));
+ // The next dialog starts from those settings.
+ let r = crate::menus::invoke(&mut app, &ctx, "file.export.saveForWebLegacy", json!({})).unwrap();
+ let d = app.ui.dialog_mut(r["dialog"].as_u64().unwrap()).unwrap();
+ assert_eq!(d.fields["format"], "gif");
+ assert!(!d.fields.contains_key("path"));
+ }
+
+ #[test]
+ fn print_dialog_and_toggles() {
+ let (mut app, ctx) = app();
+ let r = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap();
+ let id = r["dialog"].as_u64().unwrap();
+ let out = std::env::temp_dir().join(format!("pc-printui-{}.pdf", std::process::id())).to_string_lossy().into_owned();
+ app.ui.dialog_mut(id).unwrap().fields.insert("output".into(), json!(out));
+ let r = crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(r["sent"], false);
+ assert!(std::fs::read(&out).unwrap().starts_with(b"%PDF"));
+ assert_eq!(checked(&app, "view.lockSlices"), Some(false));
+ crate::menus::invoke(&mut app, &ctx, "view.lockSlices", json!({})).unwrap();
+ assert_eq!(checked(&app, "view.lockSlices"), Some(true));
+ crate::menus::invoke(&mut app, &ctx, "file.generate.imageAssets", json!({})).unwrap();
+ assert_eq!(checked(&app, "file.generate.imageAssets"), Some(true));
+ // Form dialogs open for the rest.
+ for id in ["file.automate.contactSheetII", "file.scripts.statistics", "file.scripts.scriptEventsManager", "file.package"] {
+ let r = crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap();
+ assert!(r["dialog"].is_u64(), "{id}");
+ }
+ }
+}
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs
index 42ca4577d..76e7c9329 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -123,6 +123,10 @@ pub const PREVIEWED: &[&str] = &[
];
pub fn has_dialog(command: &str) -> bool {
+ // The Filter Gallery has its own full-window dialog (gallery_ui).
+ if command == "filter.filterGallery" {
+ return false;
+ }
(command.starts_with("filter.") || command.starts_with("select.modify.") || PREVIEWED.contains(&command) || matches!(command, "image.trim" | "view.newGuide" | "select.refineEdge" | "edit.assignProfile" | "edit.convertToProfile" | "view.proofSetup" | "layer.layerStyle.globalLight" | "image.mode.colorTable")) && photocraft_engine::commands::find(command).is_some_and(|c| !parse_spec(c.params).is_empty())
}
@@ -161,7 +165,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
Some(id)
}
-fn label(key: &str) -> String {
+pub(crate) fn label(key: &str) -> String {
// camelCase → "Camel Case"
let mut s = String::new();
for (i, ch) in key.chars().enumerate() {
diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rs
new file mode 100644
index 000000000..0f65be442
--- /dev/null
+++ b/crates/ui-egui/src/gallery_ui.rs
@@ -0,0 +1,650 @@
+//! Filter › Filter Gallery…: a full-window dialog like Photoshop's: a big preview on the left,
+//! the category folders with thumbnails in the middle, and on the right OK / Cancel, the
+//! selected effect's filter and settings, and the effect-layer stack (new, delete, reorder,
+//! show/hide). The stack is applied bottom to top.
+//!
+//! The preview runs the same algorithm as the command on the visible part of the layer
+//! (downsampled when zoomed out). OK runs `filter.filterGallery {effects:[...]}`, one history
+//! step (a smart filter on smart objects). Everything is drivable over the control channel with
+//! `filter.filterGallery {"ui": {...}}` while the dialog is open.
+
+use std::hash::{Hash, Hasher};
+
+use egui::{Align2, Color32, FontId, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};
+use photocraft_algo::{FilterParams, GALLERY_CATEGORIES, GalleryFilter};
+use photocraft_doc::LayerId;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::filter_dialog::{Kind, parse_spec};
+use crate::theme::Tokens;
+use crate::widgets;
+
+const MID_W: f32 = 300.0;
+const RIGHT_W: f32 = 290.0;
+const THUMB: [usize; 2] = [80, 56];
+
+/// One effect layer of the stack.
+#[derive(Clone, Debug, PartialEq)]
+pub struct EffectLayer {
+ pub filter: GalleryFilter,
+ pub params: Map<String, Value>,
+ pub visible: bool,
+}
+
+impl EffectLayer {
+ fn new(filter: GalleryFilter) -> Self {
+ EffectLayer { filter, params: default_params(filter), visible: true }
+ }
+ fn to_json(&self) -> Value {
+ json!({"filter": self.filter.key(), "params": self.params, "visible": self.visible})
+ }
+}
+
+/// The filter's defaults in command-param form (choices by name).
+fn default_params(f: GalleryFilter) -> Map<String, Value> {
+ let mut m = Map::new();
+ for p in parse_spec(f.params_doc()) {
+ let v = match p.kind {
+ Kind::Range { default, .. } => json!(default),
+ Kind::Choice(c) => json!(c[0]),
+ Kind::Bool(b) => json!(b),
+ _ => continue,
+ };
+ m.insert(p.key, v);
+ }
+ m
+}
+
+pub struct GalleryDialog {
+ pub layer: LayerId,
+ layer_name: String,
+ canvas: Rect,
+ src: Surface,
+ /// Apply order: index 0 runs first (shown at the bottom of the list).
+ pub effects: Vec<EffectLayer>,
+ pub selected: usize,
+ open: [bool; 6],
+ foreground: [f32; 4],
+ background: [f32; 4],
+ /// Screen px per document px (0 = fit) and the view centre (document px).
+ pub zoom: f32,
+ center: [f32; 2],
+ tex: Option<TextureHandle>,
+ shown: Option<(u64, ERect)>,
+ thumb_src: Surface,
+ thumbs: Vec<Option<TextureHandle>>,
+ pub preview_ms: f64,
+}
+
+impl GalleryDialog {
+ pub fn describe(&self) -> Value {
+ json!({
+ "layer": self.layer.0,
+ "effects": self.effects.iter().map(EffectLayer::to_json).collect::<Vec<_>>(),
+ "selected": self.selected,
+ "zoom": if self.zoom > 0.0 { json!(self.zoom) } else { json!("fit") },
+ "previewMs": self.preview_ms,
+ })
+ }
+
+ /// The command params for the current stack.
+ pub fn params(&self) -> Value {
+ json!({"effects": self.effects.iter().map(EffectLayer::to_json).collect::<Vec<_>>(), "foreground": self.foreground, "background": self.background})
+ }
+
+ fn cur(&mut self) -> &mut EffectLayer {
+ let i = self.selected.min(self.effects.len() - 1);
+ &mut self.effects[i]
+ }
+
+ fn set_filter(&mut self, f: GalleryFilter) {
+ let e = self.cur();
+ if e.filter != f {
+ *e = EffectLayer { visible: e.visible, ..EffectLayer::new(f) };
+ }
+ }
+
+ fn add(&mut self) {
+ // Like Photoshop: the new effect layer starts as a copy of the selected one, above it.
+ let e = self.cur().clone();
+ self.selected = (self.selected + 1).min(self.effects.len());
+ self.effects.insert(self.selected, e);
+ }
+
+ fn delete(&mut self) {
+ if self.effects.len() > 1 {
+ self.effects.remove(self.selected.min(self.effects.len() - 1));
+ self.selected = self.selected.saturating_sub(1).min(self.effects.len() - 1);
+ }
+ }
+
+ fn move_to(&mut self, from: usize, to: usize) {
+ if from < self.effects.len() && to < self.effects.len() && from != to {
+ let e = self.effects.remove(from);
+ self.effects.insert(to, e);
+ self.selected = to;
+ }
+ }
+}
+
+/// A nearest-neighbour copy of `r` of `surf`, every `k`-th pixel, placed at the origin.
+fn sample(surf: &Surface, r: Rect, k: u32) -> Surface {
+ let k = k.max(1) as i32;
+ let (w, h) = ((r.width() as i32 + k - 1) / k, (r.height() as i32 + k - 1) / k);
+ let mut out = Surface::new(surf.format());
+ if w <= 0 || h <= 0 {
+ return out;
+ }
+ let n = surf.channels();
+ let mut data = Vec::with_capacity((w * h) as usize * n);
+ for j in 0..h {
+ let y = r.y0 + j * k;
+ let row = surf.read_region(Rect::new(r.x0, y, r.x1, y + 1));
+ for i in 0..w {
+ let o = (i * k) as usize * n;
+ data.extend_from_slice(&row[o..o + n]);
+ }
+ }
+ out.write_region(Rect::new(0, 0, w, h), &data);
+ out
+}
+
+/// Runs a stack on a small surface (the preview and thumbnails).
+fn render(src: &Surface, params: &Value) -> Surface {
+ let effects = photocraft_engine::gallery_cmds::effects_from_json(params).unwrap_or_default();
+ let b = src.content_bounds().union(&Rect::new(0, 0, 1, 1));
+ let b = Rect::new(0, 0, b.x1, b.y1);
+ photocraft_algo::apply_in(src, &FilterParams::FilterGallery { effects }, b, b, None, b)
+}
+
+fn image(surf: &Surface, w: usize, h: usize) -> egui::ColorImage {
+ let mut px = vec![[0u8; 4]; w * h];
+ for y in 0..h {
+ surf.read_rgba8_into(Rect::new(0, y as i32, w as i32, y as i32 + 1), &mut px[y * w..(y + 1) * w]);
+ }
+ let alpha = surf.format().alpha;
+ egui::ColorImage::new([w, h], px.iter().map(|p| Color32::from_rgba_unmultiplied(p[0], p[1], p[2], if alpha { p[3] } else { 255 })).collect())
+}
+
+/// Opens the dialog on the active layer, starting from the last gallery stack used.
+pub fn open(app: &mut PhotocraftApp) -> Result<(), String> {
+ let (layer, src, _) = crate::distort_ui::active_pixels(app)?;
+ let st = app.session.active().ok_or("no document")?;
+ let canvas = st.doc.bounds();
+ let layer_name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default();
+ let last = app.session.journal.iter().rev().find(|(id, _)| id == "filter.filterGallery").map(|(_, p)| p.clone());
+ let mut effects: Vec<EffectLayer> = last
+ .as_ref()
+ .and_then(|p| p.get("effects").and_then(Value::as_array).cloned())
+ .unwrap_or_default()
+ .iter()
+ .filter_map(|e| {
+ let f = GalleryFilter::from_key(e.get("filter")?.as_str()?)?;
+ let mut l = EffectLayer::new(f);
+ if let Some(Value::Object(m)) = e.get("params") {
+ l.params.extend(m.clone());
+ }
+ l.visible = e.get("visible").and_then(Value::as_bool).unwrap_or(true);
+ Some(l)
+ })
+ .collect();
+ if effects.is_empty() {
+ effects.push(EffectLayer::new(GalleryFilter::ColoredPencil));
+ }
+ // Thumbnail source: the middle of the layer, about 4× the thumbnail size.
+ let cb = src.content_bounds().intersect(&canvas);
+ let cb = if cb.is_empty() { canvas } else { cb };
+ let k = ((cb.width() as usize / (THUMB[0] * 4)).min(cb.height() as usize / (THUMB[1] * 4))).max(1) as u32;
+ let (tw, th) = (THUMB[0] as i32 * k as i32, THUMB[1] as i32 * k as i32);
+ let (cx, cy) = ((cb.x0 + cb.x1) / 2, (cb.y0 + cb.y1) / 2);
+ let thumb_src = sample(&src, Rect::new(cx - tw / 2, cy - th / 2, cx - tw / 2 + tw, cy - th / 2 + th), k);
+ let sel = effects.len() - 1;
+ let open_cats = std::array::from_fn(|i| effects[sel].filter.category() == GALLERY_CATEGORIES[i]);
+ app.distort.gallery = Some(GalleryDialog {
+ layer,
+ layer_name,
+ canvas,
+ src,
+ effects,
+ selected: sel,
+ open: open_cats,
+ foreground: app.session.tools.foreground,
+ background: app.session.tools.background,
+ zoom: 0.0,
+ center: [(canvas.x0 + canvas.x1) as f32 / 2.0, (canvas.y0 + canvas.y1) as f32 / 2.0],
+ tex: None,
+ shown: None,
+ thumb_src,
+ thumbs: vec![None; GalleryFilter::ALL.len()],
+ preview_ms: 0.0,
+ });
+ Ok(())
+}
+
+/// OK: runs `filter.filterGallery` with the stack (one history step).
+pub fn commit(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let Some(d) = app.distort.gallery.take() else { return Err("the Filter Gallery is not open".into()) };
+ if !d.effects.iter().any(|e| e.visible) {
+ return Ok(json!({"committed": false}));
+ }
+ let mut p = d.params();
+ p["layer"] = json!(d.layer.0);
+ app.run("filter.filterGallery", p)
+}
+
+/// Control channel: `filter.filterGallery {"ui": {...}}` while the dialog is open.
+pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {
+ let flag = |k: &str| ui.get(k).and_then(Value::as_bool) == Some(true);
+ if flag("commit") {
+ let r = commit(app)?;
+ return Ok(json!({"committed": true, "result": r}));
+ }
+ if flag("cancel") {
+ app.distort.gallery = None;
+ return Ok(json!({"cancelled": true}));
+ }
+ let d = app.distort.gallery.as_mut().ok_or("the Filter Gallery is not open")?;
+ if let Some(i) = ui.get("select").and_then(Value::as_u64) {
+ d.selected = (i as usize).min(d.effects.len() - 1);
+ }
+ if flag("add") {
+ d.add();
+ }
+ if flag("delete") {
+ d.delete();
+ }
+ if let Some(i) = ui.get("toggle").and_then(Value::as_u64)
+ && let Some(e) = d.effects.get_mut(i as usize)
+ {
+ e.visible = !e.visible;
+ }
+ if let Some(m) = ui.get("move") {
+ let g = |k: &str| m.get(k).and_then(Value::as_u64).map(|v| v as usize);
+ if let (Some(a), Some(b)) = (g("from"), g("to")) {
+ d.move_to(a, b);
+ }
+ }
+ if let Some(k) = ui.get("filter").and_then(Value::as_str) {
+ let f = GalleryFilter::from_key(k).ok_or_else(|| format!("unknown gallery filter `{k}`"))?;
+ d.set_filter(f);
+ }
+ if let Some(Value::Object(m)) = ui.get("params") {
+ d.cur().params.extend(m.clone());
+ }
+ match ui.get("zoom") {
+ Some(Value::String(s)) if s == "fit" => d.zoom = 0.0,
+ Some(v) if v.is_number() => d.zoom = (v.as_f64().unwrap_or(1.0) as f32).clamp(0.01, 32.0),
+ _ => {}
+ }
+ Ok(d.describe())
+}
+
+/// Recomputes the preview texture when the stack or the view changed.
+fn update_preview(d: &mut GalleryDialog, ctx: &egui::Context, area: ERect) {
+ let (cw, ch) = (d.canvas.width() as f32, d.canvas.height() as f32);
+ let zoom = if d.zoom > 0.0 { d.zoom } else { ((area.width() - 24.0) / cw).min((area.height() - 24.0) / ch).clamp(0.005, 1.0) };
+ if d.zoom <= 0.0 {
+ d.center = [d.canvas.x0 as f32 + cw / 2.0, d.canvas.y0 as f32 + ch / 2.0];
+ }
+ let (hw, hh) = (area.width() / zoom / 2.0, area.height() / zoom / 2.0);
+ let vis = Rect::new((d.center[0] - hw).floor() as i32, (d.center[1] - hh).floor() as i32, (d.center[0] + hw).ceil() as i32, (d.center[1] + hh).ceil() as i32).intersect(&d.canvas);
+ let k = (1.0 / zoom).ceil().max(1.0) as u32;
+ let params = d.params();
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ params.to_string().hash(&mut h);
+ (vis.x0, vis.y0, vis.x1, vis.y1, k).hash(&mut h);
+ let key = h.finish();
+ let screen = ERect::from_min_max(
+ area.center() + vec2((vis.x0 as f32 - d.center[0]) * zoom, (vis.y0 as f32 - d.center[1]) * zoom),
+ area.center() + vec2((vis.x1 as f32 - d.center[0]) * zoom, (vis.y1 as f32 - d.center[1]) * zoom),
+ );
+ if d.shown.is_some_and(|(k0, _)| k0 == key) {
+ d.shown = Some((key, screen));
+ return;
+ }
+ if vis.is_empty() {
+ return;
+ }
+ let t0 = crate::gpu_canvas::now_ms();
+ let small = sample(&d.src, vis, k);
+ let out = render(&small, &params);
+ let (w, hgt) = (vis.width().div_ceil(k) as usize, vis.height().div_ceil(k) as usize);
+ let img = image(&out, w, hgt);
+ match &mut d.tex {
+ Some(t) => t.set(img, egui::TextureOptions::LINEAR),
+ None => d.tex = Some(ctx.load_texture("gallery-preview", img, egui::TextureOptions::LINEAR)),
+ }
+ d.preview_ms = crate::gpu_canvas::now_ms() - t0;
+ d.shown = Some((key, screen));
+}
+
+/// Renders up to `budget` missing thumbnails (spread over frames so opening stays instant).
+fn update_thumbs(d: &mut GalleryDialog, ctx: &egui::Context, budget: usize) {
+ let mut done = 0;
+ for (i, f) in GalleryFilter::ALL.iter().enumerate() {
+ if d.thumbs[i].is_some() || !d.open[GALLERY_CATEGORIES.iter().position(|c| *c == f.category()).unwrap_or(0)] {
+ continue;
+ }
+ if done == budget {
+ ctx.request_repaint();
+ return;
+ }
+ let p = json!({"effects": [{"filter": f.key()}], "foreground": d.foreground, "background": d.background});
+ let out = render(&d.thumb_src, &p);
+ let b = d.thumb_src.content_bounds();
+ let img = image(&out, b.x1.max(1) as usize, b.y1.max(1) as usize);
+ d.thumbs[i] = Some(ctx.load_texture(format!("gallery-thumb-{}", f.key()), img, egui::TextureOptions::LINEAR));
+ done += 1;
+ }
+}
+
+/// Draws the dialog (a full-window layer over the app).
+pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let t = Tokens::get(ctx);
+ let screen = ctx.content_rect();
+ let mut action: Option<&str> = None;
+ egui::Area::new(egui::Id::new("gallery-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
+ let Some(d) = app.distort.gallery.as_mut() else { return };
+ let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover());
+ let painter = ui.painter().clone();
+ painter.rect_filled(full, 0.0, t.chrome);
+ let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0));
+ painter.rect_filled(title, 0.0, t.dock);
+ painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator));
+ let pct = if d.zoom > 0.0 { format!("{:.0}%", d.zoom * 100.0) } else { "Fit".into() };
+ let name = d.effects.get(d.selected).map_or("", |e| e.filter.name());
+ painter.text(title.center(), Align2::CENTER_CENTER, format!("{name} ({}, {pct})", d.layer_name), FontId::proportional(13.0), t.text);
+ let body = ERect::from_min_max(pos2(full.left(), title.bottom()), full.max);
+ let right = ERect::from_min_size(pos2(body.right() - RIGHT_W, body.top()), vec2(RIGHT_W, body.height()));
+ let mid = ERect::from_min_size(pos2(right.left() - MID_W, body.top()), vec2(MID_W, body.height()));
+ let area = ERect::from_min_max(body.min, pos2(mid.left(), body.bottom() - 30.0));
+ let zoom_bar = ERect::from_min_max(pos2(body.left(), area.bottom()), pos2(mid.left(), body.bottom()));
+
+ // ---- Preview ----
+ painter.rect_filled(area, 0.0, t.canvas);
+ update_preview(d, ctx, area);
+ let clip = painter.with_clip_rect(area);
+ if let (Some(tex), Some((_, r))) = (&d.tex, d.shown) {
+ widgets::checker(&clip, r.intersect(area), 8.0);
+ clip.image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ clip.rect_stroke(r, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
+ }
+ let resp = ui.interact(area, egui::Id::new("gallery-preview"), Sense::drag());
+ if resp.dragged() && d.zoom > 0.0 {
+ let dl = resp.drag_delta() / d.zoom;
+ d.center = [d.center[0] - dl.x, d.center[1] - dl.y];
+ }
+ // ---- Zoom bar ----
+ painter.rect_filled(zoom_bar, 0.0, t.dock);
+ let mut zb = ui.new_child(egui::UiBuilder::new().max_rect(zoom_bar.shrink2(vec2(10.0, 3.0))).layout(egui::Layout::left_to_right(egui::Align::Center)));
+ let steps = [0.0f32, 0.125, 0.25, 0.5, 1.0, 2.0, 4.0];
+ if crate::icons::button(&mut zb, "minus", 22.0, false, "Zoom out").clicked() {
+ d.zoom = steps.iter().rev().copied().find(|&s| s > 0.0 && s < d.zoom.max(0.0) - 1e-3).unwrap_or(0.0);
+ }
+ if crate::icons::button(&mut zb, "plus", 22.0, false, "Zoom in").clicked() {
+ d.zoom = steps.iter().copied().find(|&s| s > d.zoom + 1e-3).unwrap_or(4.0);
+ }
+ let mut z = d.zoom;
+ let opts: Vec<(f32, &str)> = vec![(0.0, "Fit in View"), (0.125, "12.5%"), (0.25, "25%"), (0.5, "50%"), (1.0, "100%"), (2.0, "200%"), (4.0, "400%")];
+ if widgets::dropdown(&mut zb, "gallery-zoom", &mut z, &opts, 110.0) {
+ d.zoom = z;
+ }
+ zb.label(egui::RichText::new(format!("preview {:.0} ms", d.preview_ms)).color(t.text_faint).size(11.0));
+
+ // ---- Category folders with thumbnails ----
+ painter.rect_filled(mid, 0.0, t.dock);
+ painter.line_segment([mid.left_top(), mid.left_bottom()], Stroke::new(1.0, t.separator));
+ update_thumbs(d, ctx, 6);
+ let mut mu = ui.new_child(egui::UiBuilder::new().max_rect(mid.shrink2(vec2(8.0, 8.0))));
+ egui::ScrollArea::vertical().id_salt("gallery-tree").show(&mut mu, |ui| {
+ for (ci, cat) in GALLERY_CATEGORIES.iter().enumerate() {
+ let icon = if d.open[ci] { "folder-open" } else { "folder" };
+ let r = ui.horizontal(|ui| {
+ let (ir, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover());
+ crate::icons::paint(ui, ir, icon, 14.0, t.icon);
+ ui.add(egui::Label::new(egui::RichText::new(*cat).color(t.text)).sense(Sense::click()))
+ });
+ if r.inner.clicked() {
+ d.open[ci] = !d.open[ci];
+ }
+ if !d.open[ci] {
+ continue;
+ }
+ let members: Vec<(usize, GalleryFilter)> = GalleryFilter::ALL.iter().copied().enumerate().filter(|(_, f)| f.category() == *cat).collect();
+ egui::Grid::new(format!("gallery-cat-{ci}")).spacing([6.0, 6.0]).show(ui, |ui| {
+ for (n, (i, f)) in members.iter().enumerate() {
+ let selected = d.effects.get(d.selected).is_some_and(|e| e.filter == *f);
+ let cell = ui.vertical(|ui| {
+ let (r, resp) = ui.allocate_exact_size(vec2(THUMB[0] as f32, THUMB[1] as f32), Sense::click());
+ match &d.thumbs[*i] {
+ Some(tex) => {
+ ui.painter().image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ None => {
+ ui.painter().rect_filled(r, 2.0, t.field);
+ }
+ }
+ let stroke = if selected { Stroke::new(2.0, t.accent) } else { Stroke::new(1.0, t.separator) };
+ ui.painter().rect_stroke(r, 0.0, stroke, egui::StrokeKind::Outside);
+ ui.add_sized([THUMB[0] as f32, 14.0], egui::Label::new(egui::RichText::new(f.name()).size(10.5).color(if selected { t.text } else { t.text_dim })).truncate());
+ resp
+ });
+ if cell.inner.clicked() {
+ d.set_filter(*f);
+ }
+ if n % 3 == 2 {
+ ui.end_row();
+ }
+ }
+ });
+ ui.add_space(4.0);
+ }
+ });
+
+ // ---- Right: buttons, filter settings, effect layers ----
+ painter.rect_filled(right, 0.0, t.dock);
+ painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator));
+ let inner = right.shrink2(vec2(12.0, 10.0));
+ let mut ru = ui.new_child(egui::UiBuilder::new().max_rect(inner));
+ ru.spacing_mut().item_spacing.y = 6.0;
+ ru.horizontal(|ui| {
+ if widgets::primary_button(ui, "OK", 120.0).clicked() {
+ action = Some("ok");
+ }
+ if widgets::secondary_button(ui, "Cancel", 120.0).clicked() {
+ action = Some("cancel");
+ }
+ });
+ ru.add_space(4.0);
+ let mut cur = d.effects[d.selected].filter;
+ let names: Vec<(GalleryFilter, &str)> = GalleryFilter::ALL.iter().map(|f| (*f, f.name())).collect();
+ if widgets::dropdown(&mut ru, "gallery-filter", &mut cur, &names, inner.width() - 8.0) {
+ d.set_filter(cur);
+ }
+ widgets::hairline(&mut ru);
+ let list_h = 190.0;
+ let params_h = (inner.height() - 110.0 - list_h).max(80.0);
+ egui::ScrollArea::vertical().id_salt("gallery-params").max_height(params_h).show(&mut ru, |ui| {
+ let sel = d.selected;
+ let e = &mut d.effects[sel];
+ for p in parse_spec(e.filter.params_doc()) {
+ let label = crate::filter_dialog::label(&p.key);
+ match p.kind {
+ Kind::Range { min, max, default } => {
+ let mut v = e.params.get(&p.key).and_then(Value::as_f64).unwrap_or(default as f64) as f32;
+ widgets::slider_row(ui, &label, &mut v, min..=max, "", None);
+ e.params.insert(p.key, json!(v.round()));
+ }
+ Kind::Choice(options) => {
+ let mut c = e.params.get(&p.key).and_then(Value::as_str).unwrap_or(&options[0]).to_string();
+ let labels: Vec<String> = options.iter().map(|o| crate::filter_dialog::label(o)).collect();
+ let opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect();
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(label).color(t.text_dim));
+ widgets::dropdown(ui, &format!("gallery-{}", p.key), &mut c, &opts, 140.0);
+ });
+ e.params.insert(p.key, json!(c));
+ }
+ Kind::Bool(b0) => {
+ let mut b = e.params.get(&p.key).and_then(Value::as_bool).unwrap_or(b0);
+ widgets::checkbox(ui, &mut b, &label);
+ e.params.insert(p.key, json!(b));
+ }
+ Kind::Json if p.key == "glowColor" => {
+ let c = e.params.get("glowColor").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).map(|v| v as f32).collect::<Vec<_>>()).filter(|v| v.len() >= 3);
+ let neon = photocraft_algo::GalleryEffect::new(GalleryFilter::NeonGlow).color;
+ let mut rgb = c.map_or([neon[0], neon[1], neon[2]], |v| [v[0], v[1], v[2]]);
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Glow Color").color(t.text_dim));
+ ui.color_edit_button_rgb(&mut rgb);
+ });
+ e.params.insert("glowColor".into(), json!([rgb[0], rgb[1], rgb[2], 1.0]));
+ }
+ _ => {}
+ }
+ }
+ if e.filter.uses_colours() {
+ ui.label(egui::RichText::new("Uses the foreground and background colours.").color(t.text_faint).size(11.0));
+ }
+ });
+ // Effect layers (top of the list = applied last).
+ let list_top = inner.bottom() - list_h;
+ let lr = ERect::from_min_max(pos2(inner.left(), list_top), inner.max);
+ let mut lu = ui.new_child(egui::UiBuilder::new().max_rect(lr));
+ widgets::hairline(&mut lu);
+ egui::ScrollArea::vertical().id_salt("gallery-layers").max_height(list_h - 44.0).show(&mut lu, |ui| {
+ let mut toggle = None;
+ for i in (0..d.effects.len()).rev() {
+ let sel = i == d.selected;
+ let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click());
+ if sel {
+ ui.painter().rect_filled(row, 2.0, t.accent_soft);
+ }
+ let eye = ERect::from_min_size(row.min + vec2(4.0, 4.0), vec2(16.0, 16.0));
+ crate::icons::paint(ui, eye, if d.effects[i].visible { "eye" } else { "eye-off" }, 14.0, t.icon);
+ ui.painter().text(row.left_center() + vec2(28.0, 0.0), Align2::LEFT_CENTER, d.effects[i].filter.name(), FontId::proportional(12.5), if d.effects[i].visible { t.text } else { t.text_faint });
+ if resp.clicked() {
+ if resp.interact_pointer_pos().is_some_and(|p| p.x < eye.right() + 4.0) {
+ toggle = Some(i);
+ } else {
+ d.selected = i;
+ }
+ }
+ }
+ if let Some(i) = toggle {
+ d.effects[i].visible = !d.effects[i].visible;
+ }
+ });
+ lu.horizontal(|ui| {
+ if crate::icons::button(ui, "chevron-up", 24.0, false, "Move effect layer up").clicked() {
+ let s = d.selected;
+ d.move_to(s, (s + 1).min(d.effects.len() - 1));
+ }
+ if crate::icons::button(ui, "chevron-down", 24.0, false, "Move effect layer down").clicked() {
+ let s = d.selected;
+ d.move_to(s, s.saturating_sub(1));
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "trash", 24.0, false, "Delete effect layer").clicked() {
+ d.delete();
+ }
+ if crate::icons::button(ui, "file-plus", 24.0, false, "New effect layer").clicked() {
+ d.add();
+ }
+ });
+ });
+ });
+ match action {
+ Some("ok") => {
+ let _ = commit(app);
+ }
+ Some("cancel") => app.distort.gallery = None,
+ _ => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.session.execute("file.new", json!({"width": 90, "height": 60, "depth": 16})).unwrap();
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ app.session
+ .edit("paint", |doc, active| {
+ let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ for y in 0..60 {
+ for x in 0..90 {
+ let v = ((x / 6 + y / 6) % 2) as f32;
+ s.write_pixel(x, y, &[v, 0.4, 1.0 - v, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ app.sync_views();
+ app
+ }
+
+ #[test]
+ fn stack_editing_and_commit_match_the_engine() {
+ let ctx = egui::Context::default();
+ let mut app = app();
+ let r = crate::distort_ui::menu(&mut app, &ctx, "filter.filterGallery", &json!({})).unwrap().unwrap();
+ assert_eq!(r["gallery"]["effects"].as_array().unwrap().len(), 1);
+ control(&mut app, &json!({"filter": "cutout", "params": {"numberOfLevels": 3}})).unwrap();
+ control(&mut app, &json!({"add": true})).unwrap();
+ control(&mut app, &json!({"filter": "texturizer", "params": {"texture": "brick", "relief": 20}})).unwrap();
+ control(&mut app, &json!({"add": true})).unwrap();
+ control(&mut app, &json!({"filter": "glowingEdges"})).unwrap();
+ control(&mut app, &json!({"toggle": 2})).unwrap();
+ let d = control(&mut app, &json!({"move": {"from": 1, "to": 0}})).unwrap();
+ let keys: Vec<&str> = d["effects"].as_array().unwrap().iter().map(|e| e["filter"].as_str().unwrap()).collect();
+ assert_eq!(keys, ["texturizer", "cutout", "glowingEdges"]);
+ assert_eq!(d["effects"][2]["visible"], json!(false));
+ // Preview pixels = engine result on the same pixels.
+ let params = app.distort.gallery.as_ref().unwrap().params();
+ let before = app.session.active().unwrap().history.past_len();
+ control(&mut app, &json!({"commit": true})).unwrap();
+ assert!(app.distort.gallery.is_none());
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
+ let (id, p) = app.session.journal.last().cloned().unwrap();
+ assert_eq!(id, "filter.filterGallery");
+ assert_eq!(p["effects"], params["effects"]);
+ // Re-opening starts from the last stack.
+ crate::distort_ui::menu(&mut app, &ctx, "filter.filterGallery", &json!({})).unwrap().unwrap();
+ assert_eq!(app.distort.gallery.as_ref().unwrap().effects.len(), 3);
+ control(&mut app, &json!({"delete": true})).unwrap();
+ assert_eq!(app.distort.gallery.as_ref().unwrap().effects.len(), 2);
+ control(&mut app, &json!({"cancel": true})).unwrap();
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "cancel records nothing");
+ }
+
+ #[test]
+ fn preview_and_thumbnails_render() {
+ let ctx = egui::Context::default();
+ let mut app = app();
+ open(&mut app).unwrap();
+ let d = app.distort.gallery.as_mut().unwrap();
+ update_preview(d, &ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)));
+ assert!(d.tex.is_some() && d.shown.is_some());
+ d.open = [true; 6];
+ update_thumbs(d, &ctx, 100);
+ assert!(d.thumbs.iter().all(Option::is_some));
+ // Preview equals the engine's algorithm on the sampled pixels.
+ let src = sample(&d.src, d.canvas, 1);
+ let a = render(&src, &d.params());
+ let mut s2 = photocraft_engine::Session::new();
+ s2.add_document(app.session.active().unwrap().doc.as_ref().clone(), None);
+ s2.select_layer(d.layer).unwrap();
+ s2.execute("filter.filterGallery", d.params()).unwrap();
+ let st = s2.active().unwrap();
+ let b = st.doc.layer(d.layer).unwrap().surface().unwrap().read_region(d.canvas);
+ let worst = a.read_region(d.canvas).iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
+ assert!(worst < 2e-3, "preview differs from the result by {worst}");
+ }
+}
diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs
index 855026af0..e7b92fdbe 100644
--- a/crates/ui-egui/src/icon_data.rs
+++ b/crates/ui-egui/src/icon_data.rs
@@ -10,16 +10,17 @@ pub static ICONS: &[(&str, &[u8])] = &[
("ban", include_bytes!("../../../assets/icons/ban.svg")),
("bandage", include_bytes!("../../../assets/icons/bandage.svg")),
("blend", include_bytes!("../../../assets/icons/blend.svg")),
- ("brush-cleaning", include_bytes!("../../../assets/icons/brush-cleaning.svg")),
("brush", include_bytes!("../../../assets/icons/brush.svg")),
+ ("brush-cleaning", include_bytes!("../../../assets/icons/brush-cleaning.svg")),
("check", include_bytes!("../../../assets/icons/check.svg")),
("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")),
("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")),
+ ("chevron-up", include_bytes!("../../../assets/icons/chevron-up.svg")),
("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")),
("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),
+ ("circle", include_bytes!("../../../assets/icons/circle.svg")),
("circle-dashed", include_bytes!("../../../assets/icons/circle-dashed.svg")),
("circle-dot", include_bytes!("../../../assets/icons/circle-dot.svg")),
- ("circle", include_bytes!("../../../assets/icons/circle.svg")),
("clock", include_bytes!("../../../assets/icons/clock.svg")),
("cloud", include_bytes!("../../../assets/icons/cloud.svg")),
("compass", include_bytes!("../../../assets/icons/compass.svg")),
@@ -30,25 +31,27 @@ pub static ICONS: &[(&str, &[u8])] = &[
("droplet", include_bytes!("../../../assets/icons/droplet.svg")),
("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")),
("eraser", include_bytes!("../../../assets/icons/eraser.svg")),
- ("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")),
("eye", include_bytes!("../../../assets/icons/eye.svg")),
+ ("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")),
+ ("file", include_bytes!("../../../assets/icons/file.svg")),
("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")),
("flame", include_bytes!("../../../assets/icons/flame.svg")),
+ ("folder", include_bytes!("../../../assets/icons/folder.svg")),
("folder-open", include_bytes!("../../../assets/icons/folder-open.svg")),
("folder-plus", include_bytes!("../../../assets/icons/folder-plus.svg")),
- ("folder", include_bytes!("../../../assets/icons/folder.svg")),
("gauge", include_bytes!("../../../assets/icons/gauge.svg")),
("grid-2x2", include_bytes!("../../../assets/icons/grid-2x2.svg")),
("grid-3x3", include_bytes!("../../../assets/icons/grid-3x3.svg")),
("hand", include_bytes!("../../../assets/icons/hand.svg")),
+ ("house", include_bytes!("../../../assets/icons/house.svg")),
("image", include_bytes!("../../../assets/icons/image.svg")),
("info", include_bytes!("../../../assets/icons/info.svg")),
- ("lasso-select", include_bytes!("../../../assets/icons/lasso-select.svg")),
("lasso", include_bytes!("../../../assets/icons/lasso.svg")),
+ ("lasso-select", include_bytes!("../../../assets/icons/lasso-select.svg")),
("layers", include_bytes!("../../../assets/icons/layers.svg")),
("link", include_bytes!("../../../assets/icons/link.svg")),
- ("lock-open", include_bytes!("../../../assets/icons/lock-open.svg")),
("lock", include_bytes!("../../../assets/icons/lock.svg")),
+ ("lock-open", include_bytes!("../../../assets/icons/lock-open.svg")),
("lollipop", include_bytes!("../../../assets/icons/lollipop.svg")),
("maximize-2", include_bytes!("../../../assets/icons/maximize-2.svg")),
("message-square", include_bytes!("../../../assets/icons/message-square.svg")),
@@ -68,35 +71,42 @@ pub static ICONS: &[(&str, &[u8])] = &[
("plus", include_bytes!("../../../assets/icons/plus.svg")),
("pointer", include_bytes!("../../../assets/icons/pointer.svg")),
("rectangle-horizontal", include_bytes!("../../../assets/icons/rectangle-horizontal.svg")),
+ ("rectangle-vertical", include_bytes!("../../../assets/icons/rectangle-vertical.svg")),
("redo-2", include_bytes!("../../../assets/icons/redo-2.svg")),
("rotate-cw", include_bytes!("../../../assets/icons/rotate-cw.svg")),
+ ("ruler", include_bytes!("../../../assets/icons/ruler.svg")),
("scaling", include_bytes!("../../../assets/icons/scaling.svg")),
- ("scan-line", include_bytes!("../../../assets/icons/scan-line.svg")),
("scan", include_bytes!("../../../assets/icons/scan.svg")),
+ ("scan-line", include_bytes!("../../../assets/icons/scan-line.svg")),
("scissors", include_bytes!("../../../assets/icons/scissors.svg")),
("search", include_bytes!("../../../assets/icons/search.svg")),
("settings", include_bytes!("../../../assets/icons/settings.svg")),
("slash", include_bytes!("../../../assets/icons/slash.svg")),
+ ("slice-knife", include_bytes!("../../../assets/icons/slice-knife.svg")),
("sliders-horizontal", include_bytes!("../../../assets/icons/sliders-horizontal.svg")),
("sparkles", include_bytes!("../../../assets/icons/sparkles.svg")),
("spline", include_bytes!("../../../assets/icons/spline.svg")),
- ("square-dashed-mouse-pointer", include_bytes!("../../../assets/icons/square-dashed-mouse-pointer.svg")),
- ("square-dashed", include_bytes!("../../../assets/icons/square-dashed.svg")),
("square", include_bytes!("../../../assets/icons/square.svg")),
+ ("square-dashed", include_bytes!("../../../assets/icons/square-dashed.svg")),
+ ("square-dashed-mouse-pointer", include_bytes!("../../../assets/icons/square-dashed-mouse-pointer.svg")),
+ ("square-dot", include_bytes!("../../../assets/icons/square-dot.svg")),
+ ("square-plus", include_bytes!("../../../assets/icons/square-plus.svg")),
("squares-subtract", include_bytes!("../../../assets/icons/squares-subtract.svg")),
("stamp", include_bytes!("../../../assets/icons/stamp.svg")),
("sun", include_bytes!("../../../assets/icons/sun.svg")),
("swatch-book", include_bytes!("../../../assets/icons/swatch-book.svg")),
("text-cursor", include_bytes!("../../../assets/icons/text-cursor.svg")),
+ ("toggle-left", include_bytes!("../../../assets/icons/toggle-left.svg")),
+ ("toggle-right", include_bytes!("../../../assets/icons/toggle-right.svg")),
("trash", include_bytes!("../../../assets/icons/trash.svg")),
+ ("triangle", include_bytes!("../../../assets/icons/triangle.svg")),
("triangle-alert", include_bytes!("../../../assets/icons/triangle-alert.svg")),
("triangle-right", include_bytes!("../../../assets/icons/triangle-right.svg")),
- ("triangle", include_bytes!("../../../assets/icons/triangle.svg")),
("type", include_bytes!("../../../assets/icons/type.svg")),
("undo-2", include_bytes!("../../../assets/icons/undo-2.svg")),
("unlink", include_bytes!("../../../assets/icons/unlink.svg")),
- ("wand-sparkles", include_bytes!("../../../assets/icons/wand-sparkles.svg")),
("wand", include_bytes!("../../../assets/icons/wand.svg")),
+ ("wand-sparkles", include_bytes!("../../../assets/icons/wand-sparkles.svg")),
("x", include_bytes!("../../../assets/icons/x.svg")),
("zoom-in", include_bytes!("../../../assets/icons/zoom-in.svg")),
];
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index 2fa932488..7567f442e 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -50,10 +50,15 @@ pub fn tool_icon(t: Tool) -> &'static str {
Tool::Brush => "brush",
Tool::Eraser => "eraser",
Tool::Eyedropper => "pipette",
+ Tool::Ruler => "ruler",
+ Tool::Note => "message-square",
+ Tool::Count => "circle-dot",
Tool::Lasso => "lasso",
Tool::PolygonLasso => "pentagon",
Tool::MagicWand => "wand-sparkles",
Tool::Crop => "crop",
+ Tool::Slice => "slice-knife",
+ Tool::SliceSelect => "square-dashed-mouse-pointer",
Tool::Gradient => "blend",
Tool::PaintBucket => "paint-bucket",
Tool::Type => "type",
@@ -77,6 +82,7 @@ pub fn tool_icon(t: Tool) -> &'static str {
Tool::Triangle => "triangle",
Tool::Polygon => "pentagon",
Tool::Line => "slash",
+ Tool::CustomShape => "cloud",
}
}
diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs
new file mode 100644
index 000000000..75eb16acb
--- /dev/null
+++ b/crates/ui-egui/src/layer_menu_ui.rs
@@ -0,0 +1,132 @@
+//! Layers panel right-click menu in Photoshop's order. Items are command ids from the menu catalog;
+//! unavailable ones are greyed using the same enablement as the main menus. Items marked as menu
+//! invocations (`Value::Null` params) go through `menus::invoke`, so dialogs open like in the menu bar.
+
+use photocraft_doc::{Layer, LayerContent};
+use serde_json::{Value, json};
+
+/// One entry: label, command id. `None` = separator.
+pub type Entry = Option<(&'static str, &'static str)>;
+
+/// The context menu entries for a layer (Photoshop 2026 order, trimmed to the layer kind).
+pub fn entries(l: &Layer, multi: bool) -> Vec<Entry> {
+ let mut v: Vec<Entry> = vec![Some(("Blending Options…", "layer.layerStyle.blendingOptions"))];
+ v.push(None);
+ v.push(Some((if multi { "Duplicate Layers…" } else { "Duplicate Layer…" }, "layer.duplicate")));
+ v.push(Some((if multi { "Delete Layers" } else { "Delete Layer" }, "layer.delete")));
+ if !multi {
+ v.push(Some(("Group from Layers…", "layer.groupLayers")));
+ }
+ v.push(None);
+ v.push(Some(("Quick Export As PNG", "layer.quickExportAsPng")));
+ v.push(Some(("Export As…", "layer.exportAs")));
+ v.push(None);
+ v.push(Some(("Artboard from Layers…", "layer.new.artboardFromLayers")));
+ v.push(Some(("Frame from Layers…", "layer.new.frameFromLayers")));
+ v.push(None);
+ v.push(Some(("Convert to Smart Object", "layer.smartObjects.convertToSmartObject")));
+ match &l.content {
+ LayerContent::Text(_) => v.push(Some(("Rasterize Type", "layer.rasterize.type"))),
+ LayerContent::Shape(_) => v.push(Some(("Rasterize Layer", "layer.rasterize.shape"))),
+ LayerContent::Smart(_) => v.push(Some(("Rasterize Layer", "layer.rasterize.smartObject"))),
+ LayerContent::Fill(_) => v.push(Some(("Rasterize Layer", "layer.rasterize.fillContent"))),
+ _ => v.push(Some(("Rasterize Layer", "layer.rasterize.layer"))),
+ }
+ v.push(None);
+ if l.mask.is_some() {
+ v.push(Some(("Disable Layer Mask", "layer.layerMask.enabled")));
+ v.push(Some(("Apply Layer Mask", "layer.layerMask.apply")));
+ v.push(Some(("Delete Layer Mask", "layer.layerMask.delete")));
+ } else {
+ v.push(Some(("Add Layer Mask", "layer.layerMask.revealAll")));
+ }
+ v.push(Some((if l.clipped { "Release Clipping Mask" } else { "Create Clipping Mask" }, if l.clipped { "layer.releaseClippingMask" } else { "layer.createClippingMask" })));
+ v.push(None);
+ v.push(Some(("Link Layers", "layer.linkLayers")));
+ v.push(Some(("Select Linked Layers", "layer.selectLinkedLayers")));
+ v.push(None);
+ v.push(Some(("Copy Layer Style", "layer.layerStyle.copyLayerStyle")));
+ v.push(Some(("Paste Layer Style", "layer.layerStyle.pasteLayerStyle")));
+ v.push(Some(("Clear Layer Style", "layer.layerStyle.clear")));
+ v.push(None);
+ if multi {
+ v.push(Some(("Merge Layers", "layer.mergeLayers")));
+ } else {
+ v.push(Some(("Merge Down", "layer.mergeDown")));
+ }
+ v.push(Some(("Merge Visible", "layer.mergeVisible")));
+ v.push(Some(("Flatten Image", "layer.flattenImage")));
+ v
+}
+
+/// Render the menu. Pushes `(command, params)` actions; `Value::Null` params mean "invoke like the
+/// menu item" (opens the command's dialog when it has one).
+pub fn show(app: &crate::PhotocraftApp, ui: &mut egui::Ui, l: &Layer, on_set: bool, actions: &mut Vec<(String, Value)>) -> bool {
+ ui.set_min_width(220.0);
+ let mut rename = false;
+ let mut last_sep = true;
+ for e in entries(l, on_set) {
+ match e {
+ None => {
+ if !last_sep {
+ ui.separator();
+ }
+ last_sep = true;
+ }
+ Some((label, id)) => {
+ // Skip commands this build doesn't have rather than showing dead items.
+ if photocraft_engine::commands::find(id).is_none() && !crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) {
+ continue;
+ }
+ last_sep = false;
+ // Enablement is exact for the active layer (or the selection); another row is
+ // selected first when clicked, so its items stay available.
+ let is_active = app.session.active().is_some_and(|s| s.active_layer == Some(l.id));
+ let enabled = if on_set || is_active { crate::menus::is_enabled(app, id) } else { true };
+ if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
+ if !on_set {
+ actions.push(("layer.select".into(), json!({"layer": l.id.0})));
+ }
+ actions.push((id.into(), Value::Null));
+ ui.close();
+ }
+ }
+ }
+ }
+ ui.separator();
+ if ui.button("Rename Layer…").clicked() {
+ rename = true;
+ ui.close();
+ }
+ rename
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn entries_follow_layer_state() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 10, "height": 10})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let st = s.active().unwrap();
+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone();
+ let ids: Vec<&str> = entries(&l, false).into_iter().flatten().map(|e| e.1).collect();
+ assert_eq!(ids.first(), Some(&"layer.layerStyle.blendingOptions"));
+ assert!(ids.contains(&"layer.mergeDown") && !ids.contains(&"layer.mergeLayers"));
+ assert!(ids.contains(&"layer.layerMask.revealAll"));
+ let ids: Vec<&str> = entries(&l, true).into_iter().flatten().map(|e| e.1).collect();
+ assert!(ids.contains(&"layer.mergeLayers"));
+ }
+
+ #[test]
+ fn every_entry_is_a_known_command() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 10, "height": 10})).unwrap();
+ let l = s.active().unwrap().doc.layers[0].clone();
+ for (_, id) in entries(&l, false).into_iter().flatten() {
+ assert!(crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) || photocraft_engine::commands::find(id).is_some(), "{id}");
+ }
+ }
+}
diff --git a/crates/ui-egui/src/layer_props_ui.rs b/crates/ui-egui/src/layer_props_ui.rs
new file mode 100644
index 000000000..acb53c38b
--- /dev/null
+++ b/crates/ui-egui/src/layer_props_ui.rs
@@ -0,0 +1,211 @@
+//! Properties panel for pixel (and other bounded) layers, Photoshop 2026 style: a Transform section
+//! (W/H/X/Y of the layer content, editable), Align and Distribute, and Quick Actions. Edits dispatch
+//! `edit.transform`, `layer.translate`, `layer.align.*` and selection commands.
+
+use egui::{Rect, Sense, Stroke, pos2, vec2};
+use photocraft_doc::Layer;
+use serde_json::{Value, json};
+
+use crate::theme::Tokens;
+use crate::{PhotocraftApp, widgets};
+
+/// `edit.transform` params that scale the content box `b` = [x0, y0, x1, y1] to `w` x `h`, keeping
+/// the top-left corner (Photoshop's Properties W/H fields), or `layer.translate` params for X/Y.
+pub fn transform_params(layer: u64, b: [i32; 4], w: Option<f32>, h: Option<f32>, linked: bool) -> Option<Value> {
+ let (bw, bh) = ((b[2] - b[0]) as f32, (b[3] - b[1]) as f32);
+ if bw <= 0.0 || bh <= 0.0 {
+ return None;
+ }
+ let (mut nw, mut nh) = (w.unwrap_or(bw).max(1.0), h.unwrap_or(bh).max(1.0));
+ if linked {
+ if w.is_some() {
+ nh = (nw * bh / bw).max(1.0);
+ } else if h.is_some() {
+ nw = (nh * bw / bh).max(1.0);
+ }
+ }
+ if (nw - bw).abs() < 0.5 && (nh - bh).abs() < 0.5 {
+ return None;
+ }
+ let (x0, y0) = (b[0] as f32, b[1] as f32);
+ let quad = [[x0, y0], [x0 + nw, y0], [x0 + nw, y0 + nh], [x0, y0 + nh]];
+ Some(json!({"layer": layer, "rect": b, "quad": quad}))
+}
+
+fn section(ui: &mut egui::Ui, id: &str, title: &str) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let key = egui::Id::new(("layer-props-section", id));
+ let mut open = ui.data(|d| d.get_temp::<bool>(key)).unwrap_or(true);
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
+ crate::icons::paint(ui, Rect::from_center_size(pos2(r.left() + 7.0, r.center().y), vec2(12.0, 12.0)), if open { "chevron-down" } else { "chevron-right" }, 11.0, t.text_dim);
+ ui.painter().text(pos2(r.left() + 18.0, r.center().y), egui::Align2::LEFT_CENTER, title, crate::theme::semibold(12.0), t.text);
+ if resp.clicked() {
+ open = !open;
+ ui.data_mut(|d| d.insert_temp(key, open));
+ }
+ open
+}
+
+/// A number field that reports a value once committed (drag released, Enter, focus lost).
+fn field(ui: &mut egui::Ui, id: &str, label: &str, current: f32) -> Option<f32> {
+ let t = Tokens::get(ui.ctx());
+ let (r, _) = ui.allocate_exact_size(vec2(16.0, 22.0), Sense::hover());
+ ui.painter().text(pos2(r.right() - 2.0, r.center().y), egui::Align2::RIGHT_CENTER, label, egui::FontId::proportional(12.0), t.text_dim);
+ let key = egui::Id::new(("layer-props-field", id));
+ let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);
+ let resp = widgets::value_field(ui, &mut v, -300_000.0..=300_000.0, "px", 80.0);
+ if resp.dragged() || resp.has_focus() {
+ ui.data_mut(|d| d.insert_temp(key, v));
+ return None;
+ }
+ ui.data_mut(|d| d.remove::<f32>(key));
+ (resp.drag_stopped() || resp.lost_focus() || resp.changed()).then_some(v).filter(|v| (*v - current).abs() >= 0.5)
+}
+
+/// Align glyph: a reference line and two bars (Photoshop's align icons).
+fn align_glyph(ui: &egui::Ui, r: Rect, kind: &str, color: egui::Color32) {
+ let p = ui.painter();
+ let c = r.center();
+ let s = Stroke::new(1.2, color);
+ let vertical_ref = matches!(kind, "leftEdges" | "horizontalCenters" | "rightEdges");
+ if vertical_ref {
+ let x = match kind {
+ "leftEdges" => c.x - 6.0,
+ "rightEdges" => c.x + 6.0,
+ _ => c.x,
+ };
+ p.line_segment([pos2(x, c.y - 7.0), pos2(x, c.y + 7.0)], s);
+ for (dy, w) in [(-3.0, 10.0), (3.0, 6.0)] {
+ let x0 = match kind {
+ "leftEdges" => x,
+ "rightEdges" => x - w,
+ _ => x - w / 2.0,
+ };
+ p.rect_filled(Rect::from_min_size(pos2(x0, c.y + dy - 1.5), vec2(w, 3.0)), 0.0, color);
+ }
+ } else {
+ let y = match kind {
+ "topEdges" => c.y - 6.0,
+ "bottomEdges" => c.y + 6.0,
+ _ => c.y,
+ };
+ p.line_segment([pos2(c.x - 7.0, y), pos2(c.x + 7.0, y)], s);
+ for (dx, h) in [(-3.0, 10.0), (3.0, 6.0)] {
+ let y0 = match kind {
+ "topEdges" => y,
+ "bottomEdges" => y - h,
+ _ => y - h / 2.0,
+ };
+ p.rect_filled(Rect::from_min_size(pos2(c.x + dx - 1.5, y0), vec2(3.0, h)), 0.0, color);
+ }
+ }
+}
+
+/// Pro Properties body for a non-adjustment layer.
+pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {
+ let t = Tokens::get(ui.ctx());
+ let mut run: Vec<(String, Value)> = Vec::new();
+ if let Some(s) = layer.surface() {
+ let b = app.cached_bounds(layer.id.0, s);
+ if section(ui, "transform", "Transform") {
+ let link_key = egui::Id::new("layer-props-link");
+ let linked = ui.data(|d| d.get_temp::<bool>(link_key)).unwrap_or(true);
+ let bb = [b.x0, b.y0, b.x1, b.y1];
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if let Some(v) = field(ui, "w", "W", b.width() as f32) {
+ run.extend(transform_params(layer.id.0, bb, Some(v), None, linked).map(|p| ("edit.transform".to_string(), p)));
+ }
+ if crate::icons::button(ui, if linked { "link" } else { "unlink" }, 20.0, linked, "Link width and height").clicked() {
+ ui.data_mut(|d| d.insert_temp(link_key, !linked));
+ }
+ if let Some(v) = field(ui, "h", "H", b.height() as f32) {
+ run.extend(transform_params(layer.id.0, bb, None, Some(v), linked).map(|p| ("edit.transform".to_string(), p)));
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if let Some(v) = field(ui, "x", "X", b.x0 as f32) {
+ run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": (v - b.x0 as f32).round() as i32, "dy": 0})));
+ }
+ ui.add_space(24.0);
+ if let Some(v) = field(ui, "y", "Y", b.y0 as f32) {
+ run.push(("layer.translate".into(), json!({"layer": layer.id.0, "dx": 0, "dy": (v - b.y0 as f32).round() as i32})));
+ }
+ });
+ ui.add_space(4.0);
+ }
+ widgets::hairline(ui);
+ ui.add_space(2.0);
+ }
+ if section(ui, "align", "Align and Distribute") {
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ for (i, kind) in ["leftEdges", "horizontalCenters", "rightEdges", "topEdges", "verticalCenters", "bottomEdges"].into_iter().enumerate() {
+ if i == 3 {
+ ui.add_space(8.0);
+ }
+ let id = format!("layer.align.{kind}");
+ let on = app.session.is_enabled(&id);
+ let label = photocraft_engine::commands::find(&id).map_or(kind, |c| c.label);
+ let (r, resp) = ui.allocate_exact_size(vec2(24.0, 24.0), if on { Sense::click() } else { Sense::hover() });
+ if resp.hovered() && on {
+ ui.painter().rect_filled(r, t.radius_sm, t.hover);
+ }
+ align_glyph(ui, r, kind, if on { t.icon } else { t.text_faint });
+ if resp.on_hover_text(format!("Align {label}")).clicked() {
+ run.push((id, json!({})));
+ }
+ }
+ });
+ ui.add_space(4.0);
+ }
+ widgets::hairline(ui);
+ ui.add_space(2.0);
+ if section(ui, "quick", "Quick Actions") {
+ ui.horizontal(|ui| {
+ for (label, id) in [("Remove Background", "layer.removeBackground"), ("Select Subject", "select.subject")] {
+ if photocraft_engine::commands::find(id).is_some() && widgets::secondary_button(ui, label, 0.0).clicked() {
+ run.push((id.to_string(), json!({})));
+ }
+ }
+ });
+ }
+ for (id, p) in run {
+ if let Err(e) = app.run(&id, p) {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn width_edit_scales_from_the_top_left() {
+ let p = transform_params(7, [10, 20, 110, 70], Some(200.0), None, true).unwrap();
+ assert_eq!(p["layer"], 7);
+ assert_eq!(p["quad"], json!([[10.0, 20.0], [210.0, 20.0], [210.0, 120.0], [10.0, 120.0]]));
+ let p = transform_params(7, [10, 20, 110, 70], None, Some(25.0), false).unwrap();
+ assert_eq!(p["quad"][2], json!([110.0, 45.0]));
+ assert!(transform_params(7, [10, 20, 110, 70], Some(100.0), None, true).is_none());
+ assert!(transform_params(7, [0, 0, 0, 0], Some(5.0), None, true).is_none());
+ }
+
+ #[test]
+ fn transform_params_resize_a_layer_in_the_engine() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 20, "width": 100, "height": 50})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ let p = transform_params(id.0, [10, 20, 110, 70], Some(50.0), None, true).unwrap();
+ s.execute("edit.transform", p).unwrap();
+ let b = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds();
+ assert_eq!((b.x0, b.y0, b.width(), b.height()), (10, 20, 50, 25));
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index b6d1fc90e..40de3cf4a 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -8,22 +8,32 @@
pub mod actions;
pub mod adjust_ui;
+pub mod analysis_ui;
+pub mod file_ui;
+pub mod slice_ui;
pub mod artboard_ui;
pub mod brush_panel;
pub mod canvas;
pub mod channel_view;
pub mod channels_panel;
+pub mod chrome_ui;
+pub mod color_picker_ui;
pub mod comps_ui;
pub mod control;
pub mod dialogs;
+pub mod doc_props_ui;
+pub mod enable_rules;
pub mod export_dialog;
pub mod gpu_canvas;
pub mod filter_dialog;
pub mod icons;
+pub mod layer_menu_ui;
+pub mod layer_props_ui;
pub mod layer_style;
pub mod links;
pub mod menu_catalog;
pub mod menus;
+pub mod new_doc_ui;
pub mod outline;
pub mod palette;
pub mod proxy;
@@ -34,6 +44,8 @@ pub mod panels;
pub mod parity;
pub mod shortcuts;
pub mod prefs_ui;
+pub mod preset_panels;
+pub mod type_panels_ui;
pub mod snap_ui;
mod sizing;
pub mod state;
@@ -41,6 +53,9 @@ pub mod theme;
pub mod tone;
pub mod transform_tool;
pub mod distort_ui;
+pub mod camera_raw_ui;
+pub mod wide_angle_ui;
+pub mod gallery_ui;
pub mod liquify_ui;
pub mod puppet_ui;
pub mod perspective_ui;
@@ -48,6 +63,7 @@ pub mod type_tool;
pub mod vector_ui;
pub mod view_cmds;
pub mod widgets;
+pub mod workspace_ui;
mod icon_data;
use std::collections::HashMap;
@@ -171,6 +187,10 @@ pub struct PhotocraftApp {
pub(crate) transform_preview: Option<transform_tool::TransformPreview>,
/// Liquify dialog, Puppet Warp and Perspective Warp sessions (distort_ui).
pub(crate) distort: distort_ui::Distort,
+ /// Filter › Camera Raw Filter dialog (camera_raw_ui).
+ pub(crate) camera_raw: Option<camera_raw_ui::CameraRawDialog>,
+ /// Filter › Adaptive Wide Angle dialog (wide_angle_ui).
+ pub(crate) wide_angle: Option<wide_angle_ui::WideAngleDialog>,
/// Signature of the image we last put on the OS clipboard (to tell ours from other apps').
os_clip_sig: Option<u64>,
/// Pointer position over the canvas (document px), for the Info panel and status bar.
@@ -234,6 +254,8 @@ impl PhotocraftApp {
os_clip_sig: None,
transform_preview: None,
distort: Default::default(),
+ camera_raw: None,
+ wide_angle: None,
tone_hist: None,
doc_hist: None,
gpu: None,
@@ -244,6 +266,8 @@ impl PhotocraftApp {
};
// Saved preferences (and recovered documents) are in place before the first frame.
prefs_ui::load(&mut app);
+ // File › Scripts › Script Events Manager: "Start Application".
+ photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication");
app
}
@@ -304,6 +328,9 @@ impl PhotocraftApp {
let (_, color) = self.session.open_document(doc, Some(name.to_string()));
self.sync_views();
self.ui.status = format!("Opened {name}");
+ // Script events bound to "Open Document".
+ photocraft_engine::automate_cmds::document_opened(&mut self.session);
+ self.sync_views();
let ask = color.get("ask").and_then(Value::as_bool) == Some(true);
if ask && (color.get("mismatch").and_then(Value::as_bool) == Some(true) || color.get("missing").is_some()) {
prefs_ui::open_mismatch(self, &color);
@@ -341,6 +368,13 @@ impl PhotocraftApp {
st.saved_revision = st.revision;
}
self.ui.status = format!("Saved {path}");
+ // "Save Document" script events and File › Generate › Image Assets.
+ if let Some(i) = self.session.active_index()
+ && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut self.session, i)
+ {
+ self.ui.status = format!("Saved {path}; {} image assets in {}", r["files"].as_array().map_or(0, Vec::len), r["dir"].as_str().unwrap_or(""));
+ }
+ self.sync_views();
Ok(path)
}
@@ -507,9 +541,15 @@ impl eframe::App for PhotocraftApp {
});
panels::properties_window(self, &ctx);
brush_panel::window(self, &ctx);
+ preset_panels::windows(self, &ctx);
+ type_panels_ui::windows(self, &ctx);
+ analysis_ui::windows(self, &ctx);
+ workspace_ui::windows(self, &ctx);
palette::show(self, &ctx);
dialogs::show(self, &ctx);
distort_ui::show(self, &ctx);
+ camera_raw_ui::show(self, &ctx);
+ wide_angle_ui::show(self, &ctx);
canvas::extra_windows(self, &ctx);
self.perf.frame(gpu_canvas::now_ms() - t0);
// Synthetic input is injected one press/release step per frame: keep frames coming until
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 87b13cde8..6341c6d6a 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -103,6 +103,22 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
if id == "view.proofSetup.custom" {
return Ok(json!({"dialog": crate::filter_dialog::open(app, "view.proofSetup")}));
}
+ // Image › Analysis tools/dialogs, Measurement Log and Notes panels, File › Import › Notes.
+ if let Some(r) = crate::analysis_ui::menu(app, id, &params) {
+ return r;
+ }
+ // Workspace New/Delete/Lock, Modifier Keys, custom pixel aspect, Extras/32-bit options.
+ if let Some(r) = crate::workspace_ui::menu(app, id, &params) {
+ return r;
+ }
+ // Window › Gradients, Patterns, Styles, Shapes, Tool Presets, Clone Source.
+ if let Some(r) = crate::preset_panels::menu(app, id, &params) {
+ return r;
+ }
+ // Character/Paragraph Styles, Glyphs, Edit › Check Spelling dialog.
+ if let Some(r) = crate::type_panels_ui::menu(app, id, &params) {
+ return r;
+ }
if id == "window.panel.brushes" {
// Window › Brushes opens the Brush Settings window on its presets tab.
app.ui.panels.brush_settings = true;
@@ -117,6 +133,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, &params) {
return r;
}
+ // Save for Web, Print and the other File-menu dialogs added with slices.
+ if let Some(r) = crate::file_ui::invoke(app, ctx, id, &params) {
+ return r;
+ }
if let Some(r) = crate::view_cmds::invoke(app, ctx, id, &params) {
return r;
}
@@ -124,6 +144,13 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
if let Some(r) = crate::distort_ui::menu(app, ctx, id, &params) {
return r;
}
+ // Camera Raw Filter dialog (and its control params).
+ if let Some(r) = crate::camera_raw_ui::menu(app, ctx, id, &params) {
+ return r;
+ }
+ if let Some(r) = crate::wide_angle_ui::menu(app, ctx, id, &params) {
+ return r;
+ }
if let Some(profile) = proof_preset(id) {
// View › Proof Setup presets: set the proof profile and turn Proof Colors on.
app.run("view.proofSetup", json!({"profile": profile}))?;
@@ -220,6 +247,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
}
// Photoshop's "Select and Mask…" is the engine's select.refineEdge.
"select.selectAndMask" => Ok(json!({"dialog": crate::filter_dialog::open(app, "select.refineEdge")})),
+ // Select › Transform Selection from the menu: the interactive box (with params: the engine).
+ "select.transformSelection" if params.as_object().is_none_or(|o| o.is_empty()) => {
+ crate::transform_tool::begin_selection(app, ctx).map(|_| json!({"transform": app.ui.transform}))
+ }
"edit.paste" if params.as_object().is_none_or(|o| o.is_empty()) => {
// Photoshop: paste in place when the copied area is visible, else centred in the view;
// images from other apps are always centred.
@@ -319,6 +350,19 @@ fn open_path(_app: &mut PhotocraftApp, path: &str) -> Result<Value, String> {
}
pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
+ // Photoshop greys these for the Background layer, other layer kinds or single-layer documents.
+ if crate::enable_rules::disabled(app, id) {
+ return false;
+ }
+ if let Some(e) = crate::workspace_ui::is_enabled(app, id) {
+ return e;
+ }
+ if crate::analysis_ui::handles(id) {
+ return true;
+ }
+ if crate::preset_panels::handles(id) || crate::type_panels_ui::handles(id) {
+ return true;
+ }
if let Some(e) = crate::view_cmds::is_enabled(app, id) {
return e;
}
@@ -334,6 +378,7 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
"view.proofSetup.custom" => app.session.active().is_some(),
"view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => true,
"select.selectAndMask" => app.session.is_enabled("select.refineEdge"),
+ "select.transformSelection" => app.ui.transform.is_none() && app.session.is_enabled("select.transformSelection"),
i if (i.starts_with("view.zoom") || i == "view.fitOnScreen" || i == "view.actualPixels") || i == "window.newWindowForDocument" => app.session.active().is_some(),
"edit.freeTransform" | "edit.transform.scale" | "edit.transform.rotate" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective" => {
app.ui.transform.is_none() && app.session.active().and_then(|s| s.active_layer).is_some()
@@ -348,9 +393,21 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
if let Some(c) = crate::view_cmds::checked(app, id) {
return Some(c);
}
+ if let Some(c) = crate::analysis_ui::checked(app, id).or_else(|| crate::workspace_ui::checked(app, id)).or_else(|| crate::file_ui::checked(app, id)) {
+ return Some(c);
+ }
+ if let Some(c) = crate::preset_panels::checked(app, id) {
+ return Some(c);
+ }
+ if let Some(c) = crate::type_panels_ui::checked(app, id) {
+ return Some(c);
+ }
if let Some(alias) = panel_alias(id) {
return checked(app, alias);
}
+ if id == "select.isolateLayers" {
+ return Some(!app.session.active()?.isolated_layers.is_empty());
+ }
if id == "view.proofColors" || id == "view.gamutWarning" {
let d = app.session.active()?;
let pv = app.session.color.proof(d.doc.id);
@@ -367,6 +424,10 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
"grayscale" => Some(d.mode == ColorMode::Grayscale),
"cmyk" => Some(d.mode == ColorMode::Cmyk),
"lab" => Some(d.mode == ColorMode::Lab),
+ "multichannel" => Some(d.mode == ColorMode::Multichannel),
+ "indexedColor" => Some(d.mode == ColorMode::Indexed),
+ "bitmap" => Some(d.mode == ColorMode::Bitmap),
+ "duotone" => Some(d.mode == ColorMode::Duotone),
"bits8" => Some(d.depth == SampleType::U8),
"bits16" => Some(d.depth == SampleType::U16),
"bits32" => Some(d.depth == SampleType::F32),
@@ -413,7 +474,7 @@ pub struct MenuItem {
/// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and
/// the parity report ([`crate::parity`]).
pub fn is_live(id: &str) -> bool {
- photocraft_engine::commands::find(id).is_some() || UI_COMMANDS.iter().any(|c| c.0 == id) || panel_alias(id).is_some() || workspace_name(id).is_some() || proof_preset(id).is_some() || id == "view.proofSetup.custom" || crate::view_cmds::handles(id)
+ photocraft_engine::commands::find(id).is_some() || UI_COMMANDS.iter().any(|c| c.0 == id) || panel_alias(id).is_some() || workspace_name(id).is_some() || proof_preset(id).is_some() || id == "view.proofSetup.custom" || crate::view_cmds::handles(id) || crate::analysis_ui::handles(id) || crate::workspace_ui::handles(id) || crate::preset_panels::handles(id) || crate::type_panels_ui::handles(id)
}
pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
@@ -575,6 +636,10 @@ fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &
/// Workspace presets (Window → Workspace): which panels are visible.
pub fn apply_workspace(app: &mut PhotocraftApp) {
+ // Saved workspaces (Window › Workspace › New Workspace…) restore their own layout.
+ if crate::workspace_ui::apply_custom(app) {
+ return;
+ }
let p = &mut app.ui.panels;
let (nav, color, layers, history, props) = match app.ui.workspace.as_str() {
"Photography" => (true, false, true, true, true),
diff --git a/crates/ui-egui/src/new_doc_ui.rs b/crates/ui-egui/src/new_doc_ui.rs
new file mode 100644
index 000000000..b646c4db5
--- /dev/null
+++ b/crates/ui-egui/src/new_doc_ui.rs
@@ -0,0 +1,241 @@
+//! File › New: Photoshop's New Document dialog. Category tabs with blank-document presets on the
+//! left, Preset Details on the right. Values live in the dialog fields (`width`/`height` in pixels,
+//! `resolution` in ppi, `mode`, `depth`, `background`, `name`), so `ui.dialog.set` drives it and
+//! Create runs `file.new` with them.
+
+use egui::{Align2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2};
+use serde_json::{Map, Value, json};
+
+use crate::theme::Tokens;
+use crate::{icons, widgets};
+
+/// A blank-document preset: (name, width px, height px, ppi).
+pub type Preset = (&'static str, u32, u32, f32);
+
+/// Photoshop's New Document categories and their blank-document presets.
+pub const CATEGORIES: &[(&str, &[Preset])] = &[
+ ("Recent", &[("Default Photoshop Size", 2100, 1500, 300.0), ("HDTV 1080p", 1920, 1080, 72.0)]),
+ ("Photo", &[("Landscape, 6 x 4", 1800, 1200, 300.0), ("Landscape, 7 x 5", 2100, 1500, 300.0), ("Landscape, 10 x 8", 3000, 2400, 300.0), ("Portrait, 4 x 6", 1200, 1800, 300.0), ("Portrait, 5 x 7", 1500, 2100, 300.0), ("Square, 5 x 5", 1500, 1500, 300.0)]),
+ ("Print", &[("Letter", 2550, 3300, 300.0), ("Legal", 2550, 4200, 300.0), ("Tabloid", 3300, 5100, 300.0), ("A4", 2480, 3508, 300.0), ("A3", 3508, 4961, 300.0), ("A5", 1748, 2480, 300.0)]),
+ ("Art & Illustration", &[("Poster", 5400, 7200, 300.0), ("Postcard", 1800, 1200, 300.0), ("Comic Book", 1988, 3075, 300.0), ("Square, 12 x 12", 3600, 3600, 300.0)]),
+ ("Web", &[("Web Most Common", 1366, 768, 72.0), ("Web Minimum", 1024, 768, 72.0), ("Web Large", 1920, 1080, 72.0), ("MacBook Pro 16\"", 3456, 2234, 72.0), ("iMac 24\"", 4480, 2520, 72.0)]),
+ ("Mobile", &[("iPhone 16", 1179, 2556, 72.0), ("iPhone 16 Pro Max", 1320, 2868, 72.0), ("iPad Pro 13\"", 2064, 2752, 72.0), ("Android 1080p", 1080, 1920, 72.0), ("Apple Watch 45mm", 396, 484, 72.0)]),
+ ("Film & Video", &[("HDTV 1080p", 1920, 1080, 72.0), ("HDTV 720p", 1280, 720, 72.0), ("UHD 4K", 3840, 2160, 72.0), ("DCI 4K", 4096, 2160, 72.0), ("UHD 8K", 7680, 4320, 72.0)]),
+];
+
+/// Width/Height units: (key, label, units per inch; 0 = pixels).
+pub const UNITS: &[(&str, &str, f32)] = &[("px", "Pixels", 0.0), ("in", "Inches", 1.0), ("cm", "Centimeters", 2.54), ("mm", "Millimeters", 25.4), ("pt", "Points", 72.0), ("pica", "Picas", 6.0)];
+
+/// Pixels to the display unit at `ppi`.
+pub fn to_unit(px: f32, unit: &str, ppi: f32) -> f32 {
+ match UNITS.iter().find(|u| u.0 == unit) {
+ Some((_, _, per_in)) if *per_in > 0.0 => px / ppi.max(1.0) * per_in,
+ _ => px,
+ }
+}
+
+/// Display unit back to pixels at `ppi`.
+pub fn from_unit(v: f32, unit: &str, ppi: f32) -> f32 {
+ match UNITS.iter().find(|u| u.0 == unit) {
+ Some((_, _, per_in)) if *per_in > 0.0 => (v / per_in * ppi.max(1.0)).round(),
+ _ => v.round(),
+ }
+}
+
+/// Apply a preset to the dialog fields.
+pub fn apply_preset(f: &mut Map<String, Value>, p: &Preset) {
+ f.insert("width".into(), json!(p.1));
+ f.insert("height".into(), json!(p.2));
+ f.insert("resolution".into(), json!(p.3));
+ f.insert("__preset".into(), json!(p.0));
+ // Print and photo presets are specified in inches, screen presets in pixels.
+ f.insert("__unit".into(), json!(if p.3 >= 300.0 { "in" } else { "px" }));
+}
+
+/// Fields `file.new` takes (drops the dialog's `__` UI keys).
+pub fn command_params(f: &Map<String, Value>) -> Value {
+ Value::Object(f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect())
+}
+
+fn get_f(f: &Map<String, Value>, k: &str, d: f32) -> f32 {
+ f.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32)
+}
+
+fn get_s(f: &Map<String, Value>, k: &str, d: &str) -> String {
+ f.get(k).and_then(Value::as_str).unwrap_or(d).to_string()
+}
+
+fn small_label(ui: &mut egui::Ui, s: &str) {
+ let t = Tokens::get(ui.ctx());
+ ui.label(RichText::new(s).size(11.5).color(t.text_dim));
+}
+
+/// Paint a page thumbnail with the preset's aspect ratio.
+fn page_icon(ui: &egui::Ui, r: Rect, w: u32, h: u32, t: &Tokens) {
+ let s = 30.0 / (w.max(h) as f32);
+ let page = Rect::from_center_size(r.center(), vec2(w as f32 * s, h as f32 * s));
+ ui.painter().rect_stroke(page, 1.0, Stroke::new(1.2, t.text_dim), StrokeKind::Inside);
+}
+
+pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ let t = Tokens::get(ui.ctx());
+ let cat = get_s(f, "__category", "Recent");
+ // Category tabs.
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 18.0;
+ for (name, _) in CATEGORIES {
+ let on = cat == *name;
+ let r = ui.add(egui::Label::new(RichText::new(*name).size(13.0).color(if on { t.text } else { t.text_dim })).sense(Sense::click()));
+ if on {
+ ui.painter().line_segment([r.rect.left_bottom() + vec2(0.0, 3.0), r.rect.right_bottom() + vec2(0.0, 3.0)], Stroke::new(2.0, t.text));
+ }
+ if r.clicked() {
+ f.insert("__category".into(), json!(name));
+ }
+ }
+ });
+ ui.add_space(6.0);
+ widgets::hairline(ui);
+ ui.add_space(8.0);
+ let presets = CATEGORIES.iter().find(|c| c.0 == cat).map_or(CATEGORIES[0].1, |c| c.1);
+ let chosen = get_s(f, "__preset", "");
+ ui.horizontal_top(|ui| {
+ // Left: preset grid.
+ ui.vertical(|ui| {
+ ui.set_width(520.0);
+ ui.label(RichText::new(format!("BLANK DOCUMENT PRESETS ({})", presets.len())).size(11.0).color(t.text_faint));
+ ui.add_space(6.0);
+ let card = vec2(164.0, 112.0);
+ for row in presets.chunks(3) {
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 8.0;
+ for p in row {
+ let (r, resp) = ui.allocate_exact_size(card, Sense::click());
+ let on = chosen == p.0;
+ ui.painter().rect_filled(r, t.radius, if on { t.row_selected } else if resp.hovered() { t.hover } else { t.field });
+ if on {
+ ui.painter().rect_stroke(r, t.radius, Stroke::new(1.5, t.accent), StrokeKind::Inside);
+ }
+ page_icon(ui, Rect::from_center_size(pos2(r.center().x, r.top() + 34.0), vec2(40.0, 40.0)), p.1, p.2, &t);
+ ui.painter().text(pos2(r.center().x, r.top() + 72.0), Align2::CENTER_CENTER, p.0, egui::FontId::proportional(12.0), t.text);
+ let unit = if p.3 >= 300.0 { "in" } else { "px" };
+ let size = if unit == "in" {
+ format!("{} x {} in @ {} ppi", widgets::fmt_num(to_unit(p.1 as f32, "in", p.3) as f64), widgets::fmt_num(to_unit(p.2 as f32, "in", p.3) as f64), p.3)
+ } else {
+ format!("{} x {} px @ {} ppi", p.1, p.2, p.3)
+ };
+ ui.painter().text(pos2(r.center().x, r.top() + 90.0), Align2::CENTER_CENTER, size, egui::FontId::proportional(10.5), t.text_faint);
+ if resp.clicked() {
+ apply_preset(f, p);
+ }
+ }
+ });
+ ui.add_space(8.0);
+ }
+ });
+ ui.add_space(10.0);
+ // Right: Preset Details.
+ ui.vertical(|ui| {
+ ui.set_width(260.0);
+ ui.label(RichText::new("PRESET DETAILS").size(11.0).color(t.text_faint));
+ ui.add_space(4.0);
+ let mut name = get_s(f, "name", "Untitled-1");
+ if ui.add(egui::TextEdit::singleline(&mut name).desired_width(250.0).font(egui::FontId::proportional(15.0))).changed() {
+ f.insert("name".into(), json!(name));
+ }
+ ui.add_space(8.0);
+ let ppi = get_f(f, "resolution", 72.0);
+ let mut unit = get_s(f, "__unit", "px");
+ small_label(ui, "Width");
+ ui.horizontal(|ui| {
+ let mut w = to_unit(get_f(f, "width", 1920.0), &unit, ppi);
+ if widgets::value_field(ui, &mut w, 0.01..=300_000.0, "", 110.0).changed() {
+ f.insert("width".into(), json!(from_unit(w, &unit, ppi).max(1.0)));
+ f.remove("__preset");
+ }
+ let opts: Vec<(String, &str)> = UNITS.iter().map(|u| (u.0.to_string(), u.1)).collect();
+ if widgets::dropdown(ui, "nd-unit", &mut unit, &opts, 120.0) {
+ f.insert("__unit".into(), json!(unit));
+ }
+ });
+ small_label(ui, "Height");
+ ui.horizontal(|ui| {
+ let mut h = to_unit(get_f(f, "height", 1080.0), &unit, ppi);
+ if widgets::value_field(ui, &mut h, 0.01..=300_000.0, "", 110.0).changed() {
+ f.insert("height".into(), json!(from_unit(h, &unit, ppi).max(1.0)));
+ f.remove("__preset");
+ }
+ ui.add_space(6.0);
+ small_label(ui, "Orientation");
+ let (w, h) = (get_f(f, "width", 1920.0), get_f(f, "height", 1080.0));
+ for (icon, portrait) in [("rectangle-vertical", true), ("rectangle-horizontal", false)] {
+ if icons::button(ui, icon, 24.0, (h > w) == portrait, if portrait { "Portrait" } else { "Landscape" }).clicked() && (h > w) != portrait {
+ f.insert("width".into(), json!(h));
+ f.insert("height".into(), json!(w));
+ }
+ }
+ });
+ ui.add_space(4.0);
+ small_label(ui, "Resolution");
+ ui.horizontal(|ui| {
+ let per_cm = get_s(f, "__resUnit", "in") == "cm";
+ let mut r = if per_cm { ppi / 2.54 } else { ppi };
+ if widgets::value_field(ui, &mut r, 1.0..=30_000.0, "", 110.0).changed() {
+ f.insert("resolution".into(), json!(if per_cm { r * 2.54 } else { r }));
+ }
+ let mut ru = get_s(f, "__resUnit", "in");
+ if widgets::dropdown(ui, "nd-resunit", &mut ru, &[("in".to_string(), "Pixels/Inch"), ("cm".to_string(), "Pixels/Centimeter")], 120.0) {
+ f.insert("__resUnit".into(), json!(ru));
+ }
+ });
+ ui.add_space(4.0);
+ small_label(ui, "Color Mode");
+ ui.horizontal(|ui| {
+ let mut mode = get_s(f, "mode", "rgb");
+ if widgets::dropdown(ui, "nd-mode", &mut mode, &[("gray".to_string(), "Grayscale"), ("rgb".to_string(), "RGB Color"), ("cmyk".to_string(), "CMYK Color"), ("lab".to_string(), "Lab Color")], 110.0) {
+ f.insert("mode".into(), json!(mode));
+ }
+ let mut depth = f.get("depth").and_then(Value::as_u64).unwrap_or(8);
+ if widgets::dropdown(ui, "nd-depth", &mut depth, &[(8u64, "8 bit"), (16, "16 bit"), (32, "32 bit")], 120.0) {
+ f.insert("depth".into(), json!(depth));
+ }
+ });
+ ui.add_space(4.0);
+ small_label(ui, "Background Contents");
+ let mut bg = get_s(f, "background", "white");
+ let opts = [("white".to_string(), "White"), ("black".to_string(), "Black"), ("backgroundColor".to_string(), "Background Color"), ("transparent".to_string(), "Transparent")];
+ if widgets::dropdown(ui, "nd-bg", &mut bg, &opts, 240.0) {
+ f.insert("background".into(), json!(bg));
+ }
+ });
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn units_round_trip_through_pixels() {
+ assert_eq!(to_unit(2100.0, "in", 300.0), 7.0);
+ assert_eq!(from_unit(7.0, "in", 300.0), 2100.0);
+ assert_eq!(from_unit(2.54, "cm", 300.0), 300.0);
+ assert_eq!(to_unit(640.0, "px", 72.0), 640.0);
+ }
+
+ #[test]
+ fn preset_sets_size_resolution_and_create_params_drop_ui_keys() {
+ let mut f = crate::state::UiState::new_document_fields();
+ let a4 = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1.iter().find(|p| p.0 == "A4").unwrap();
+ apply_preset(&mut f, a4);
+ let p = command_params(&f);
+ assert_eq!(p["width"], 2480);
+ assert_eq!(p["height"], 3508);
+ assert_eq!(p["resolution"], 300.0);
+ assert!(p.get("__preset").is_none() && p.get("__unit").is_none());
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", p).unwrap();
+ let d = &s.active().unwrap().doc;
+ assert_eq!((d.size.width, d.size.height, d.resolution_dpi), (2480, 3508, 300.0));
+ }
+}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 084ceb4c9..a4d887d5a 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -16,7 +16,7 @@ use crate::{PhotocraftApp, icons, widgets};
/// shows the group's last-used tool.
const TOOL_SECTIONS: &[&[&[Tool]]] = &[
&[&[Tool::Move]],
- &[&[Tool::RectMarquee, Tool::EllipseMarquee], &[Tool::Lasso, Tool::PolygonLasso], &[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand], &[Tool::Crop], &[Tool::Eyedropper]],
+ &[&[Tool::RectMarquee, Tool::EllipseMarquee], &[Tool::Lasso, Tool::PolygonLasso], &[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand], &[Tool::Crop, Tool::Slice, Tool::SliceSelect], &[Tool::Eyedropper, Tool::Ruler, Tool::Note, Tool::Count]],
&[
&[Tool::SpotHealing, Tool::Healing],
&[Tool::Brush],
@@ -27,7 +27,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[
&[Tool::Blur, Tool::Sharpen, Tool::Smudge],
&[Tool::Dodge, Tool::Burn, Tool::Sponge],
],
- &[&[Tool::Pen], &[Tool::Type], &[Tool::PathSelection], &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line]],
+ &[&[Tool::Pen], &[Tool::Type], &[Tool::PathSelection], &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape]],
&[&[Tool::Hand], &[Tool::Zoom]],
];
@@ -43,11 +43,9 @@ fn slot_tool(ui: &egui::Ui, current: Tool, slot: &[Tool], key: egui::Id) -> Tool
pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let (w1, bx, m) = if t.pro { (40.0, 30.0, 5i8) } else { (50.0, 36.0, 7i8) };
- // Photoshop switches to a double-column toolbar when the window is too short.
+ // Photoshop switches to a double-column toolbar only when one column doesn't fit.
let slots: usize = TOOL_SECTIONS.iter().map(|g| g.len()).sum();
- let needed = slots as f32 * (bx + 3.0) + TOOL_SECTIONS.len() as f32 * 9.0 + 190.0;
- let avail_h = ui.ctx().content_rect().height() - 130.0;
- let double = needed > avail_h;
+ let double = toolbar_needs_double(slots, TOOL_SECTIONS.len(), bx, t.pro, ui.available_rect_before_wrap().height());
let w = if double { w1 + bx + 2.0 } else { w1 };
egui::Panel::left("toolbar").resizable(false).exact_size(w).frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(m, 8))).show(ui, |ui| {
if t.pro {
@@ -60,7 +58,7 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
// Subtle violet wash at the bottom of the toolbar.
let full = ui.max_rect();
- if !t.bevel && t.dark() {
+ if !t.bevel && !t.pro && t.dark() {
let mut mesh = egui::Mesh::default();
let r = Rect::from_min_max(pos2(full.left() - 7.0, full.bottom() - 260.0), pos2(full.right() + 7.0, full.bottom() + 8.0));
let top = Color32::TRANSPARENT;
@@ -77,7 +75,8 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let flyout_id = egui::Id::new("tool-flyout");
let mut slot_index = 0usize;
for (si, section) in TOOL_SECTIONS.iter().enumerate() {
- if si > 0 {
+ // Photoshop 2026 draws one uninterrupted column (no group dividers).
+ if si > 0 && !t.pro {
ui.add_space(4.0);
let (r, _) = ui.allocate_exact_size(vec2(if double { bx * 2.0 + 2.0 } else { bx }, 1.0), Sense::hover());
ui.painter().line_segment([r.left_center() + vec2(8.0, 0.0), r.right_center() - vec2(8.0, 0.0)], Stroke::new(1.0, t.separator));
@@ -145,17 +144,50 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
});
}
}
- ui.add_space(14.0);
+ let ctx = ui.ctx().clone();
+ if t.pro && icons::button(ui, "ellipsis", bx, false, "Edit Toolbar…").clicked() {
+ let _ = crate::menus::invoke(app, &ctx, "edit.toolbar", json!({}));
+ }
+ ui.add_space(if t.pro { 8.0 } else { 14.0 });
color_chips(app, ui);
if t.pro {
- ui.add_space(10.0);
- let _ = icons::button(ui, "square-dashed", bx, false, "Edit in Quick Mask Mode (Q)");
- let _ = icons::button(ui, "app-window", bx, false, "Change Screen Mode (F)");
- let _ = icons::button(ui, "ellipsis", bx, false, "Edit Toolbar…");
+ ui.add_space(8.0);
+ let quick_mask = app.session.active().is_some_and(|s| s.doc.quick_mask.is_some());
+ if icons::button(ui, "square-dashed", bx, quick_mask, if quick_mask { "Edit in Standard Mode (Q)" } else { "Edit in Quick Mask Mode (Q)" }).clicked() {
+ let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({}));
+ }
+ let sm = icons::button(ui, "app-window", bx, false, "Change Screen Mode (F)");
+ if sm.clicked() {
+ let _ = crate::menus::invoke(app, &ctx, "view.screenMode.cycle", json!({}));
+ }
+ // Right-click (or long-press) lists the modes, like Photoshop's flyout.
+ egui::Popup::context_menu(&sm).show(|ui| {
+ ui.set_min_width(220.0);
+ for (id, label) in [("view.screenMode.standard", "Standard Screen Mode"), ("view.screenMode.fullScreenWithMenuBar", "Full Screen Mode With Menu Bar"), ("view.screenMode.fullScreen", "Full Screen Mode")] {
+ let on = crate::view_cmds::checked(app, id).unwrap_or(false);
+ if ui.add(egui::Button::selectable(on, label)).clicked() {
+ let _ = crate::menus::invoke(app, &ctx, id, json!({}));
+ ui.close();
+ }
+ }
+ });
}
});
}
+/// Does the toolbar need two columns? Height of one column (header, tool slots, Edit Toolbar,
+/// colour chips, Quick Mask and Screen Mode) against the height the toolbar gets.
+pub fn toolbar_needs_double(slots: usize, sections: usize, bx: f32, pro: bool, avail_h: f32) -> bool {
+ let pitch = bx + 3.0;
+ let needed = if pro {
+ // margins + header + slots + "…" + gap + chips (38 + swap row) + gap + 2 buttons
+ 16.0 + 21.0 + (slots + 1) as f32 * pitch + 8.0 + 59.0 + 8.0 + 2.0 * pitch
+ } else {
+ 16.0 + slots as f32 * pitch + sections.saturating_sub(1) as f32 * 12.0 + 14.0 + 59.0
+ };
+ needed > avail_h
+}
+
fn c32(c: [f32; 4]) -> Color32 {
Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, (c[3] * 255.0) as u8)
}
@@ -171,10 +203,13 @@ fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
p.rect_filled(fg, 5.0, c32(app.session.tools.foreground));
p.rect_stroke(fg, 5.0, Stroke::new(1.5, t.chrome), StrokeKind::Outside);
p.rect_stroke(fg, 5.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ // Photoshop: clicking a chip opens the Color Picker for that colour.
+ let bg_resp = ui.interact(bg, ui.id().with("bgchip"), Sense::click());
let fg_resp = ui.interact(fg, ui.id().with("fgchip"), Sense::click());
- if fg_resp.on_hover_text("Foreground colour").clicked() {
- app.ui.panels.color = true;
- app.ui.dock_tabs.color = 1;
+ if fg_resp.on_hover_text("Set foreground color").clicked() {
+ crate::color_picker_ui::open(app, "foreground");
+ } else if bg_resp.on_hover_text("Set background color").clicked() {
+ crate::color_picker_ui::open(app, "background");
}
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
@@ -241,6 +276,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.painter().line_segment([r.left_top(), r.right_top()], Stroke::new(1.0, t.separator));
ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));
ui.horizontal_centered(|ui| {
+ if t.pro {
+ crate::chrome_ui::home_button(app, ui);
+ widgets::vline(ui, 22.0);
+ }
let _ = icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, app.ui.tool.label());
if t.pro {
let (r, _) = ui.allocate_exact_size(vec2(10.0, 20.0), Sense::hover());
@@ -259,7 +298,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
brush_preset_chip(ui, &mut app.session.tools.brush);
widgets::vline(ui, 22.0);
}
- if crate::retouch_ui::options_bar(app, ui, tool) || crate::vector_ui::options_bar(app, ui, tool) {
+ if crate::retouch_ui::options_bar(app, ui, tool) || crate::vector_ui::options_bar(app, ui, tool) || crate::analysis_ui::options_bar(app, ui, tool) || crate::slice_ui::options_bar(app, ui, tool) {
return;
}
let b = &mut app.session.tools.brush;
@@ -327,15 +366,28 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
ui.spacing_mut().item_spacing.x = 8.0;
widgets::vline(ui, 22.0);
+ let o = &mut app.ui.tool_options;
opt_label(ui, "Feather");
- let mut feather = 0.0f32;
- widgets::value_field(ui, &mut feather, 0.0..=1000.0, "px", 62.0);
- let mut aa = true;
- widgets::checkbox(ui, &mut aa, "Anti-alias");
+ widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0);
+ // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard).
+ ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, "Anti-alias"));
widgets::vline(ui, 22.0);
opt_label(ui, "Style");
- let mut style = 0u8;
- widgets::dropdown(ui, "marquee-style", &mut style, &[(0u8, "Normal"), (1, "Fixed Ratio"), (2, "Fixed Size")], 96.0);
+ let styles = [("normal".to_string(), "Normal"), ("fixedRatio".to_string(), "Fixed Ratio"), ("fixedSize".to_string(), "Fixed Size")];
+ if widgets::dropdown(ui, "marquee-style", &mut o.marquee_style, &styles, 96.0) {
+ (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) };
+ }
+ let fixed = o.marquee_style != "normal";
+ let (unit, range) = if o.marquee_style == "fixedSize" { ("px", 1.0..=300_000.0) } else { ("", 0.001..=999.0) };
+ ui.add_enabled_ui(fixed, |ui| {
+ opt_label(ui, "Width");
+ widgets::value_field(ui, &mut o.marquee_width, range.clone(), unit, 62.0);
+ if icons::button(ui, "arrow-left-right", 22.0, false, "Swaps height and width").clicked() {
+ std::mem::swap(&mut o.marquee_width, &mut o.marquee_height);
+ }
+ opt_label(ui, "Height");
+ widgets::value_field(ui, &mut o.marquee_height, range, unit, 62.0);
+ });
widgets::vline(ui, 22.0);
if widgets::secondary_button(ui, "Select and Mask…", 0.0).clicked() {
let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));
@@ -419,13 +471,11 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
Tool::Type if t.pro => crate::type_tool::options_bar(app, ui),
Tool::Move if t.pro => {
- let mut auto = false;
- widgets::checkbox(ui, &mut auto, "Auto-Select:");
- let mut target = 0u8;
- widgets::dropdown(ui, "move-target", &mut target, &[(0u8, "Layer"), (1, "Group")], 76.0);
+ let o = &mut app.ui.tool_options;
+ widgets::checkbox(ui, &mut o.move_auto_select, "Auto-Select:");
+ widgets::dropdown(ui, "move-target", &mut o.move_target, &[("layer".to_string(), "Layer"), ("group".to_string(), "Group")], 76.0);
widgets::vline(ui, 22.0);
- let mut tc = false;
- widgets::checkbox(ui, &mut tc, "Show Transform Controls");
+ widgets::checkbox(ui, &mut o.move_show_transform, "Show Transform Controls");
widgets::vline(ui, 22.0);
ui.spacing_mut().item_spacing.x = 0.0;
for (icon, tip, cmd) in [("panels-top-left", "Align left edges", "layer.align.leftEdges"), ("app-window", "Align horizontal centers", "layer.align.horizontalCenters"), ("panel-right", "Align right edges", "layer.align.rightEdges")] {
@@ -507,6 +557,10 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let r = ui.max_rect();
ui.painter().line_segment([r.left_top(), r.right_top()], Stroke::new(1.0, t.separator));
ui.horizontal_centered(|ui| {
+ if t.pro {
+ crate::chrome_ui::status_bar_pro(app, ui);
+ return;
+ }
if let (Some(st), Some(i)) = (app.session.active(), app.session.active_index()) {
let (w, h, mode, bits, layers) = (st.doc.size.width, st.doc.size.height, crate::canvas::mode_label(&st.doc), st.doc.depth.bits(), st.doc.layer_count());
let mut pct = app.ui.views[i].zoom * 100.0;
@@ -592,9 +646,12 @@ fn dock_panels(app: &mut PhotocraftApp, ui: &mut egui::Ui, p: &crate::state::Pan
// Photoshop Essentials order: Color, Properties, (Navigator, History), Layers last and filling.
if p.color {
let mut sel = app.ui.dock_tabs.color;
- let tabs: &[&str] = if t.pro { &["Color", "Swatches"] } else { &["Swatches", "Color"] };
+ // Photoshop Essentials: Color | Swatches | Gradients | Patterns.
+ let tabs: &[&str] = if t.pro { &["Color", "Swatches", "Gradients", "Patterns"] } else { &["Swatches", "Color", "Gradients", "Patterns"] };
let pro = t.pro;
widgets::card(ui, "color", tabs, &mut sel, |ui, tab| match (pro, tab) {
+ (_, 2) => crate::preset_panels::gradients_panel(app, ui),
+ (_, 3) => crate::preset_panels::patterns_panel(app, ui),
(true, 0) => color_field(app, ui),
(true, _) => swatches(app, ui),
(false, 0) => swatches(app, ui),
@@ -850,6 +907,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let active = st.active_layer;
let active_layer = active.and_then(|id| doc.layer(id)).cloned();
let selection = st.selected_layers();
+ let isolated = st.isolated_layers.clone();
let mut actions: Vec<(String, Value)> = Vec::new();
let t = Tokens::get(ui.ctx());
@@ -876,7 +934,10 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.add_space(4.0);
}
if let Some(l) = &active_layer {
+ // Photoshop greys blend mode, Opacity and Fill for the Background layer.
+ let bg = crate::doc_props_ui::is_background(&doc, l);
ui.horizontal(|ui| {
+ ui.add_enabled_ui(!bg, |ui| {
let mut m = l.blend;
let w = ui.available_width() - 150.0;
if widgets::dropdown(ui, "blend", &mut m, &blend_options(l.is_group()), w.max(100.0)) {
@@ -889,6 +950,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
label(ui, if t.pro { "Opacity:" } else { "Opacity" });
});
+ });
});
ui.horizontal(|ui| {
label(ui, if t.pro { "Lock:" } else { "Lock" });
@@ -913,13 +975,13 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "locks": {"all": !l.locks.all}})));
}
}
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ ui.add_enabled_ui(!bg, |ui| ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut f = l.fill_opacity * 100.0;
if widgets::value_field(ui, &mut f, 0.0..=100.0, "%", 66.0).changed() {
actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "fill": f / 100.0})));
}
label(ui, if t.pro { "Fill:" } else { "Fill" });
- });
+ }));
});
ui.add_space(2.0);
}
@@ -932,6 +994,10 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
egui::ScrollArea::vertical().id_salt("layer-rows").max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show(ui, |ui| {
let filter = app.ui.layer_filter.clone();
for (_, depth, l) in rows.iter().rev() {
+ // Select › Isolate Layers.
+ if !photocraft_engine::select_extra_cmds::isolation_shows(&doc, &isolated, l.id) {
+ continue;
+ }
if !filter.is_empty() {
let kind = match &l.content {
LayerContent::Raster(_) => "pixel",
@@ -966,13 +1032,13 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if icons::button(ui, "trash", 26.0, false, "Delete layer").clicked() {
actions.push(("layer.delete".into(), json!({})));
}
- if icons::button(ui, "plus", 26.0, false, "New layer (⇧⌘N)").clicked() {
+ if icons::button(ui, "square-plus", 26.0, false, "Create a new layer (⇧⌘N)").clicked() {
actions.push(("layer.new.layer".into(), json!({})));
}
- if icons::button(ui, "folder-plus", 26.0, false, "New group").clicked() {
+ if icons::button(ui, "folder", 26.0, false, "Create a new group").clicked() {
actions.push(("layer.new.group".into(), json!({})));
}
- let adj = icons::button(ui, "contrast", 26.0, false, "New fill or adjustment layer");
+ let adj = icons::button(ui, "contrast", 26.0, false, "Create new fill or adjustment layer");
egui::Popup::menu(&adj).show(|ui| {
ui.set_min_width(190.0);
for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("layer.newAdjustmentLayer.")) {
@@ -991,13 +1057,10 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.close();
}
});
- if icons::button(ui, "square-dashed", 26.0, false, "Add layer mask").clicked() {
+ if icons::button(ui, "square-dot", 26.0, false, "Add a mask").clicked() {
actions.push(("layer.layerMask.revealAll".into(), json!({})));
}
- if icons::button(ui, "copy", 26.0, false, "Duplicate layer (⌘J)").clicked() {
- actions.push(("layer.duplicate".into(), json!({})));
- }
- let fx = icons::button(ui, "sparkles", 26.0, false, "Add a layer style");
+ let fx = fx_button(ui, 26.0, "Add a layer style");
egui::Popup::menu(&fx).show(|ui| {
ui.set_min_width(180.0);
if ui.button("Blending Options…").clicked() {
@@ -1012,8 +1075,10 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
});
- if icons::button(ui, "link", 26.0, false, "Create clipping mask (⌥⌘G)").clicked() {
- actions.push(("layer.createClippingMask".into(), json!({})));
+ // Photoshop's footer starts with Link Layers (enabled with two or more layers selected).
+ let can_link = app.session.is_enabled("layer.linkLayers");
+ if ui.add_enabled_ui(can_link, |ui| icons::button(ui, "link", 26.0, false, "Link layers")).inner.clicked() {
+ actions.push(("layer.linkLayers".into(), json!({})));
}
});
});
@@ -1022,10 +1087,33 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
app.ui.mask_target = p.as_bool().unwrap_or(false);
continue;
}
+ if p.is_null() {
+ // Context-menu items behave like their menu-bar twins (dialogs included).
+ let ctx = ui.ctx().clone();
+ if let Err(e) = crate::menus::invoke(app, &ctx, &id, json!({})) {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ continue;
+ }
let _ = app.run(&id, p);
}
}
+/// Photoshop's italic "fx" footer button (no icon-font equivalent).
+fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response {
+ let t = Tokens::get(ui.ctx());
+ let (r, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(r, t.radius_sm, t.hover);
+ }
+ let mut job = egui::text::LayoutJob::default();
+ job.append("fx", 0.0, egui::TextFormat { font_id: egui::FontId::proportional(15.0), color: t.icon, italics: true, ..Default::default() });
+ let g = ui.painter().layout_job(job);
+ ui.painter().galley(r.center() - g.size() / 2.0, g, t.icon);
+ resp.on_hover_text(tip)
+}
+
/// How a Layers panel row is selected: in the (multi-)selection, the primary/active layer, and
/// whether several layers are selected.
#[derive(Clone, Copy)]
@@ -1051,7 +1139,8 @@ fn select_mode(m: egui::Modifiers) -> &'static str {
fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, doc: &photocraft_doc::Document, l: &Layer, depth: usize, row: RowSel, actions: &mut Vec<(String, Value)>) {
let selected = row.selected;
let t = Tokens::get(ctx);
- let row_h = if t.pro { 36.0 } else { 46.0 };
+ // Photoshop's default (medium) thumbnails: 32 pt rows.
+ let row_h = if t.pro { 32.0 } else { 46.0 };
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag());
layer_drag_and_drop(ctx, ui, l, rect, &resp, actions);
let painter = ui.painter_at(rect.expand(1.0));
@@ -1082,7 +1171,7 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
painter.text(pos2(x, rect.center().y), Align2::LEFT_CENTER, "↳", egui::FontId::proportional(13.0), t.text_faint);
x += 12.0;
}
- let ts = if t.pro { 28.0 } else { 34.0 };
+ let ts = if t.pro { 24.0 } else { 34.0 };
let thumb = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts));
draw_layer_thumb(app, ctx, ui, doc, l, thumb, row.primary);
x += ts + 6.0;
@@ -1110,12 +1199,13 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
}
let name_color = if l.visible { t.text } else { t.text_faint };
let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) };
- // Photoshop sets the locked Background layer's name in italics.
- let italic = l.name == "Background" && l.locks.transparency;
+ // Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright.
+ let italic = !t.pro && l.name == "Background" && l.locks.transparency;
let mut job = egui::text::LayoutJob::default();
job.append(&l.name, 0.0, egui::TextFormat { font_id: font, color: name_color, italics: italic, ..Default::default() });
let galley = painter.layout_job(job);
- let is_pixel = matches!(l.content, LayerContent::Raster(_));
+ // Photoshop rows show only the name; the kind sub-label is a Studio-theme addition.
+ let is_pixel = t.pro || matches!(l.content, LayerContent::Raster(_));
let text_pos = pos2(x, rect.center().y - galley.size().y / 2.0 - if is_pixel { 0.0 } else { 7.0 });
painter.galley(text_pos, galley, name_color);
if !is_pixel {
@@ -1186,50 +1276,10 @@ fn layer_row(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &mut egui::Ui, do
}
// Right-click context menu.
resp.context_menu(|ui| {
- ui.set_min_width(200.0);
- let id = l.id.0;
// Right-clicking inside a multi-selection keeps it and acts on every selected layer.
let on_set = row.multi && selected;
- let mut item = |ui: &mut egui::Ui, label: &str, cmd: &str| {
- if ui.button(label).clicked() {
- if on_set {
- actions.push((cmd.into(), json!({})));
- } else {
- actions.push(("layer.select".into(), json!({"layer": id})));
- actions.push((cmd.into(), json!({"layer": id})));
- }
- ui.close();
- }
- };
- item(ui, if on_set { "Duplicate Layers" } else { "Duplicate Layer" }, "layer.duplicate");
- item(ui, if on_set { "Delete Layers" } else { "Delete Layer" }, "layer.delete");
- ui.separator();
- if l.clipped {
- item(ui, "Release Clipping Mask", "layer.releaseClippingMask");
- } else {
- item(ui, "Create Clipping Mask", "layer.createClippingMask");
- }
- if l.mask.is_some() {
- item(ui, "Delete Layer Mask", "layer.layerMask.delete");
- } else {
- item(ui, "Add Layer Mask", "layer.layerMask.revealAll");
- }
- ui.separator();
- item(ui, "Group Layers", "layer.groupLayers");
- if on_set {
- item(ui, "Merge Layers", "layer.mergeLayers");
- item(ui, "Link Layers", "layer.linkLayers");
- } else {
- item(ui, "Merge Down", "layer.mergeDown");
- }
- if ui.button("Flatten Image").clicked() {
- actions.push(("layer.flattenImage".into(), json!({})));
- ui.close();
- }
- ui.separator();
- if ui.button("Rename Layer…").clicked() {
+ if crate::layer_menu_ui::show(app, ui, l, on_set, actions) {
ui.ctx().data_mut(|d| d.insert_temp(rename_id, l.name.clone()));
- ui.close();
}
});
}
@@ -1566,10 +1616,12 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
empty(ui, "No properties");
return;
};
- let Some(id) = st.active_layer else {
- empty(ui, "No layer selected");
+ // Photoshop shows the Document properties when nothing or the Background layer is selected.
+ if crate::doc_props_ui::shows_document(&st.doc, st.active_layer) {
+ crate::doc_props_ui::properties(app, ui);
return;
- };
+ }
+ let Some(id) = st.active_layer else { return };
let Some(layer) = st.doc.layer(id).cloned() else { return };
ui.horizontal(|ui| {
let icon = match &layer.content {
@@ -1597,7 +1649,11 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
} else if layer.artboard().is_some() {
crate::artboard_ui::properties(app, ui, &layer);
} else {
- layer_controls(app, ui, &layer);
+ if t.pro {
+ crate::layer_props_ui::properties(app, ui, &layer);
+ } else {
+ layer_controls(app, ui, &layer);
+ }
if matches!(layer.content, LayerContent::Text(_)) {
crate::type_tool::type_properties(app, ui);
}
diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs
index 8830a4031..d485aa5e2 100644
--- a/crates/ui-egui/src/parity.rs
+++ b/crates/ui-egui/src/parity.rs
@@ -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 = 527;
+pub const FLOOR: usize = 595;
/// One top-level menu's coverage.
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs
new file mode 100644
index 000000000..75f6d40e9
--- /dev/null
+++ b/crates/ui-egui/src/preset_panels.rs
@@ -0,0 +1,1037 @@
+//! Window › Gradients, Patterns (tabs of the Color card, as in Photoshop's Essentials workspace),
+//! Styles, Shapes, Tool Presets and Clone Source (floating panels).
+//!
+//! The preset panels share one browser: folders with disclosure triangles, a thumbnail grid (or a
+//! list when the size slider is at its minimum), a rename field, a context menu (Rename, Delete,
+//! Move to group) and the Photoshop footer (size slider · New Group · New · Delete). Clicking a
+//! preset selects it, double-clicking or dragging it onto the canvas applies it. Every action is
+//! an engine command (`gradient.presets.*`, `pattern.presets.*`, `style.presets.*`,
+//! `shape.presets.*`, `tool.presets.*`, `cloneSource.*`); this module only draws and dispatches.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+use egui::{Align2, Color32, ColorImage, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, TextureHandle, TextureOptions, pos2, vec2};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::Tool;
+use crate::theme::Tokens;
+
+/// Panel state (serde, so the control channel can read and drive it).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct PresetUi {
+ /// Floating panels.
+ pub styles: bool,
+ pub shapes: bool,
+ pub tool_presets: bool,
+ pub clone_source: bool,
+ /// Thumbnail size per panel (px; the minimum shows a list).
+ pub sizes: BTreeMap<String, f32>,
+ /// Folders whose open state differs from the default (only the first folder starts open).
+ pub toggled: BTreeSet<String>,
+ /// Selected preset per panel (by name / pattern id).
+ pub selected: BTreeMap<String, String>,
+ /// Tool Presets: Current Tool Only.
+ pub current_tool_only: bool,
+ /// Custom Shape tool: the shape it draws.
+ pub custom_shape: String,
+ /// In-place rename: (panel, preset or "group:<name>", text).
+ #[serde(skip)]
+ pub renaming: Option<(String, String, String)>,
+}
+
+impl PresetUi {
+ pub fn shape(&self) -> &str {
+ if self.custom_shape.is_empty() { "Heart" } else { &self.custom_shape }
+ }
+}
+
+const PANELS: [&str; 6] = ["window.panel.gradients", "window.panel.patterns", "window.panel.styles", "window.panel.shapes", "window.panel.toolPresets", "window.panel.cloneSource"];
+const MIN_THUMB: f32 = 20.0;
+
+/// Window-menu ids handled here.
+pub fn handles(id: &str) -> bool {
+ PANELS.contains(&id)
+}
+
+/// Color card tab of a Window › Gradients / Patterns id.
+fn color_tab(id: &str) -> Option<usize> {
+ match id {
+ "window.panel.gradients" => Some(2),
+ "window.panel.patterns" => Some(3),
+ _ => None,
+ }
+}
+
+fn float_flag<'a>(p: &'a mut PresetUi, id: &str) -> Option<&'a mut bool> {
+ Some(match id {
+ "window.panel.styles" => &mut p.styles,
+ "window.panel.shapes" => &mut p.shapes,
+ "window.panel.toolPresets" => &mut p.tool_presets,
+ "window.panel.cloneSource" => &mut p.clone_source,
+ _ => return None,
+ })
+}
+
+/// Window › <panel>: toggles the panel (Gradients and Patterns: the Color card tab).
+pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if !handles(id) {
+ return None;
+ }
+ let want = params.get("show").and_then(Value::as_bool);
+ if let Some(tab) = color_tab(id) {
+ let showing = app.ui.panels.color && app.ui.dock_tabs.color == tab;
+ let show = want.unwrap_or(!showing);
+ app.ui.panels.color = show || (app.ui.panels.color && app.ui.dock_tabs.color != tab);
+ if show {
+ app.ui.dock_tabs.color = tab;
+ }
+ return Some(Ok(json!({"visible": show})));
+ }
+ let flag = float_flag(&mut app.ui.presets_ui, id)?;
+ *flag = want.unwrap_or(!*flag);
+ Some(Ok(json!({"visible": *flag})))
+}
+
+pub fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ if let Some(tab) = color_tab(id) {
+ return Some(app.ui.panels.color && app.ui.dock_tabs.color == tab);
+ }
+ let mut p = app.ui.presets_ui.clone();
+ float_flag(&mut p, id).map(|f| *f)
+}
+
+fn run(app: &mut PhotocraftApp, id: &str, p: Value) -> Option<Value> {
+ match app.run(id, p) {
+ Ok(v) => Some(v),
+ Err(e) => {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ None
+ }
+ }
+}
+
+// ------------------------------------------------------------------ textures
+
+fn cached_texture(ctx: &egui::Context, key: impl std::hash::Hash + std::fmt::Debug, make: impl FnOnce() -> ColorImage) -> TextureHandle {
+ let id = egui::Id::new(("preset-tex", key));
+ if let Some(t) = ctx.data(|d| d.get_temp::<TextureHandle>(id)) {
+ return t;
+ }
+ let tex = ctx.load_texture(format!("preset-{id:?}"), make(), TextureOptions::LINEAR);
+ ctx.data_mut(|d| d.insert_temp(id, tex.clone()));
+ tex
+}
+
+fn c32(c: [f32; 4]) -> Color32 {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3]))
+}
+
+/// A gradient swatch: stops as a horizontal mesh over a checkerboard where it's transparent.
+pub fn paint_gradient(ui: &egui::Ui, rect: Rect, stops: &[(f32, [f32; 4])]) {
+ let p = ui.painter_at(rect);
+ if stops.iter().any(|s| s.1[3] < 0.999) {
+ crate::widgets::checker(&p, rect, (rect.height() / 4.0).clamp(3.0, 8.0));
+ }
+ let mut mesh = egui::Mesh::default();
+ let x = |t: f32| rect.left() + rect.width() * t.clamp(0.0, 1.0);
+ let mut pts: Vec<(f32, [f32; 4])> = stops.to_vec();
+ if pts.first().is_some_and(|s| s.0 > 0.0) {
+ pts.insert(0, (0.0, pts[0].1));
+ }
+ if let Some(l) = pts.last().copied().filter(|s| s.0 < 1.0) {
+ pts.push((1.0, l.1));
+ }
+ for w in pts.windows(2) {
+ let (a, b) = (w[0], w[1]);
+ let i = mesh.vertices.len() as u32;
+ let (ca, cb) = (c32(a.1), c32(b.1));
+ mesh.colored_vertex(pos2(x(a.0), rect.top()), ca);
+ mesh.colored_vertex(pos2(x(b.0), rect.top()), cb);
+ mesh.colored_vertex(pos2(x(b.0), rect.bottom()), cb);
+ mesh.colored_vertex(pos2(x(a.0), rect.bottom()), ca);
+ mesh.add_triangle(i, i + 1, i + 2);
+ mesh.add_triangle(i, i + 2, i + 3);
+ }
+ p.add(mesh);
+}
+
+fn pattern_texture(ctx: &egui::Context, pat: &photocraft_doc::Pattern) -> TextureHandle {
+ cached_texture(ctx, ("pattern", pat.id.clone()), || {
+ let (w, h) = (pat.width.max(1), pat.height.max(1));
+ let fmt = pat.surface.format();
+ let px = pat.surface.read_region(photocraft_geom::Rect::new(0, 0, w as i32, h as i32));
+ let n = fmt.channels();
+ // Tiles smaller than the swatch repeat; larger ones are shown shrunk.
+ const S: u32 = 64;
+ let step = (w.max(h) as f32 / S as f32).max(1.0);
+ let mut img = ColorImage::new([S as usize, S as usize], vec![Color32::TRANSPARENT; (S * S) as usize]);
+ for y in 0..S {
+ for x in 0..S {
+ let sx = ((x as f32 * step) as u32) % w;
+ let sy = ((y as f32 * step) as u32) % h;
+ let i = (sy * w + sx) as usize * n;
+ img.pixels[(y * S + x) as usize] = c32(photocraft_raster::to_rgba(&fmt, &px[i..i + n]));
+ }
+ }
+ img
+ })
+}
+
+fn style_texture(app: &PhotocraftApp, ctx: &egui::Context, st: &photocraft_engine::presets::styles::StylePreset) -> TextureHandle {
+ let key = ("style", st.name.clone(), st.effects.len(), format!("{:?}{:?}", st.blend, st.fill_opacity));
+ cached_texture(ctx, key, || {
+ const S: u32 = 64;
+ let px = photocraft_engine::presets::styles::thumbnail(&app.session, st, S);
+ ColorImage::from_rgba_unmultiplied([S as usize, S as usize], &px)
+ })
+}
+
+fn shape_texture(ctx: &egui::Context, sh: &photocraft_engine::presets::shapes::ShapePreset) -> TextureHandle {
+ let knots: usize = sh.path.subpaths.iter().map(|s| s.knots.len()).sum();
+ cached_texture(ctx, ("shape", sh.name.clone(), knots), || {
+ const S: u32 = 64;
+ let cov = photocraft_engine::presets::shapes::thumbnail(&sh.path, S);
+ ColorImage::new([S as usize, S as usize], cov.iter().map(|a| Color32::from_white_alpha((a.clamp(0.0, 1.0) * 255.0).round() as u8)).collect())
+ })
+}
+
+// ------------------------------------------------------------------ the browser
+
+struct ItemView {
+ key: String,
+ name: String,
+}
+
+struct GroupView {
+ name: String,
+ items: Vec<ItemView>,
+}
+
+enum Ev {
+ Select(String),
+ Activate(String),
+ Drop(String, Pos2),
+ Rename(String, String),
+ Delete(String),
+ Move(String, String),
+ RenameGroup(String, String),
+ DeleteGroup(String),
+ NewGroup,
+ New,
+}
+
+fn group_open(st: &PresetUi, panel: &str, gi: usize, name: &str) -> bool {
+ (gi == 0) != st.toggled.contains(&format!("{panel}/{name}"))
+}
+
+/// Draws the folders and footer; `thumb` paints item `(group, item)` into a rect.
+/// Where a browser sits: the canvas (drop target), its height cap and the New button's tooltip.
+struct Place<'a> {
+ canvas: Rect,
+ max_h: f32,
+ new_tip: &'a str,
+}
+
+fn browser(ui: &mut egui::Ui, st: &mut PresetUi, panel: &str, groups: &[GroupView], place: Place, thumb: &mut dyn FnMut(&egui::Ui, Rect, usize, usize)) -> Vec<Ev> {
+ let t = Tokens::get(ui.ctx());
+ let Place { canvas, max_h, new_tip } = place;
+ let mut ev = Vec::new();
+ let size = *st.sizes.get(panel).unwrap_or(&40.0);
+ let list = size <= MIN_THUMB + 0.5;
+ let selected = st.selected.get(panel).cloned();
+ // Rename field (Photoshop opens a small dialog; inline keeps the panel modeless).
+ if let Some((p, key, mut text)) = st.renaming.clone().filter(|r| r.0 == panel) {
+ let mut done = None;
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Name:").color(t.text_dim).size(11.5));
+ let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 4.0));
+ if !r.has_focus() && !r.lost_focus() {
+ r.request_focus();
+ }
+ if r.lost_focus() {
+ done = Some(ui.input(|i| i.key_pressed(egui::Key::Enter)));
+ }
+ });
+ st.renaming = Some((p, key.clone(), text.clone()));
+ if let Some(ok) = done {
+ st.renaming = None;
+ if ok && !text.trim().is_empty() {
+ match key.strip_prefix("group:") {
+ Some(g) => ev.push(Ev::RenameGroup(g.to_string(), text.trim().to_string())),
+ None => ev.push(Ev::Rename(key, text.trim().to_string())),
+ }
+ }
+ }
+ }
+ let mut headers: Vec<(Rect, String)> = Vec::new();
+ let mut dropped: Option<(String, Pos2)> = None;
+ let group_names: Vec<String> = groups.iter().map(|g| g.name.clone()).collect();
+ egui::ScrollArea::vertical().id_salt(("preset-scroll", panel)).max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {
+ ui.spacing_mut().item_spacing = vec2(0.0, 2.0);
+ for (gi, g) in groups.iter().enumerate() {
+ let open = group_open(st, panel, gi, &g.name);
+ let (hr, hresp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
+ if hresp.hovered() {
+ ui.painter().rect_filled(hr, 2.0, t.hover.gamma_multiply(0.5));
+ }
+ let tri = Rect::from_center_size(pos2(hr.left() + 9.0, hr.center().y), vec2(12.0, 12.0));
+ crate::icons::paint(ui, tri, if open { "chevron-down" } else { "chevron-right" }, 10.0, t.text_dim);
+ let fold = Rect::from_center_size(pos2(hr.left() + 25.0, hr.center().y), vec2(14.0, 14.0));
+ crate::icons::paint(ui, fold, if open { "folder-open" } else { "folder" }, 12.0, t.icon);
+ ui.painter().text(pos2(hr.left() + 37.0, hr.center().y), Align2::LEFT_CENTER, &g.name, FontId::proportional(11.5), t.text);
+ if hresp.clicked() {
+ let k = format!("{panel}/{}", g.name);
+ if !st.toggled.remove(&k) {
+ st.toggled.insert(k);
+ }
+ }
+ hresp.context_menu(|ui| {
+ if ui.button("Rename Group…").clicked() {
+ st.renaming = Some((panel.to_string(), format!("group:{}", g.name), g.name.clone()));
+ ui.close();
+ }
+ if ui.button("Delete Group").clicked() {
+ ev.push(Ev::DeleteGroup(g.name.clone()));
+ ui.close();
+ }
+ });
+ headers.push((hr, g.name.clone()));
+ if !open {
+ continue;
+ }
+ let w = ui.available_width();
+ let (cell, cols) = if list { (vec2(w, 24.0), 1) } else {
+ let cols = ((w - 8.0 + 4.0) / (size + 4.0)).floor().max(1.0) as usize;
+ (vec2(size, size), cols)
+ };
+ let rows = g.items.len().div_ceil(cols);
+ let pad = if list { 0.0 } else { 8.0 };
+ let gap = if list { 0.0 } else { 4.0 };
+ let (area, _) = ui.allocate_exact_size(vec2(w, rows as f32 * (cell.y + gap) + 2.0), Sense::hover());
+ for (ii, it) in g.items.iter().enumerate() {
+ let (cx, cy) = ((ii % cols) as f32, (ii / cols) as f32);
+ let r = Rect::from_min_size(area.min + vec2(pad + cx * (cell.x + gap), cy * (cell.y + gap)), cell);
+ let resp = ui.interact(r, ui.id().with((panel, gi, ii)), Sense::click_and_drag());
+ let is_sel = selected.as_deref() == Some(&it.key);
+ if list {
+ if is_sel {
+ ui.painter().rect_filled(r, 0.0, t.row_selected);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));
+ }
+ let tr = Rect::from_min_size(r.min + vec2(24.0, 2.0), vec2(20.0, 20.0));
+ thumb(ui, tr, gi, ii);
+ ui.painter().text(pos2(tr.right() + 8.0, r.center().y), Align2::LEFT_CENTER, &it.name, FontId::proportional(11.5), t.text);
+ } else {
+ thumb(ui, r, gi, ii);
+ let (stroke, kind) = if is_sel { (Stroke::new(2.0, t.accent), egui::StrokeKind::Outside) } else if resp.hovered() { (Stroke::new(1.0, t.text_dim), egui::StrokeKind::Outside) } else { (Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside) };
+ ui.painter().rect_stroke(r, CornerRadius::same(2), stroke, kind);
+ }
+ let resp = if list { resp } else { resp.on_hover_text(&it.name) };
+ if resp.double_clicked() {
+ ev.push(Ev::Activate(it.key.clone()));
+ } else if resp.clicked() {
+ ev.push(Ev::Select(it.key.clone()));
+ }
+ if resp.dragged()
+ && let Some(pp) = ui.ctx().pointer_interact_pos()
+ {
+ // A ghost of the swatch follows the pointer.
+ let lp = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("preset-drag")));
+ let gr = Rect::from_center_size(pp, vec2(28.0, 28.0));
+ lp.rect_filled(gr, 3.0, t.card.gamma_multiply(0.8));
+ lp.rect_stroke(gr, 3.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Outside);
+ lp.text(gr.center(), Align2::CENTER_CENTER, "+", FontId::proportional(16.0), t.accent);
+ }
+ if resp.drag_stopped()
+ && let Some(pp) = ui.ctx().pointer_interact_pos()
+ && !r.contains(pp)
+ {
+ dropped = Some((it.key.clone(), pp));
+ }
+ resp.context_menu(|ui| {
+ if ui.button("Rename…").clicked() {
+ st.renaming = Some((panel.to_string(), it.key.clone(), it.name.clone()));
+ ui.close();
+ }
+ if ui.button("Delete").clicked() {
+ ev.push(Ev::Delete(it.key.clone()));
+ ui.close();
+ }
+ ui.menu_button("Move to", |ui| {
+ for gname in group_names.iter().filter(|n| **n != g.name) {
+ if ui.button(gname).clicked() {
+ ev.push(Ev::Move(it.key.clone(), gname.clone()));
+ ui.close();
+ }
+ }
+ });
+ });
+ }
+ }
+ });
+ if let Some((key, pos)) = dropped {
+ if let Some((_, g)) = headers.iter().find(|(r, _)| r.contains(pos)) {
+ ev.push(Ev::Move(key, g.clone()));
+ } else if canvas.contains(pos) {
+ ev.push(Ev::Drop(key, pos));
+ }
+ }
+ // Footer: thumbnail size | New Group, New, Delete.
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ let mut s = size;
+ ui.add_sized(vec2(90.0, 18.0), egui::Slider::new(&mut s, MIN_THUMB..=96.0).show_value(false)).on_hover_text("Thumbnail size (smallest: list)");
+ if (s - size).abs() > 0.01 {
+ st.sizes.insert(panel.to_string(), s);
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "trash", 24.0, false, "Delete").clicked()
+ && let Some(k) = selected.clone()
+ {
+ ev.push(Ev::Delete(k));
+ }
+ if crate::icons::button(ui, "plus", 24.0, false, new_tip).clicked() {
+ ev.push(Ev::New);
+ }
+ if crate::icons::button(ui, "folder-plus", 24.0, false, "Create new group").clicked() {
+ ev.push(Ev::NewGroup);
+ }
+ });
+ });
+ ev
+}
+
+/// Shared handling of the generic events through `<prefix>.edit` / `.new`.
+fn generic(app: &mut PhotocraftApp, panel: &str, prefix: &str, e: &Ev, new_params: Value) -> bool {
+ let edit = format!("{prefix}.edit");
+ match e {
+ Ev::Rename(k, n) => {
+ run(app, &edit, json!({"action": "rename", "preset": k, "name": n}));
+ if app.ui.presets_ui.selected.get(panel) == Some(k) {
+ app.ui.presets_ui.selected.insert(panel.into(), n.clone());
+ }
+ }
+ Ev::Delete(k) => {
+ if run(app, &edit, json!({"action": "delete", "preset": k})).is_some() {
+ app.ui.presets_ui.selected.remove(panel);
+ }
+ }
+ Ev::Move(k, g) => drop(run(app, &edit, json!({"action": "move", "preset": k, "to": g}))),
+ Ev::RenameGroup(g, n) => drop(run(app, &edit, json!({"action": "renameGroup", "group": g, "name": n}))),
+ Ev::DeleteGroup(g) => drop(run(app, &edit, json!({"action": "deleteGroup", "group": g}))),
+ Ev::NewGroup => {
+ if let Some(r) = run(app, &edit, json!({"action": "newGroup", "name": "Group"})) {
+ let g = r["group"].as_str().unwrap_or_default().to_string();
+ app.ui.presets_ui.renaming = Some((panel.into(), format!("group:{g}"), g));
+ }
+ }
+ Ev::New => {
+ if let Some(r) = run(app, &format!("{prefix}.new"), new_params) {
+ let name = r.get("name").or(r.get("pattern")).and_then(Value::as_str).unwrap_or_default().to_string();
+ app.ui.presets_ui.selected.insert(panel.into(), name.clone());
+ if prefix != "pattern.presets" {
+ app.ui.presets_ui.renaming = Some((panel.into(), name.clone(), name));
+ }
+ }
+ }
+ _ => return false,
+ }
+ true
+}
+
+fn empty(ui: &mut egui::Ui, s: &str) {
+ let t = Tokens::get(ui.ctx());
+ ui.label(egui::RichText::new(s).color(t.text_faint).size(11.5));
+}
+
+/// Document point under a screen position on the main canvas.
+fn doc_point(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> {
+ let i = app.session.active_index()?;
+ let v = app.ui.views.get(i)?;
+ let xf = crate::canvas::ViewXform { rect: app.last_canvas_rect, zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal };
+ Some(xf.to_doc(pos))
+}
+
+// ------------------------------------------------------------------ Gradients
+
+pub fn gradients_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);
+ let groups_src = app.session.presets.gradients.clone();
+ // Current gradient (what the Gradient tool paints), like the panel's top "recent" row.
+ let cur = app.session.presets.gradient.clone();
+ let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
+ paint_gradient(ui, r, &cur.resolve(fg, bg));
+ ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, Tokens::get(ui.ctx()).card_border), egui::StrokeKind::Inside);
+ ui.add_space(4.0);
+ let groups: Vec<GroupView> = groups_src.iter().map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }).collect();
+ let canvas = app.last_canvas_rect;
+ let mut st = std::mem::take(&mut app.ui.presets_ui);
+ let max_h = (ui.available_height() - 40.0).clamp(90.0, 260.0);
+ let events = browser(ui, &mut st, "gradients", &groups, Place { canvas, max_h, new_tip: "Create new gradient" }, &mut |ui, r, gi, ii| {
+ let stops = groups_src[gi].items[ii].resolve(fg, bg);
+ paint_gradient(ui, r, &stops);
+ });
+ app.ui.presets_ui = st;
+ for e in events {
+ match &e {
+ Ev::Select(k) => {
+ app.ui.presets_ui.selected.insert("gradients".into(), k.clone());
+ run(app, "gradient.presets.select", json!({"preset": k}));
+ }
+ Ev::Activate(k) | Ev::Drop(k, _) => {
+ app.ui.presets_ui.selected.insert("gradients".into(), k.clone());
+ run(app, "gradient.presets.apply", json!({"preset": k}));
+ }
+ _ => {
+ generic(app, "gradients", "gradient.presets", &e, json!({"name": "Custom"}));
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------ Patterns
+
+pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ photocraft_engine::presets::patterns::sync(&mut app.session);
+ let lib = app.session.patterns.items.clone();
+ let groups: Vec<GroupView> = app
+ .session
+ .presets
+ .pattern_groups
+ .iter()
+ .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().filter_map(|id| lib.iter().find(|p| &p.id == id)).map(|p| ItemView { key: p.id.clone(), name: p.display_name().to_string() }).collect() })
+ .collect();
+ let pats: Vec<Vec<photocraft_doc::Pattern>> = app.session.presets.pattern_groups.iter().map(|g| g.items.iter().filter_map(|id| lib.iter().find(|p| &p.id == id).cloned()).collect()).collect();
+ let canvas = app.last_canvas_rect;
+ let mut st = std::mem::take(&mut app.ui.presets_ui);
+ let max_h = (ui.available_height() - 40.0).clamp(90.0, 280.0);
+ let ctx = ui.ctx().clone();
+ let events = browser(ui, &mut st, "patterns", &groups, Place { canvas, max_h, new_tip: "Create new pattern from the selection" }, &mut |ui, r, gi, ii| {
+ let tex = pattern_texture(&ctx, &pats[gi][ii]);
+ ui.painter().image(tex.id(), r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
+ });
+ app.ui.presets_ui = st;
+ for e in events {
+ match &e {
+ Ev::Select(k) => {
+ app.ui.presets_ui.selected.insert("patterns".into(), k.clone());
+ run(app, "pattern.presets.select", json!({"pattern": k}));
+ }
+ Ev::Activate(k) | Ev::Drop(k, _) => {
+ app.ui.presets_ui.selected.insert("patterns".into(), k.clone());
+ run(app, "pattern.presets.apply", json!({"pattern": k}));
+ }
+ _ => {
+ generic(app, "patterns", "pattern.presets", &e, json!({}));
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------ floating panels
+
+fn float_window(app: &mut PhotocraftApp, ctx: &egui::Context, key: &str, title: &str, width: f32, offset: f32, body: impl FnOnce(&mut PhotocraftApp, &mut egui::Ui)) -> bool {
+ let t = Tokens::get(ctx);
+ let frame = egui::Frame::NONE
+ .fill(t.card)
+ .stroke(Stroke::new(1.0, t.card_border))
+ .corner_radius(CornerRadius::same(t.radius_lg as u8))
+ .shadow(egui::Shadow { offset: [0, 10], blur: 30, spread: 0, color: t.shadow })
+ .inner_margin(egui::Margin::same(8));
+ let canvas = app.last_canvas_rect;
+ let mut close = false;
+ egui::Window::new(title)
+ .id(egui::Id::new(("preset-window", key)))
+ .title_bar(false)
+ .resizable(false)
+ .frame(frame)
+ .default_pos(pos2((canvas.right() - width - 16.0 - offset).max(canvas.left() + 8.0), canvas.top() + 40.0))
+ .show(ctx, |ui| {
+ ui.set_width(width);
+ // Photoshop-style tab header with a close box.
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(title).color(t.text).size(12.0).strong());
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "x", 20.0, false, "Close").clicked() {
+ close = true;
+ }
+ });
+ });
+ crate::widgets::hairline(ui);
+ ui.add_space(4.0);
+ body(app, ui);
+ });
+ close
+}
+
+/// Draws the open floating panels (Styles, Shapes, Tool Presets, Clone Source).
+pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let p = app.ui.presets_ui.clone();
+ if p.styles && float_window(app, ctx, "styles", "Styles", 250.0, 0.0, styles_panel) {
+ app.ui.presets_ui.styles = false;
+ }
+ if p.shapes && float_window(app, ctx, "shapes", "Shapes", 250.0, 280.0, shapes_panel) {
+ app.ui.presets_ui.shapes = false;
+ }
+ if p.tool_presets && float_window(app, ctx, "toolPresets", "Tool Presets", 250.0, 560.0, tool_presets_panel) {
+ app.ui.presets_ui.tool_presets = false;
+ }
+ if p.clone_source && float_window(app, ctx, "cloneSource", "Clone Source", 270.0, 840.0, clone_source_panel) {
+ app.ui.presets_ui.clone_source = false;
+ }
+}
+
+// ------------------------------------------------------------------ Styles
+
+pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let src = app.session.presets.styles.clone();
+ let groups: Vec<GroupView> = src.iter().map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }).collect();
+ let canvas = app.last_canvas_rect;
+ let mut st = std::mem::take(&mut app.ui.presets_ui);
+ let ctx = ui.ctx().clone();
+ let t = Tokens::get(&ctx);
+ let mut texes: Vec<Vec<TextureHandle>> = Vec::new();
+ for g in &src {
+ texes.push(g.items.iter().map(|s| style_texture(app, &ctx, s)).collect());
+ }
+ let events = browser(ui, &mut st, "styles", &groups, Place { canvas, max_h: 300.0, new_tip: "Create new style from the selected layer" }, &mut |ui, r, gi, ii| {
+ ui.painter().rect_filled(r, 2.0, t.field);
+ ui.painter().image(texes[gi][ii].id(), r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
+ });
+ app.ui.presets_ui = st;
+ let shift = ui.input(|i| i.modifiers.shift);
+ for e in events {
+ match &e {
+ Ev::Select(k) | Ev::Activate(k) => {
+ app.ui.presets_ui.selected.insert("styles".into(), k.clone());
+ // Clicking applies to the selected layers (⇧ adds to their effects).
+ run(app, "style.presets.apply", json!({"preset": k, "add": shift}));
+ }
+ Ev::Drop(k, pos) => {
+ // Dropping on the canvas styles the layer under the pointer's selection: the active layer.
+ let _ = pos;
+ run(app, "style.presets.apply", json!({"preset": k}));
+ }
+ _ => {
+ generic(app, "styles", "style.presets", &e, json!({"name": "Style"}));
+ }
+ }
+ }
+}
+
+// ------------------------------------------------------------------ Shapes
+
+pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let src = photocraft_engine::presets::shapes::all_groups(&app.session);
+ let groups: Vec<GroupView> = src.iter().map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }).collect();
+ let canvas = app.last_canvas_rect;
+ let mut st = std::mem::take(&mut app.ui.presets_ui);
+ let ctx = ui.ctx().clone();
+ let t = Tokens::get(&ctx);
+ let events = browser(ui, &mut st, "shapes", &groups, Place { canvas, max_h: 300.0, new_tip: "Create new shape from the current path" }, &mut |ui, r, gi, ii| {
+ let tex = shape_texture(&ctx, &src[gi].items[ii]);
+ ui.painter().image(tex.id(), r.shrink(2.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text);
+ });
+ app.ui.presets_ui = st;
+ let fill = shape_fill(app);
+ for e in events {
+ match &e {
+ Ev::Select(k) => {
+ // Selecting a shape picks it for the Custom Shape tool (and switches to it).
+ app.ui.presets_ui.selected.insert("shapes".into(), k.clone());
+ app.ui.presets_ui.custom_shape = k.clone();
+ app.ui.tool = Tool::CustomShape;
+ }
+ Ev::Activate(k) => {
+ app.ui.presets_ui.custom_shape = k.clone();
+ run(app, "shape.presets.place", json!({"preset": k, "fill": fill}));
+ }
+ Ev::Drop(k, pos) => {
+ app.ui.presets_ui.custom_shape = k.clone();
+ let mut p = json!({"preset": k, "fill": fill});
+ if let (Some(c), Some(d)) = (doc_point(app, *pos), app.session.active()) {
+ let side = (d.doc.size.width.min(d.doc.size.height) as f64 * 0.3).max(8.0);
+ p["rect"] = json!([c[0] - side / 2.0, c[1] - side / 2.0, side, side]);
+ }
+ run(app, "shape.presets.place", p);
+ }
+ _ => {
+ generic(app, "shapes", "shape.presets", &e, json!({"name": "Shape"}));
+ }
+ }
+ }
+}
+
+fn shape_fill(app: &PhotocraftApp) -> Value {
+ let f = app.session.tools.foreground;
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ if app.ui.tool_options.shape_fill { json!(format!("#{:02x}{:02x}{:02x}", q(f[0]), q(f[1]), q(f[2]))) } else { Value::Null }
+}
+
+/// Options-bar shape picker for the Custom Shape tool.
+pub fn shape_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ ui.label(egui::RichText::new("Shape:").color(t.text_dim).size(12.0));
+ let groups = photocraft_engine::presets::shapes::all_groups(&app.session);
+ let cur = app.ui.presets_ui.shape().to_string();
+ let ctx = ui.ctx().clone();
+ let (r, resp) = ui.allocate_exact_size(vec2(36.0, 22.0), Sense::click());
+ ui.painter().rect_filled(r, 3.0, t.field);
+ ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
+ if let Some(sh) = groups.iter().flat_map(|g| g.items.iter()).find(|s| s.name == cur) {
+ let tex = shape_texture(&ctx, sh);
+ ui.painter().image(tex.id(), Rect::from_center_size(r.center() - vec2(5.0, 0.0), vec2(18.0, 18.0)), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text);
+ }
+ crate::icons::paint(ui, Rect::from_center_size(pos2(r.right() - 8.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_dim);
+ let resp = resp.on_hover_text(&cur);
+ egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
+ ui.set_width(232.0);
+ egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
+ for g in &groups {
+ ui.label(egui::RichText::new(&g.name).color(t.text_dim).size(11.0));
+ ui.horizontal_wrapped(|ui| {
+ ui.spacing_mut().item_spacing = vec2(3.0, 3.0);
+ for sh in &g.items {
+ let (cr, cresp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click());
+ let on = sh.name == cur;
+ ui.painter().rect_filled(cr, 2.0, if on { t.accent_soft } else if cresp.hovered() { t.hover } else { t.field });
+ let tex = shape_texture(&ctx, sh);
+ ui.painter().image(tex.id(), cr.shrink(4.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text);
+ if cresp.on_hover_text(&sh.name).clicked() {
+ app.ui.presets_ui.custom_shape = sh.name.clone();
+ ui.close();
+ }
+ }
+ });
+ }
+ });
+ });
+}
+
+/// Custom Shape tool drag: places the selected shape in the dragged rect (⇧ keeps proportions).
+pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, fill: Value, stroke: Value) {
+ let name = app.ui.presets_ui.shape().to_string();
+ let r = run(app, "shape.presets.place", json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke}));
+ if r.is_none() && !photocraft_engine::presets::shapes::all_groups(&app.session).iter().any(|g| g.items.iter().any(|s| s.name == name)) {
+ app.ui.status = format!("No custom shape \"{name}\": pick one in the options bar or Window › Shapes");
+ }
+}
+
+// ------------------------------------------------------------------ Tool Presets
+
+fn tool_id(t: Tool) -> String {
+ let s = format!("{t:?}");
+ let mut c = s.chars();
+ c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default()
+}
+
+/// Apply a tool preset: the engine sets the brush/colour, the shell switches tool and options.
+pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) {
+ let Some(r) = run(app, "tool.presets.select", json!({"preset": name})) else { return };
+ if let Some(tool) = r["tool"].as_str().and_then(Tool::from_name) {
+ app.ui.tool = tool;
+ }
+ if let Some(o) = r["options"].get("toolOptions").and_then(Value::as_object) {
+ let mut cur = serde_json::to_value(&app.ui.tool_options).unwrap_or_default();
+ if let Some(c) = cur.as_object_mut() {
+ for (k, v) in o {
+ c.insert(k.clone(), v.clone());
+ }
+ }
+ if let Ok(opts) = serde_json::from_value(cur) {
+ app.ui.tool_options = opts;
+ }
+ }
+}
+
+pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let only = app.ui.presets_ui.current_tool_only;
+ let cur = app.ui.tool;
+ let items: Vec<(String, String)> = app.session.presets.tool_presets.iter().filter(|p| !only || Tool::from_name(&p.tool) == Some(cur)).map(|p| (p.name.clone(), p.tool.clone())).collect();
+ let selected = app.ui.presets_ui.selected.get("toolPresets").cloned();
+ let mut action: Option<(String, Value)> = None;
+ let mut pick: Option<String> = None;
+ // Rename field.
+ if let Some((_, key, mut text)) = app.ui.presets_ui.renaming.clone().filter(|r| r.0 == "toolPresets") {
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new("Name:").color(t.text_dim).size(11.5));
+ let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 4.0));
+ if !r.has_focus() && !r.lost_focus() {
+ r.request_focus();
+ }
+ if r.lost_focus() {
+ app.ui.presets_ui.renaming = None;
+ if ui.input(|i| i.key_pressed(egui::Key::Enter)) && !text.trim().is_empty() {
+ action = Some(("tool.presets.edit".into(), json!({"action": "rename", "preset": key, "name": text.trim()})));
+ }
+ } else {
+ app.ui.presets_ui.renaming = Some(("toolPresets".into(), key.clone(), text.clone()));
+ }
+ });
+ }
+ egui::ScrollArea::vertical().id_salt("tool-presets").max_height(260.0).auto_shrink([false, true]).show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ if items.is_empty() {
+ empty(ui, if only { "No presets for the current tool." } else { "No tool presets." });
+ }
+ for (name, tool) in &items {
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click());
+ if selected.as_deref() == Some(name) {
+ ui.painter().rect_filled(r, 0.0, t.row_selected);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));
+ }
+ let icon = Tool::from_name(tool).map(crate::icons::tool_icon).unwrap_or("settings");
+ crate::icons::paint(ui, Rect::from_center_size(pos2(r.left() + 14.0, r.center().y), vec2(16.0, 16.0)), icon, 13.0, t.icon);
+ ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, name, FontId::proportional(11.5), t.text);
+ if resp.clicked() {
+ pick = Some(name.clone());
+ }
+ resp.context_menu(|ui| {
+ if ui.button("Rename Tool Preset…").clicked() {
+ app.ui.presets_ui.renaming = Some(("toolPresets".into(), name.clone(), name.clone()));
+ ui.close();
+ }
+ if ui.button("Delete Tool Preset").clicked() {
+ action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": name})));
+ ui.close();
+ }
+ });
+ }
+ });
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ crate::widgets::checkbox(ui, &mut app.ui.presets_ui.current_tool_only, "Current Tool Only");
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "trash", 24.0, false, "Delete tool preset").clicked()
+ && let Some(n) = selected.clone()
+ {
+ action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": n})));
+ }
+ if crate::icons::button(ui, "plus", 24.0, false, "Create new tool preset").clicked() {
+ let label = cur.label().to_string();
+ let opts = json!({"toolOptions": serde_json::to_value(&app.ui.tool_options).unwrap_or_default()});
+ action = Some(("tool.presets.new".into(), json!({"name": label, "tool": tool_id(cur), "options": opts})));
+ }
+ });
+ });
+ if let Some(n) = pick {
+ app.ui.presets_ui.selected.insert("toolPresets".into(), n.clone());
+ select_tool_preset(app, &n);
+ }
+ if let Some((cmd, p)) = action {
+ let created = cmd == "tool.presets.new";
+ if let Some(r) = run(app, &cmd, p)
+ && created
+ {
+ let n = r["name"].as_str().unwrap_or_default().to_string();
+ app.ui.presets_ui.selected.insert("toolPresets".into(), n.clone());
+ app.ui.presets_ui.renaming = Some(("toolPresets".into(), n.clone(), n));
+ }
+ }
+}
+
+// ------------------------------------------------------------------ Clone Source
+
+pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let cs = app.session.presets.clone.clone();
+ let slot = cs.active().clone();
+ let mut action: Option<Value> = None;
+ // The five source buttons.
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for i in 0..photocraft_engine::presets::clone_source::SLOTS {
+ let set = cs.slots[i].source.is_some();
+ let tip = match cs.slots[i].source {
+ Some(s) => format!("Clone source {}: {:.0}, {:.0}", i + 1, s[0], s[1]),
+ None => format!("Clone source {} (⌥-click with Clone Stamp to set)", i + 1),
+ };
+ let r = crate::icons::button(ui, "stamp", 30.0, cs.active == i, &tip);
+ if set {
+ let d = r.rect.right_bottom() - vec2(6.0, 6.0);
+ ui.painter().circle_filled(d, 2.5, t.accent);
+ }
+ if r.clicked() {
+ run(app, "cloneSource.select", json!({"index": i}));
+ }
+ }
+ });
+ ui.add_space(4.0);
+ let src_line = match (slot.source, slot.layer.and_then(|l| app.session.active().and_then(|d| d.doc.layer(photocraft_doc::LayerId(l)).map(|x| x.name.clone())))) {
+ (Some(_), Some(l)) => format!("Source: {} : {l}", app.session.active().map(|d| d.doc.name.clone()).unwrap_or_default()),
+ (Some(_), None) => "Source: set".to_string(),
+ _ => "Source: not set (⌥-click with Clone Stamp)".to_string(),
+ };
+ ui.label(egui::RichText::new(src_line).color(t.text_dim).size(11.0));
+ ui.add_space(4.0);
+ let lbl = |ui: &mut egui::Ui, s: &str| {
+ ui.add_sized(vec2(18.0, 18.0), egui::Label::new(egui::RichText::new(s).color(t.text_dim).size(11.5)));
+ };
+ let off = slot.offset().unwrap_or([0.0, 0.0]);
+ let (mut ox, mut oy) = (off[0] as f32, off[1] as f32);
+ let (mut w, mut h) = (slot.scale[0] as f32, slot.scale[1] as f32);
+ let mut rot = slot.rotation as f32;
+ egui::Grid::new("clone-src-grid").num_columns(4).spacing(vec2(6.0, 4.0)).show(ui, |ui| {
+ lbl(ui, "X:");
+ if crate::widgets::value_field(ui, &mut ox, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() {
+ action = Some(json!({"offset": [ox, oy]}));
+ }
+ lbl(ui, "W:");
+ if crate::widgets::value_field(ui, &mut w, -1000.0..=1000.0, "%", 64.0).changed() {
+ action = Some(json!({"width": w}));
+ }
+ ui.end_row();
+ lbl(ui, "Y:");
+ if crate::widgets::value_field(ui, &mut oy, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() {
+ action = Some(json!({"offset": [ox, oy]}));
+ }
+ lbl(ui, "H:");
+ if crate::widgets::value_field(ui, &mut h, -1000.0..=1000.0, "%", 64.0).changed() {
+ action = Some(json!({"height": h}));
+ }
+ ui.end_row();
+ lbl(ui, "A:");
+ if crate::widgets::value_field(ui, &mut rot, -180.0..=180.0, "°", 72.0).changed() {
+ action = Some(json!({"rotation": rot}));
+ }
+ ui.horizontal(|ui| {
+ if crate::icons::button(ui, "arrow-left-right", 22.0, slot.flip_h, "Flip Horizontal").clicked() {
+ action = Some(json!({"flipH": !slot.flip_h}));
+ }
+ if crate::icons::button(ui, "rotate-cw", 22.0, false, "Reset Transform").clicked() {
+ run(app, "cloneSource.resetTransform", json!({}));
+ }
+ });
+ ui.horizontal(|ui| {
+ if crate::icons::button(ui, "scaling", 22.0, slot.flip_v, "Flip Vertical").clicked() {
+ action = Some(json!({"flipV": !slot.flip_v}));
+ }
+ });
+ ui.end_row();
+ });
+ if let Some(p) = action {
+ run(app, "cloneSource.set", p);
+ }
+ ui.add_space(6.0);
+ crate::widgets::hairline(ui);
+ ui.add_space(4.0);
+ // Overlay options.
+ let mut o = cs.overlay.clone();
+ let before = o.clone();
+ crate::widgets::checkbox(ui, &mut o.show, "Show Overlay");
+ ui.horizontal(|ui| {
+ ui.add_space(18.0);
+ ui.label(egui::RichText::new("Opacity:").color(t.text_dim).size(11.5));
+ crate::widgets::value_field(ui, &mut o.opacity, 0.0..=100.0, "%", 56.0);
+ let opts = [("normal".to_string(), "Normal"), ("darken".to_string(), "Darken"), ("lighten".to_string(), "Lighten"), ("difference".to_string(), "Difference")];
+ crate::widgets::dropdown(ui, "clone-overlay-mode", &mut o.blend, &opts, 90.0);
+ });
+ ui.horizontal(|ui| {
+ ui.add_space(18.0);
+ crate::widgets::checkbox(ui, &mut o.clipped, "Clipped");
+ crate::widgets::checkbox(ui, &mut o.auto_hide, "Auto Hide");
+ crate::widgets::checkbox(ui, &mut o.invert, "Invert");
+ });
+ if o != before {
+ run(app, "cloneSource.overlay", json!({"show": o.show, "opacity": o.opacity, "clipped": o.clipped, "autoHide": o.auto_hide, "invert": o.invert, "blend": o.blend}));
+ }
+}
+
+/// Where the active clone source samples for document point `at` (for the canvas marker).
+pub fn clone_sample_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option<[f64; 2]> {
+ use photocraft_engine::presets::clone_source::{Mapping, transform_matrix};
+ let s = app.session.presets.clone.active();
+ let src = s.source?;
+ match (s.anchor, at) {
+ (Some(a), Some(h)) if app.ui.tool_options.clone_aligned => {
+ let m = Mapping { source: (src[0], src[1]), anchor: (a[0], a[1]), m: transform_matrix(s.scale, s.rotation, s.flip_h, s.flip_v) };
+ let (x, y) = m.map(h[0], h[1]);
+ Some([x, y])
+ }
+ _ => Some(src),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::menus::invoke;
+
+ fn app() -> (PhotocraftApp, egui::Context) {
+ let ctx = egui::Context::default();
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
+ app.sync_views();
+ (app, ctx)
+ }
+
+ #[test]
+ fn window_menu_toggles_panels_and_color_tabs() {
+ let (mut app, ctx) = app();
+ for id in PANELS {
+ assert!(crate::menus::is_live(id), "{id}");
+ }
+ invoke(&mut app, &ctx, "window.panel.gradients", Value::Null).unwrap();
+ assert!(app.ui.panels.color && app.ui.dock_tabs.color == 2);
+ assert_eq!(checked(&app, "window.panel.gradients"), Some(true));
+ assert_eq!(checked(&app, "window.panel.patterns"), Some(false));
+ invoke(&mut app, &ctx, "window.panel.patterns", Value::Null).unwrap();
+ assert_eq!(app.ui.dock_tabs.color, 3);
+ // Choosing it again hides the card.
+ invoke(&mut app, &ctx, "window.panel.patterns", Value::Null).unwrap();
+ assert!(!app.ui.panels.color);
+ for (id, f) in [("window.panel.styles", 0), ("window.panel.shapes", 1), ("window.panel.toolPresets", 2), ("window.panel.cloneSource", 3)] {
+ invoke(&mut app, &ctx, id, Value::Null).unwrap();
+ let p = &app.ui.presets_ui;
+ assert!([p.styles, p.shapes, p.tool_presets, p.clone_source][f], "{id}");
+ assert_eq!(checked(&app, id), Some(true));
+ invoke(&mut app, &ctx, id, json!({"show": false})).unwrap();
+ assert_eq!(checked(&app, id), Some(false));
+ }
+ }
+
+ #[test]
+ fn tool_preset_switches_tool_and_options() {
+ let (mut app, _) = app();
+ app.ui.tool = Tool::Brush;
+ select_tool_preset(&mut app, "Radial Gradient");
+ assert_eq!(app.ui.tool, Tool::Gradient);
+ assert_eq!(app.ui.tool_options.gradient_style, "radial");
+ select_tool_preset(&mut app, "Soft Eraser 60 px");
+ assert_eq!(app.ui.tool, Tool::Eraser);
+ assert_eq!(app.session.tools.brush.size, 60.0);
+ assert_eq!(tool_id(Tool::CloneStamp), "cloneStamp");
+ assert_eq!(Tool::from_name(&tool_id(Tool::CustomShape)), Some(Tool::CustomShape));
+ }
+
+ #[test]
+ fn custom_shape_tool_places_the_picked_shape() {
+ let (mut app, _) = app();
+ app.ui.presets_ui.custom_shape = "Star".into();
+ finish_custom_shape(&mut app, [4.0, 4.0, 20.0, 20.0], true, json!("#ff0000"), Value::Null);
+ let d = app.session.active().unwrap();
+ let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
+ assert_eq!(l.name, "Star");
+ assert!(matches!(l.content, photocraft_doc::LayerContent::Shape(_)));
+ }
+
+ #[test]
+ fn clone_marker_follows_the_engine_slot() {
+ let (mut app, _) = app();
+ assert_eq!(clone_sample_point(&app, Some([5.0, 5.0])), None);
+ app.run("cloneSource.set", json!({"source": [10, 10]})).unwrap();
+ assert_eq!(clone_sample_point(&app, Some([30.0, 30.0])), Some([10.0, 10.0]));
+ app.session.presets.clone.active_mut().anchor = Some([20.0, 20.0]);
+ assert_eq!(clone_sample_point(&app, Some([30.0, 30.0])), Some([20.0, 20.0]));
+ }
+}
diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs
index 5c75d76ef..eb1741e2f 100644
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@ -18,7 +18,11 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m
Tool::SpotHealing => ("paint.spotHealing", json!({"type": o.spot_type})),
Tool::Healing | Tool::CloneStamp => {
let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample});
- match (app.ui.clone_offset.filter(|_| o.clone_aligned), app.ui.clone_source) {
+ // The Clone Source panel's active slot (set by ⌥-click) drives the stroke: the engine
+ // keeps the aligned pairing and applies the slot's scale/rotation/flip.
+ let slot = app.session.presets.clone.active().source.is_some();
+ match (app.ui.clone_offset.filter(|_| o.clone_aligned && !slot), app.ui.clone_source.filter(|_| !slot)) {
+ _ if slot => {}
(Some(off), _) => p["offset"] = json!(off),
(None, Some(src)) => p["source"] = json!(src),
(None, None) => {
@@ -74,6 +78,7 @@ pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f
pub fn set_source(app: &mut PhotocraftApp, x: f64, y: f64) {
app.ui.clone_source = Some([x.round(), y.round()]);
app.ui.clone_offset = None;
+ let _ = app.run("cloneSource.set", json!({"source": [x.round(), y.round()]}));
app.ui.status = format!("Clone source set at {:.0}, {:.0}", x, y);
app.ui.status_error = false;
}
@@ -83,9 +88,10 @@ pub fn draw_source_marker(app: &PhotocraftApp, painter: &egui::Painter, xf: &Vie
if !matches!(app.ui.tool, Tool::CloneStamp | Tool::Healing) {
return;
}
- let src = match (app.ui.clone_offset, app.hover_doc, app.ui.clone_source) {
- (Some(off), Some(h), _) => Some([h[0] + off[0], h[1] + off[1]]),
- (None, _, Some(s)) => Some(s),
+ let src = match (crate::preset_panels::clone_sample_point(app, app.hover_doc), app.ui.clone_offset, app.hover_doc, app.ui.clone_source) {
+ (Some(p), ..) => Some(p),
+ (None, Some(off), Some(h), _) => Some([h[0] + off[0], h[1] + off[1]]),
+ (None, None, _, Some(s)) => Some(s),
_ => None,
};
let Some(s) = src else { return };
diff --git a/crates/ui-egui/src/slice_ui.rs b/crates/ui-egui/src/slice_ui.rs
new file mode 100644
index 000000000..58792802a
--- /dev/null
+++ b/crates/ui-egui/src/slice_ui.rs
@@ -0,0 +1,320 @@
+//! Slice tool and Slice Select tool (Crop group, C): drawing new user slices, selecting and
+//! moving slices, the slice overlay (outlines and numbered badges in the Preferences › Guides,
+//! Grid & Slices colour) and both tools' options bars. Every change is an engine command
+//! (`slice.new`, `slice.set`, `slice.promote`, `slice.divide`, `slice.delete`); this module only
+//! turns pointer gestures into them.
+
+use egui::{Color32, Rect, Stroke, vec2};
+use photocraft_doc::slices::{self, ResolvedSlice};
+use photocraft_doc::{Document, SliceOrigin};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+use crate::state::{DialogKind, Tool};
+
+/// Slice tool state (serde: readable through the control channel).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct SliceUi {
+ /// The selected slice's display number (Slice Select tool).
+ pub selected: Option<usize>,
+ /// Slice Select options bar › Hide Auto Slices.
+ pub hide_auto: bool,
+ #[serde(skip)]
+ pub drag: Option<SliceDrag>,
+}
+
+/// A gesture in progress.
+#[derive(Clone, Debug, PartialEq)]
+pub enum SliceDrag {
+ New { start: [f64; 2], cur: [f64; 2] },
+ Move { id: u32, start: [f64; 2], cur: [f64; 2], rect: photocraft_geom::Rect },
+}
+
+fn is_slice_tool(t: Tool) -> bool {
+ matches!(t, Tool::Slice | Tool::SliceSelect)
+}
+
+/// The slice under a document point: stored slices win (the latest on top), then auto slices.
+pub fn slice_at(doc: &Document, x: f64, y: f64) -> Option<ResolvedSlice> {
+ let all = slices::resolve(doc);
+ let (xi, yi) = (x.floor() as i32, y.floor() as i32);
+ let order = |r: &ResolvedSlice| r.id.and_then(|id| doc.slices.list.iter().position(|s| s.id == id));
+ all.iter().filter(|r| r.rect.contains(xi, yi)).max_by_key(|r| order(r).map_or(0, |i| i + 1)).cloned()
+}
+
+fn rect_from(a: [f64; 2], b: [f64; 2]) -> photocraft_geom::Rect {
+ let (x0, x1) = (a[0].min(b[0]).floor() as i32, a[0].max(b[0]).ceil() as i32);
+ let (y0, y1) = (a[1].min(b[1]).floor() as i32, a[1].max(b[1]).ceil() as i32);
+ photocraft_geom::Rect::new(x0, y0, x1, y1)
+}
+
+/// Pointer input for the two slice tools. Returns true when the event was theirs.
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) -> bool {
+ let tool = app.ui.tool;
+ if !is_slice_tool(tool) {
+ return false;
+ }
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return true };
+ let locked = app.session.file_menu.slices_locked;
+ match ev {
+ ToolEvent::Down { x, y, .. } => {
+ if tool == Tool::Slice {
+ if !locked {
+ app.ui.slices.drag = Some(SliceDrag::New { start: [x, y], cur: [x, y] });
+ }
+ } else {
+ let hit = slice_at(&doc, x, y);
+ app.ui.slices.selected = hit.as_ref().map(|r| r.number);
+ if let Some(r) = hit
+ && let Some(id) = r.id.filter(|_| !locked && r.origin == SliceOrigin::User)
+ {
+ app.ui.slices.drag = Some(SliceDrag::Move { id, start: [x, y], cur: [x, y], rect: r.rect });
+ }
+ }
+ }
+ ToolEvent::Move { x, y, .. } => match &mut app.ui.slices.drag {
+ Some(SliceDrag::New { cur, .. }) | Some(SliceDrag::Move { cur, .. }) => *cur = [x, y],
+ None => {}
+ },
+ ToolEvent::Up { x, y } => match app.ui.slices.drag.take() {
+ Some(SliceDrag::New { start, .. }) => {
+ let r = rect_from(start, [x, y]);
+ if r.width() >= 1 && r.height() >= 1 && (r.width() > 2 || r.height() > 2) {
+ if let Ok(v) = app.run("slice.new", json!({"rect": [r.x0, r.y0, r.width(), r.height()]})) {
+ app.ui.slices.selected = v.get("number").and_then(Value::as_u64).map(|n| n as usize);
+ }
+ } else {
+ app.ui.slices.selected = slice_at(&doc, x, y).map(|r| r.number);
+ }
+ }
+ Some(SliceDrag::Move { id, start, rect, .. }) => {
+ let (dx, dy) = ((x - start[0]).round() as i32, (y - start[1]).round() as i32);
+ if dx != 0 || dy != 0 {
+ let r = rect.translate(dx, dy);
+ if app.run("slice.set", json!({"slice": id, "rect": [r.x0, r.y0, r.width(), r.height()]})).is_ok() {
+ let d = app.session.active().map(|d| d.doc.clone());
+ app.ui.slices.selected = d.and_then(|d| slices::resolve(&d).into_iter().find(|s| s.id == Some(id)).map(|s| s.number));
+ }
+ }
+ }
+ None => {}
+ },
+ }
+ true
+}
+
+fn hex(s: &str, fallback: Color32) -> Color32 {
+ let s = s.trim_start_matches('#');
+ let b = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok());
+ match (s.len(), b(0), b(2), b(4)) {
+ (6, Some(r), Some(g), Some(bl)) => Color32::from_rgb(r, g, bl),
+ _ => fallback,
+ }
+}
+
+/// Slice outlines and numbered badges (View › Show › Slices; always while a slice tool is on).
+pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ let tool_on = is_slice_tool(app.ui.tool);
+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
+ if !(tool_on || (app.ui.view.shows(app.ui.view.show.slices) && !doc.slices.is_empty())) {
+ return;
+ }
+ let prefs = &app.session.prefs().guides_grid_and_slices;
+ let color = hex(&prefs.slice_color, Color32::from_rgb(0x38, 0xb5, 0xff));
+ let numbers = prefs.show_slice_numbers;
+ let selected_color = Color32::from_rgb(0xff, 0xb0, 0x00);
+ let to_screen = |r: photocraft_geom::Rect| Rect::from_two_pos(xf.to_screen(r.x0 as f32, r.y0 as f32), xf.to_screen(r.x1 as f32, r.y1 as f32));
+ let all = slices::resolve(&doc);
+ // Auto slices first (dotted, underneath), then user and layer slices.
+ for pass in [true, false] {
+ for r in all.iter().filter(|r| (r.origin == SliceOrigin::Auto) == pass) {
+ if pass && (!tool_on || app.ui.slices.hide_auto) {
+ continue;
+ }
+ let sr = to_screen(r.rect);
+ let selected = app.ui.slices.selected == Some(r.number);
+ if pass {
+ let pts = [sr.left_top(), sr.right_top(), sr.right_bottom(), sr.left_bottom(), sr.left_top()];
+ painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, color.gamma_multiply(0.7)), 3.0, 3.0));
+ } else {
+ painter.rect_stroke(sr, 0.0, Stroke::new(1.0, color), egui::StrokeKind::Inside);
+ }
+ if selected && tool_on {
+ painter.rect_stroke(sr, 0.0, Stroke::new(2.0, selected_color), egui::StrokeKind::Inside);
+ if r.origin == SliceOrigin::User {
+ for c in [sr.left_top(), sr.right_top(), sr.left_bottom(), sr.right_bottom(), sr.center_top(), sr.center_bottom(), sr.left_center(), sr.right_center()] {
+ painter.rect_filled(Rect::from_center_size(c, vec2(5.0, 5.0)), 0.0, selected_color);
+ }
+ }
+ }
+ if numbers && sr.width() > 18.0 && sr.height() > 12.0 {
+ let label = match r.origin {
+ SliceOrigin::Layer => format!("{:02} ▪", r.number),
+ _ => format!("{:02}", r.number),
+ };
+ let font = egui::FontId::proportional(10.0);
+ let galley = painter.layout_no_wrap(label, font, Color32::WHITE);
+ let badge = Rect::from_min_size(sr.left_top() + vec2(2.0, 2.0), galley.size() + vec2(6.0, 2.0));
+ let bg = if pass { Color32::from_gray(110) } else if selected && tool_on { selected_color } else { color };
+ painter.rect_filled(badge, 2.0, bg);
+ painter.galley(badge.min + vec2(3.0, 1.0), galley, Color32::WHITE);
+ }
+ }
+ }
+ match &app.ui.slices.drag {
+ Some(SliceDrag::New { start, cur }) => {
+ let sr = to_screen(rect_from(*start, *cur));
+ painter.rect_stroke(sr, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle);
+ let pts = [sr.left_top(), sr.right_top(), sr.right_bottom(), sr.left_bottom(), sr.left_top()];
+ painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, color), 4.0, 4.0));
+ }
+ Some(SliceDrag::Move { start, cur, rect, .. }) => {
+ let r = rect.translate((cur[0] - start[0]).round() as i32, (cur[1] - start[1]).round() as i32);
+ painter.rect_stroke(to_screen(r), 0.0, Stroke::new(2.0, selected_color), egui::StrokeKind::Inside);
+ }
+ None => {}
+ }
+}
+
+/// The selected slice's id, promoting an auto slice first when `promote`.
+fn selected_id(app: &mut PhotocraftApp, promote: bool) -> Option<u32> {
+ let n = app.ui.slices.selected?;
+ let doc = app.session.active()?.doc.clone();
+ let r = slices::resolve(&doc).into_iter().find(|r| r.number == n)?;
+ match r.id {
+ Some(id) => Some(id),
+ None if promote => app.run("slice.promote", json!({"number": n})).ok()?.get("slice")?.as_u64().map(|v| v as u32),
+ None => None,
+ }
+}
+
+/// Slice Options dialog for the selected slice (auto slices are promoted on OK).
+pub fn open_options(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let n = app.ui.slices.selected.ok_or("select a slice with the Slice Select tool")?;
+ let st = app.session.active().ok_or("no document")?;
+ let r = slices::resolve(&st.doc).into_iter().find(|r| r.number == n).ok_or("no such slice")?;
+ let v = photocraft_engine::slice_cmds::resolved_json(&st.doc, &r);
+ let mut f = serde_json::Map::new();
+ f.insert("__command".into(), json!("slice.set"));
+ f.insert("__label".into(), json!("Slice Options"));
+ f.insert("__form".into(), json!(true));
+ f.insert("__choices".into(), json!({"kind": ["image", "noImage"]}));
+ f.insert("number".into(), json!(n));
+ f.insert("kind".into(), v["kind"].clone());
+ for k in ["name", "url", "target", "alt", "message", "cellText"] {
+ f.insert(k.into(), v[k].clone());
+ }
+ f.insert("background".into(), json!(v["background"].as_str().unwrap_or("none")));
+ Ok(json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)}))
+}
+
+/// Divide Slice dialog.
+fn open_divide(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let n = app.ui.slices.selected.ok_or("select a slice first")?;
+ let mut f = serde_json::Map::new();
+ f.insert("__command".into(), json!("slice.divide"));
+ f.insert("__label".into(), json!("Divide Slice"));
+ f.insert("__form".into(), json!(true));
+ f.insert("__choices".into(), json!({}));
+ f.insert("number".into(), json!(n));
+ f.insert("horizontal".into(), json!(2));
+ f.insert("vertical".into(), json!(1));
+ Ok(json!({"dialog": app.ui.open_dialog(DialogKind::Command, f)}))
+}
+
+/// Options bars of the Slice and Slice Select tools.
+pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
+ if !is_slice_tool(tool) {
+ return false;
+ }
+ let has_doc = app.session.active().is_some();
+ let locked = app.session.file_menu.slices_locked;
+ let t = crate::theme::Tokens::get(ui.ctx());
+ if tool == Tool::Slice {
+ ui.label(egui::RichText::new("Style: Normal").color(t.text_dim));
+ crate::widgets::vline(ui, 22.0);
+ if ui.add_enabled_ui(has_doc && !locked, |ui| crate::widgets::secondary_button(ui, "Slices From Guides", 0.0)).inner.clicked() {
+ let _ = app.run("slice.fromGuides", json!({}));
+ }
+ } else {
+ let sel = app.ui.slices.selected.is_some();
+ let stored = sel && app.session.active().is_some_and(|d| slices::resolve(&d.doc).iter().any(|r| Some(r.number) == app.ui.slices.selected && r.id.is_some()));
+ if ui.add_enabled_ui(sel && !locked, |ui| crate::widgets::secondary_button(ui, "Promote", 0.0)).inner.clicked() {
+ let _ = selected_id(app, true).map(|id| app.run("slice.promote", json!({"slice": id})));
+ }
+ if ui.add_enabled_ui(sel && !locked, |ui| crate::widgets::secondary_button(ui, "Divide…", 0.0)).inner.clicked() {
+ let _ = open_divide(app);
+ }
+ if ui.add_enabled_ui(stored && !locked, |ui| crate::widgets::secondary_button(ui, "Delete", 0.0)).inner.clicked()
+ && let Some(id) = selected_id(app, false)
+ && app.run("slice.delete", json!({"slice": id})).is_ok()
+ {
+ app.ui.slices.selected = None;
+ }
+ crate::widgets::vline(ui, 22.0);
+ crate::widgets::checkbox(ui, &mut app.ui.slices.hide_auto, "Hide Auto Slices");
+ crate::widgets::vline(ui, 22.0);
+ if ui.add_enabled_ui(sel && !locked, |ui| crate::widgets::secondary_button(ui, "Slice Options…", 0.0)).inner.clicked() {
+ let _ = open_options(app);
+ }
+ }
+ if locked {
+ ui.label(egui::RichText::new("Slices are locked (View › Lock Slices)").color(t.text_dim).size(11.0));
+ }
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
+ app
+ }
+
+ #[test]
+ fn slice_tool_draws_and_select_tool_moves() {
+ let mut app = app();
+ app.ui.tool = Tool::Slice;
+ let m = egui::Modifiers::NONE;
+ assert!(pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m));
+ pointer(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, m);
+ pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m);
+ let doc = app.session.active().unwrap().doc.clone();
+ assert_eq!(doc.slices.list.len(), 1);
+ assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(10, 10, 40, 30));
+ let n = app.ui.slices.selected.unwrap();
+ // Slice Select: drag it by (5, 5).
+ app.ui.tool = Tool::SliceSelect;
+ pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m);
+ assert_eq!(app.ui.slices.selected, Some(n));
+ pointer(&mut app, ToolEvent::Up { x: 25.0, y: 25.0 }, m);
+ let doc = app.session.active().unwrap().doc.clone();
+ assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(15, 15, 45, 35));
+ // Clicking an auto slice selects it; Slice Options promotes it.
+ pointer(&mut app, ToolEvent::Down { x: 90.0, y: 75.0, pressure: 1.0 }, m);
+ pointer(&mut app, ToolEvent::Up { x: 90.0, y: 75.0 }, m);
+ let r = open_options(&mut app).unwrap();
+ let id = r["dialog"].as_u64().unwrap();
+ app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("footer"));
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ let doc = app.session.active().unwrap().doc.clone();
+ assert!(doc.slices.list.iter().any(|s| s.name == "footer"));
+ }
+
+ #[test]
+ fn locked_slices_ignore_gestures() {
+ let mut app = app();
+ app.run("view.lockSlices", json!({"on": true})).unwrap();
+ app.ui.tool = Tool::Slice;
+ let m = egui::Modifiers::NONE;
+ pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m);
+ pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m);
+ assert!(app.session.active().unwrap().doc.slices.is_empty());
+ }
+}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index a7e563065..af052998a 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -13,6 +13,9 @@ pub enum Tool {
MagicWand,
Crop,
Eyedropper,
+ Ruler,
+ Note,
+ Count,
Brush,
Eraser,
Gradient,
@@ -39,10 +42,13 @@ pub enum Tool {
Triangle,
Polygon,
Line,
+ CustomShape,
+ Slice,
+ SliceSelect,
}
impl Tool {
- pub const ALL: [Tool; 34] = [
+ pub const ALL: [Tool; 40] = [
Tool::Move,
Tool::RectMarquee,
Tool::EllipseMarquee,
@@ -51,6 +57,9 @@ impl Tool {
Tool::MagicWand,
Tool::Crop,
Tool::Eyedropper,
+ Tool::Ruler,
+ Tool::Note,
+ Tool::Count,
Tool::Brush,
Tool::Eraser,
Tool::Gradient,
@@ -77,6 +86,9 @@ impl Tool {
Tool::Triangle,
Tool::Polygon,
Tool::Line,
+ Tool::CustomShape,
+ Tool::Slice,
+ Tool::SliceSelect,
];
pub fn label(self) -> &'static str {
@@ -87,10 +99,15 @@ impl Tool {
Tool::Brush => "Brush Tool",
Tool::Eraser => "Eraser Tool",
Tool::Eyedropper => "Eyedropper Tool",
+ Tool::Ruler => "Ruler Tool",
+ Tool::Note => "Note Tool",
+ Tool::Count => "Count Tool",
Tool::Lasso => "Lasso Tool",
Tool::PolygonLasso => "Polygonal Lasso Tool",
Tool::MagicWand => "Magic Wand Tool",
Tool::Crop => "Crop Tool",
+ Tool::Slice => "Slice Tool",
+ Tool::SliceSelect => "Slice Select Tool",
Tool::Gradient => "Gradient Tool",
Tool::PaintBucket => "Paint Bucket Tool",
Tool::Type => "Horizontal Type Tool",
@@ -115,6 +132,7 @@ impl Tool {
Tool::Triangle => "Triangle Tool",
Tool::Polygon => "Polygon Tool",
Tool::Line => "Line Tool",
+ Tool::CustomShape => "Custom Shape Tool",
}
}
/// Retouching and painting tools that stroke with the brush (share the brush cursor and chip).
@@ -128,10 +146,10 @@ impl Tool {
Tool::RectMarquee | Tool::EllipseMarquee => 'M',
Tool::Brush => 'B',
Tool::Eraser => 'E',
- Tool::Eyedropper => 'I',
+ Tool::Eyedropper | Tool::Ruler | Tool::Note | Tool::Count => 'I',
Tool::Lasso | Tool::PolygonLasso => 'L',
Tool::MagicWand => 'W',
- Tool::Crop => 'C',
+ Tool::Crop | Tool::Slice | Tool::SliceSelect => 'C',
Tool::Gradient | Tool::PaintBucket => 'G',
Tool::Type => 'T',
Tool::Hand => 'H',
@@ -144,7 +162,7 @@ impl Tool {
Tool::QuickSelection | Tool::ObjectSelection => 'W',
Tool::Pen => 'P',
Tool::PathSelection => 'A',
- Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line => 'U',
+ Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => 'U',
}
}
/// Glyph drawn in the toolbar (vector icons come later).
@@ -292,6 +310,32 @@ pub struct ToolOptions {
pub corner_radius: f32,
pub polygon_sides: u32,
pub line_weight: f32,
+ /// Marquee options bar: "normal" | "fixedRatio" | "fixedSize", with the ratio or size.
+ #[serde(default = "default_marquee_style")]
+ pub marquee_style: String,
+ #[serde(default = "one")]
+ pub marquee_width: f32,
+ #[serde(default = "one")]
+ pub marquee_height: f32,
+ /// Move tool: Auto-Select (with "layer" or "group" target) and Show Transform Controls.
+ #[serde(default)]
+ pub move_auto_select: bool,
+ #[serde(default = "default_move_target")]
+ pub move_target: String,
+ #[serde(default)]
+ pub move_show_transform: bool,
+}
+
+fn default_move_target() -> String {
+ "layer".into()
+}
+
+fn default_marquee_style() -> String {
+ "normal".into()
+}
+
+fn one() -> f32 {
+ 1.0
}
impl Default for ToolOptions {
@@ -328,6 +372,12 @@ impl Default for ToolOptions {
corner_radius: 0.0,
polygon_sides: 5,
line_weight: 3.0,
+ marquee_style: default_marquee_style(),
+ marquee_width: 1.0,
+ marquee_height: 1.0,
+ move_auto_select: false,
+ move_target: default_move_target(),
+ move_show_transform: false,
}
}
}
@@ -346,6 +396,9 @@ pub struct TransformSession {
/// Warp mode (Edit › Transform › Warp): the warp being edited over `rect`, in document px.
#[serde(default)]
pub warp: Option<photocraft_geom::warp::Warp>,
+ /// Select › Transform Selection: the box transforms the selection outline, not pixels.
+ #[serde(default)]
+ pub selection: bool,
}
/// In-progress inline type editing (Type tool). Offsets are character indices.
@@ -424,6 +477,21 @@ pub struct UiState {
/// Layer Comps panel: the selected comp (by comp id).
#[serde(default)]
pub layer_comp_selected: Option<u32>,
+ /// Preset panels (Gradients, Patterns, Styles, Shapes, Tool Presets, Clone Source).
+ #[serde(default)]
+ pub presets_ui: crate::preset_panels::PresetUi,
+ /// Character/Paragraph Styles, Glyphs and Check Spelling (see `type_panels_ui`).
+ #[serde(default)]
+ pub type_panels: crate::type_panels_ui::TypePanelsUi,
+ /// Ruler/Count/Note tools, Measurement Log and Notes panels (see `analysis_ui`).
+ #[serde(default)]
+ pub analysis: crate::analysis_ui::AnalysisUi,
+ /// Slice and Slice Select tools (see `slice_ui`).
+ #[serde(default)]
+ pub slices: crate::slice_ui::SliceUi,
+ /// Modifier Keys panel, custom pixel aspect ratios, workspace dialogs (see `workspace_ui`).
+ #[serde(default)]
+ pub shell: crate::workspace_ui::ShellUi,
/// View extras: rulers (⌘R), grid (⌘'), guides (⌘;), snapping (⇧⌘;), locked guides (⌥⌘;).
#[serde(default)]
pub extras: Extras,
@@ -461,6 +529,9 @@ pub struct UiState {
/// The status message is an error (shown in the warning colour).
#[serde(default)]
pub status_error: bool,
+ /// Status bar info field, Home screen (see `chrome_ui`).
+ #[serde(default)]
+ pub chrome: crate::chrome_ui::ChromeState,
}
impl Default for UiState {
@@ -476,6 +547,11 @@ impl Default for UiState {
view: Default::default(),
actions: Default::default(),
layer_comp_selected: None,
+ presets_ui: Default::default(),
+ type_panels: Default::default(),
+ analysis: Default::default(),
+ slices: Default::default(),
+ shell: Default::default(),
layer_filter: Vec::new(),
pen: None,
selected_path: None,
@@ -496,6 +572,7 @@ impl Default for UiState {
next_id: 1,
status: String::new(),
status_error: false,
+ chrome: Default::default(),
}
}
}
diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs
index 5d0b470b1..afdd150d7 100644
--- a/crates/ui-egui/src/transform_tool.rs
+++ b/crates/ui-egui/src/transform_tool.rs
@@ -72,6 +72,48 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>
pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0],
interpolation: "bicubic".into(),
warp: None,
+ selection: false,
+ });
+ Ok(())
+}
+
+/// Start Select › Transform Selection: the same box over the selection's bounds, previewing the
+/// selection mask (the marching ants are hidden meanwhile); commits `select.transformSelection`.
+pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
+ let st = app.session.active().ok_or("no document")?;
+ let doc = st.doc.clone();
+ let sel = doc.selection.clone().ok_or("no selection")?;
+ let b = sel.content_bounds();
+ if b.is_empty() {
+ return Err("no selection".into());
+ }
+ let layer = st.active_layer.or_else(|| doc.layers.first().map(|l| l.id)).ok_or("no layer")?;
+ crate::type_tool::commit(app);
+ let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64];
+ let session = app.ui.alloc_id();
+ let (w, h) = (b.width() as usize, b.height() as usize);
+ let k = w.max(h).div_ceil(2048).max(1);
+ let (tw, th) = (w.div_ceil(k), h.div_ceil(k));
+ let mut px = vec![Color32::TRANSPARENT; tw * th];
+ for ty in 0..th {
+ for tx in 0..tw {
+ let m = sel.sample_channel(b.x0 + (tx * k) as i32, b.y0 + (ty * k) as i32, 0).clamp(0.0, 1.0);
+ px[ty * tw + tx] = Color32::from_rgba_unmultiplied(120, 170, 255, (m * 110.0) as u8);
+ }
+ }
+ let texture = ctx.load_texture(format!("transform-{session}"), egui::ColorImage::new([tw, th], px), egui::TextureOptions::LINEAR);
+ let mut pd = (*doc).clone();
+ pd.selection = None;
+ app.transform_preview = Some(TransformPreview { session, doc: Arc::new(pd), texture, opacity: 1.0, gesture: None, warp_drag: None });
+ app.ui.transform = Some(TransformSession {
+ session,
+ layer: layer.0,
+ rect,
+ quad: corners(rect),
+ pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0],
+ interpolation: "bilinear".into(),
+ warp: None,
+ selection: true,
});
Ok(())
}
@@ -94,6 +136,7 @@ pub fn enter_warp(app: &mut PhotocraftApp) {
return;
}
if t.quad == corners(t.rect)
+ && !t.selection
&& let Some(w) = existing
{
t.rect = w.bounds;
@@ -164,6 +207,19 @@ fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool {
pub fn commit(app: &mut PhotocraftApp) {
let Some(t) = app.ui.transform.take() else { return };
app.transform_preview = None;
+ if t.selection {
+ let mut p = json!({"rect": t.rect, "interpolation": t.interpolation});
+ match &t.warp {
+ Some(w) if !w.is_identity() => p["warp"] = json!(w),
+ Some(_) => return,
+ None if t.quad == corners(t.rect) => return,
+ None => p["quad"] = json!(t.quad),
+ }
+ if let Err(e) = app.run("select.transformSelection", p) {
+ app.ui.status = e;
+ }
+ return;
+ }
if let Some(w) = &t.warp {
if w.is_identity() {
return;
@@ -757,7 +813,7 @@ mod tests {
use super::*;
fn session() -> TransformSession {
- TransformSession { session: 1, layer: 1, rect: [0.0, 0.0, 100.0, 50.0], quad: corners([0.0, 0.0, 100.0, 50.0]), pivot: [50.0, 25.0], interpolation: "bicubic".into(), warp: None }
+ TransformSession { session: 1, layer: 1, rect: [0.0, 0.0, 100.0, 50.0], quad: corners([0.0, 0.0, 100.0, 50.0]), pivot: [50.0, 25.0], interpolation: "bicubic".into(), warp: None, selection: false }
}
fn drag(s: &mut TransformSession, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) {
@@ -835,6 +891,26 @@ mod tests {
assert!(app.ui.transform.is_none() && app.transform_preview.is_none());
}
+ #[test]
+ fn transform_selection_moves_only_the_outline() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
+ app.sync_views();
+ app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap();
+ let px0 = app.session.active().unwrap().doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64));
+ let ctx = egui::Context::default();
+ crate::menus::invoke(&mut app, &ctx, "select.transformSelection", json!({})).unwrap();
+ let t = app.ui.transform.as_ref().unwrap();
+ assert!(t.selection && t.rect == [8.0, 8.0, 24.0, 24.0]);
+ assert!(app.transform_preview.as_ref().unwrap().doc.selection.is_none(), "ants hidden while transforming");
+ scale_about_pivot(&mut app, 2.0, 2.0);
+ commit(&mut app);
+ let st = app.session.active().unwrap();
+ let b = st.doc.selection.as_ref().unwrap().content_bounds();
+ assert!(b.width().abs_diff(32) <= 2 && b.x0.abs_diff(0) <= 1, "{b:?}");
+ assert_eq!(st.doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64)), px0);
+ }
+
#[test]
fn warp_mode_drags_anchor_with_handles_splits_and_commits() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
diff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/type_panels_ui.rs
new file mode 100644
index 000000000..b486c7a78
--- /dev/null
+++ b/crates/ui-egui/src/type_panels_ui.rs
@@ -0,0 +1,870 @@
+//! Type panels: Character Styles + Paragraph Styles (one floating group with two tabs, as in
+//! Photoshop), Glyphs, and the Edit › Check Spelling dialog.
+//!
+//! Everything acts through engine commands (`type.characterStyle.*`, `type.paragraphStyle.*`,
+//! `type.insertText`, `edit.checkSpelling`); the panels only hold view state
+//! ([`TypePanelsUi`], part of the serialisable UI state so the control channel can drive it).
+
+use egui::{Align2, Color32, CornerRadius, Rect, RichText, Sense, Stroke, TextureHandle, TextureOptions, pos2, vec2};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+/// View state of the type panels.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct TypePanelsUi {
+ /// The Character Styles / Paragraph Styles group is open.
+ pub styles: bool,
+ /// 0 = Character Styles, 1 = Paragraph Styles.
+ pub styles_tab: usize,
+ /// Glyphs panel is open.
+ pub glyphs: bool,
+ /// Style Options editor open for (paragraph?, id).
+ pub options: Option<(bool, u32)>,
+ /// Glyphs: font family and style ("" = follow the type selection), "Show" category, cell
+ /// size in points of UI, recently used glyphs (most recent first).
+ pub glyph_family: String,
+ pub glyph_style: String,
+ pub glyph_category: String,
+ pub glyph_size: f32,
+ pub glyph_recent: Vec<String>,
+ pub glyph_selected: Option<String>,
+ /// Edit › Check Spelling dialog.
+ pub spell: Option<SpellDialog>,
+}
+
+/// State of the Check Spelling dialog.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct SpellDialog {
+ /// Misspellings from `edit.checkSpelling` (layer, start, end, word, suggestions).
+ pub items: Vec<Value>,
+ pub index: usize,
+ /// Ignore All words for this check.
+ pub ignore: Vec<String>,
+ pub change_to: String,
+ pub all_layers: bool,
+ pub message: String,
+}
+
+const IDS: [&str; 6] = ["type.panels.characterStyles", "window.panel.characterStyles", "type.panels.paragraphStyles", "window.panel.paragraphStyles", "type.panels.glyphs", "window.panel.glyphs"];
+
+/// Menu ids handled here (live menu items).
+pub fn handles(id: &str) -> bool {
+ IDS.contains(&id)
+}
+
+pub fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ let p = &app.ui.type_panels;
+ Some(match id {
+ "type.panels.characterStyles" | "window.panel.characterStyles" => p.styles && p.styles_tab == 0,
+ "type.panels.paragraphStyles" | "window.panel.paragraphStyles" => p.styles && p.styles_tab == 1,
+ "type.panels.glyphs" | "window.panel.glyphs" => p.glyphs,
+ _ => return None,
+ })
+}
+
+/// Window/Type › panel toggles, and Edit › Check Spelling… (opens the dialog when run without an
+/// `action`). `params.show` forces a panel open or closed.
+pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if id == "edit.checkSpelling" && params.get("action").is_none() && params.get("ui").is_none_or(|u| u.as_bool() != Some(false)) {
+ return Some(open_spelling(app, params.get("allLayers").and_then(Value::as_bool).unwrap_or(true)));
+ }
+ if !handles(id) {
+ return None;
+ }
+ let want = params.get("show").and_then(Value::as_bool);
+ let p = &mut app.ui.type_panels;
+ let visible = if id.ends_with("glyphs") {
+ p.glyphs = want.unwrap_or(!p.glyphs);
+ p.glyphs
+ } else {
+ let tab = usize::from(id.ends_with("paragraphStyles"));
+ let showing = p.styles && p.styles_tab == tab;
+ // `{"options": styleId}` opens the panel with that style's Style Options.
+ let options = params.get("options").and_then(Value::as_u64).map(|o| (tab == 1, o as u32));
+ let show = if options.is_some() { true } else { want.unwrap_or(!showing) };
+ if options.is_some() {
+ p.options = options;
+ }
+ if show {
+ p.styles = true;
+ p.styles_tab = tab;
+ } else if p.styles_tab == tab {
+ p.styles = false;
+ }
+ show
+ };
+ Some(Ok(json!({ "visible": visible })))
+}
+
+fn run(app: &mut PhotocraftApp, id: &str, p: Value) -> Option<Value> {
+ match app.run(id, p) {
+ Ok(v) => Some(v),
+ Err(e) => {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ None
+ }
+ }
+}
+
+/// The type the panels act on: the layer being edited (with its selection), else the selected
+/// layers. Returns params with `layer` + `range`, or `{}` (selected layers).
+fn target(app: &PhotocraftApp) -> Value {
+ if let Some(ed) = &app.ui.text_edit {
+ let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));
+ return json!({ "layer": ed.layer, "range": [a, b], "coalesce": ed.session });
+ }
+ json!({})
+}
+
+fn float_frame(t: &Tokens) -> egui::Frame {
+ egui::Frame::NONE
+ .fill(t.card)
+ .stroke(Stroke::new(1.0, t.card_border))
+ .corner_radius(CornerRadius::same(t.radius_lg as u8))
+ .shadow(egui::Shadow { offset: [0, 10], blur: 30, spread: 0, color: t.shadow })
+ .inner_margin(egui::Margin::same(8))
+}
+
+/// Draws the open type panels and the spelling dialog.
+pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let t = Tokens::get(ctx);
+ let canvas = app.last_canvas_rect;
+ if app.ui.type_panels.styles {
+ let mut close = false;
+ egui::Window::new("Type Styles")
+ .id(egui::Id::new("type-styles-window"))
+ .title_bar(false)
+ .resizable(false)
+ .frame(float_frame(&t))
+ .default_pos(pos2((canvas.right() - 314.0).max(canvas.left() + 8.0), canvas.top() + 40.0))
+ .show(ctx, |ui| {
+ ui.set_width(290.0);
+ ui.horizontal(|ui| {
+ let mut tab = app.ui.type_panels.styles_tab;
+ for (i, name) in ["Character Styles", "Paragraph Styles"].iter().enumerate() {
+ if crate::widgets::pill_tab(ui, name, tab == i).clicked() {
+ tab = i;
+ }
+ }
+ if tab != app.ui.type_panels.styles_tab {
+ app.ui.type_panels.styles_tab = tab;
+ app.ui.type_panels.options = None;
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "x", 20.0, false, "Close").clicked() {
+ close = true;
+ }
+ });
+ });
+ crate::widgets::hairline(ui);
+ ui.add_space(4.0);
+ styles_panel(app, ui, app.ui.type_panels.styles_tab == 1);
+ });
+ if close {
+ app.ui.type_panels.styles = false;
+ }
+ }
+ if app.ui.type_panels.glyphs {
+ let mut close = false;
+ egui::Window::new("Glyphs")
+ .id(egui::Id::new("glyphs-window"))
+ .title_bar(false)
+ .resizable(false)
+ .frame(float_frame(&t))
+ .default_pos(pos2((canvas.right() - 314.0 - 372.0).max(canvas.left() + 8.0), canvas.top() + 40.0))
+ .show(ctx, |ui| {
+ ui.set_width(340.0);
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Glyphs").color(t.text).size(12.0).strong());
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "x", 20.0, false, "Close").clicked() {
+ close = true;
+ }
+ });
+ });
+ crate::widgets::hairline(ui);
+ ui.add_space(4.0);
+ glyphs_panel(app, ui);
+ });
+ if close {
+ app.ui.type_panels.glyphs = false;
+ }
+ }
+ if app.ui.type_panels.spell.is_some() {
+ spelling_window(app, ctx);
+ }
+}
+
+// ------------------------------------------------------------------ styles
+
+pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool) {
+ let t = Tokens::get(ui.ctx());
+ if app.session.active().is_none() {
+ ui.label(RichText::new("No document").color(t.text_faint).size(11.5));
+ return;
+ }
+ let prefix = if paragraph { "type.paragraphStyle" } else { "type.characterStyle" };
+ let tgt = target(app);
+ let Ok(list) = app.session.execute(&format!("{prefix}.list"), tgt.clone()) else { return };
+ let styles = list["styles"].as_array().cloned().unwrap_or_default();
+ let cur = &list["current"];
+ let (cur_id, over) = if paragraph { (cur["paragraph"].as_u64(), cur["paragraphOverride"].as_bool().unwrap_or(false)) } else { (cur["character"].as_u64(), cur["characterOverride"].as_bool().unwrap_or(false)) };
+ let has_target = !cur.is_null();
+ let selected = app.ui.type_panels.options.filter(|o| o.0 == paragraph).map(|o| u64::from(o.1)).or(cur_id);
+ let mut action: Option<(String, Value)> = None;
+ let row_h = 22.0;
+ egui::ScrollArea::vertical().id_salt(("type-styles", paragraph)).max_height(220.0).auto_shrink([false, true]).show(ui, |ui| {
+ for s in &styles {
+ let id = s["id"].as_u64().unwrap_or(0);
+ let name = s["name"].as_str().unwrap_or("");
+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
+ let is_cur = has_target && cur_id == Some(id);
+ if is_cur {
+ ui.painter().rect_filled(rect, 0.0, t.row_selected);
+ } else if selected == Some(id) {
+ ui.painter().rect_filled(rect, 0.0, t.hover);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5));
+ }
+ let label = if is_cur && over { format!("{name}+") } else { name.to_string() };
+ let color = if id == 0 { t.text_dim } else { t.text };
+ ui.painter().text(pos2(rect.left() + 8.0, rect.center().y), Align2::LEFT_CENTER, label, egui::FontId::proportional(12.0), color);
+ if resp.double_clicked() && (id != 0 || paragraph) {
+ app.ui.type_panels.options = Some((paragraph, id as u32));
+ } else if resp.clicked() {
+ let alt = ui.input(|i| i.modifiers.alt);
+ if has_target {
+ let mut p = tgt.clone();
+ p["id"] = json!(id);
+ p["clearOverrides"] = json!(alt);
+ if !paragraph && p.get("range").and_then(Value::as_array).is_some_and(|r| r[0] == r[1]) {
+ app.ui.status = "Select text to apply a character style".into();
+ app.ui.status_error = false;
+ } else {
+ action = Some((format!("{prefix}.apply"), p));
+ }
+ }
+ if app.ui.type_panels.options.is_some_and(|o| o.0 == paragraph) {
+ app.ui.type_panels.options = Some((paragraph, id as u32));
+ }
+ }
+ resp.on_hover_text(if id == 0 && !paragraph { "No character style" } else { "Click to apply, ⌥-click to clear overrides, double-click for Style Options" });
+ }
+ });
+ ui.add_space(4.0);
+ crate::widgets::hairline(ui);
+ ui.add_space(2.0);
+ let sel = selected.filter(|i| *i != 0 || paragraph);
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ if crate::icons::button(ui, "ban", 22.0, false, "Clear Override").clicked() && has_target && over {
+ action = Some((format!("{prefix}.clearOverride"), tgt.clone()));
+ }
+ if crate::icons::button(ui, "check", 22.0, false, "Redefine style by current selection").clicked() && has_target && cur_id.is_some_and(|i| i != 0 || paragraph) {
+ action = Some((format!("{prefix}.redefine"), tgt.clone()));
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "trash", 22.0, false, "Delete style").clicked()
+ && let Some(id) = sel.filter(|i| *i != 0)
+ {
+ action = Some((format!("{prefix}.delete"), json!({ "id": id })));
+ app.ui.type_panels.options = None;
+ }
+ if crate::icons::button(ui, "plus", 22.0, false, "Create new style (from the selected type)").clicked() {
+ let mut p = tgt.clone();
+ p["fromSelection"] = json!(has_target);
+ action = Some((format!("{prefix}.new"), p));
+ }
+ if crate::icons::button(ui, "copy", 22.0, false, "Duplicate style").clicked()
+ && let Some(id) = sel
+ {
+ action = Some((format!("{prefix}.duplicate"), json!({ "id": id })));
+ }
+ if crate::icons::button(ui, "settings", 22.0, false, "Style Options…").clicked()
+ && let Some(id) = sel
+ {
+ app.ui.type_panels.options = Some((paragraph, id as u32));
+ }
+ });
+ });
+ if let Some((id, p)) = action
+ && let Some(r) = run(app, &id, p)
+ && id.ends_with(".new")
+ && let Some(nid) = r["id"].as_u64()
+ {
+ app.ui.type_panels.options = Some((paragraph, nid as u32));
+ }
+ if let Some((para, id)) = app.ui.type_panels.options
+ && para == paragraph
+ {
+ if let Some(s) = styles.iter().find(|s| s["id"].as_u64() == Some(u64::from(id))) {
+ ui.add_space(4.0);
+ crate::widgets::hairline(ui);
+ options_editor(app, ui, paragraph, s);
+ } else {
+ app.ui.type_panels.options = None;
+ }
+ }
+}
+
+/// Style Options: name plus the common attributes; a checkbox marks an attribute as part of the
+/// style (unchecked = inherited).
+fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s: &Value) {
+ let t = Tokens::get(ui.ctx());
+ let prefix = if paragraph { "type.paragraphStyle" } else { "type.characterStyle" };
+ let id = s["id"].as_u64().unwrap_or(0);
+ let (char_attrs, para_attrs) = if paragraph { (s["characterAttrs"].clone(), s["paragraphAttrs"].clone()) } else { (s["attrs"].clone(), Value::Null) };
+ let resolved_c = if paragraph { s["resolved"]["character"].clone() } else { s["resolved"].clone() };
+ let resolved_p = s["resolved"]["paragraph"].clone();
+ let mut set: Option<Value> = None;
+ let mut clear: Vec<&str> = Vec::new();
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Style Options").color(t.text).size(11.5).strong());
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if crate::icons::button(ui, "x", 18.0, false, "Close Style Options").clicked() {
+ app.ui.type_panels.options = None;
+ }
+ });
+ });
+ // Name.
+ let key = egui::Id::new(("style-name", paragraph, id));
+ let mut name: String = ui.data(|d| d.get_temp(key)).unwrap_or_else(|| s["name"].as_str().unwrap_or("").to_string());
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Name").color(t.text_dim).size(11.5));
+ let r = ui.add_enabled(id != 0, egui::TextEdit::singleline(&mut name).desired_width(170.0));
+ if r.lost_focus() && name.trim() != s["name"].as_str().unwrap_or("") && !name.trim().is_empty() {
+ let _ = run(app, &format!("{prefix}.rename"), json!({ "id": id, "name": name.trim() }));
+ ui.data_mut(|d| d.remove::<String>(key));
+ } else if r.changed() {
+ ui.data_mut(|d| d.insert_temp(key, name.clone()));
+ }
+ });
+ let defined = |attrs: &Value, k: &str| attrs.get(k).is_some();
+ egui::Grid::new(("style-opts", paragraph, id)).num_columns(3).spacing([6.0, 3.0]).show(ui, |ui| {
+ // (label, model key, panel key, kind)
+ let rows: &[(&str, &str, &str, &str)] = &[
+ ("Font", "font_family", "font", "font"),
+ ("Size", "size_pt", "size", "pt"),
+ ("Leading", "leading_pt", "leading", "leading"),
+ ("Tracking", "tracking", "tracking", "num"),
+ ("Baseline", "baseline_shift_pt", "baselineShift", "pt"),
+ ("Color", "color", "color", "color"),
+ ("Faux Bold", "faux_bold", "fauxBold", "bool"),
+ ("Faux Italic", "faux_italic", "fauxItalic", "bool"),
+ ("Underline", "underline", "underline", "bool"),
+ ("Strikethrough", "strikethrough", "strikethrough", "bool"),
+ ];
+ for &(label, key, panel, kind) in rows {
+ let mut on = defined(&char_attrs, key);
+ let was = on;
+ ui.checkbox(&mut on, "");
+ ui.label(RichText::new(label).color(if on { t.text } else { t.text_faint }).size(11.5));
+ let v = if on { char_attrs[key].clone() } else { resolved_c[key].clone() };
+ ui.add_enabled_ui(on, |ui| match kind {
+ "font" => {
+ let mut f = v.as_str().unwrap_or("").to_string();
+ if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f) {
+ set = Some(json!({ panel: f }));
+ }
+ }
+ "pt" | "num" | "leading" => {
+ let auto = kind == "leading" && v.is_null();
+ let mut x = v.as_f64().unwrap_or(0.0) as f32;
+ let range = if kind == "num" { -1000.0..=10000.0 } else { -1296.0..=1296.0 };
+ let unit = if kind == "num" { "" } else { " pt" };
+ if auto {
+ ui.label(RichText::new("Auto").color(t.text_dim).size(11.5));
+ } else if crate::widgets::value_field(ui, &mut x, range, unit, 70.0).changed() {
+ set = Some(json!({ key: x }));
+ }
+ }
+ "color" => {
+ let c = serde_json::from_value::<photocraft_doc::Color>(v.clone()).map(|c| c.to_rgb()).unwrap_or([0.0; 3]);
+ // Style colours are stored encoded (like the Color panel's hex), not linear.
+ let h = |f: f32| (f.clamp(0.0, 1.0) * 255.0).round() as u8;
+ let mut rgb = c.map(h);
+ if ui.color_edit_button_srgb(&mut rgb).changed() {
+ set = Some(json!({ "color": format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]) }));
+ }
+ }
+ _ => {
+ let mut b = v.as_bool().unwrap_or(false);
+ if ui.checkbox(&mut b, "").changed() {
+ set = Some(json!({ key: b }));
+ }
+ }
+ });
+ ui.end_row();
+ if on != was {
+ if on {
+ set = Some(json!({ key: resolved_c[key].clone() }));
+ } else {
+ clear.push(key);
+ }
+ }
+ }
+ if paragraph {
+ let rows: &[(&str, &str, &str)] = &[("Align", "align", "align"), ("Indent First", "first_line_indent_pt", "pt"), ("Indent Left", "start_indent_pt", "pt"), ("Indent Right", "end_indent_pt", "pt"), ("Space Before", "space_before_pt", "pt"), ("Space After", "space_after_pt", "pt"), ("Hyphenate", "hyphenate", "bool")];
+ for &(label, key, kind) in rows {
+ let mut on = defined(&para_attrs, key);
+ let was = on;
+ ui.checkbox(&mut on, "");
+ ui.label(RichText::new(label).color(if on { t.text } else { t.text_faint }).size(11.5));
+ let v = if on { para_attrs[key].clone() } else { resolved_p[key].clone() };
+ ui.add_enabled_ui(on, |ui| match kind {
+ "align" => {
+ let mut a = v.as_str().unwrap_or("Left").to_string();
+ let opts = ["Left", "Center", "Right", "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyAll"].map(|o| (o.to_string(), o));
+ let opts: Vec<(String, &str)> = opts.to_vec();
+ if crate::widgets::dropdown(ui, &format!("style-align-{id}"), &mut a, &opts, 110.0) {
+ set = Some(json!({ "align": a }));
+ }
+ }
+ "pt" => {
+ let mut x = v.as_f64().unwrap_or(0.0) as f32;
+ if crate::widgets::value_field(ui, &mut x, -1296.0..=1296.0, " pt", 70.0).changed() {
+ set = Some(json!({ key: x }));
+ }
+ }
+ _ => {
+ let mut b = v.as_bool().unwrap_or(false);
+ if ui.checkbox(&mut b, "").changed() {
+ set = Some(json!({ key: b }));
+ }
+ }
+ });
+ ui.end_row();
+ if on != was {
+ if on {
+ set = Some(json!({ key: resolved_p[key].clone() }));
+ } else {
+ clear.push(key);
+ }
+ }
+ }
+ }
+ });
+ if let Some(attrs) = set {
+ let _ = run(app, &format!("{prefix}.set"), json!({ "id": id, "attrs": attrs }));
+ }
+ if !clear.is_empty() {
+ let mut c: Vec<&str> = clear.clone();
+ if c.contains(&"font_family") {
+ c.extend(["font_style", "postscript_name", "weight", "italic"]);
+ }
+ let _ = run(app, &format!("{prefix}.set"), json!({ "id": id, "clear": c }));
+ }
+}
+
+/// Searchable family combo box.
+fn family_picker(ui: &mut egui::Ui, salt: &str, current: &mut String) -> bool {
+ let mut changed = false;
+ let search_id = egui::Id::new(("family-search", salt));
+ let shown = if current.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { current.clone() };
+ egui::ComboBox::from_id_salt(salt).selected_text(shown.clone()).width(140.0).height(360.0).icon(crate::widgets::chevron_icon).show_ui(ui, |ui| {
+ let mut q: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default();
+ let r = ui.add(egui::TextEdit::singleline(&mut q).hint_text("Search fonts").desired_width(180.0));
+ if !r.has_focus() && q.is_empty() {
+ r.request_focus();
+ }
+ ui.data_mut(|d| d.insert_temp(search_id, q.clone()));
+ let ql = q.to_lowercase();
+ for f in crate::type_tool::families().iter().filter(|f| ql.is_empty() || f.to_lowercase().contains(&ql)) {
+ if ui.selectable_label(*f == shown, f).clicked() {
+ *current = f.clone();
+ changed = true;
+ ui.data_mut(|d| d.remove::<String>(search_id));
+ }
+ }
+ });
+ changed
+}
+
+// ------------------------------------------------------------------ glyphs
+
+/// Font family/style the Glyphs panel shows: its own choice, else the type selection's font.
+fn glyph_font(app: &PhotocraftApp) -> (String, String) {
+ let p = &app.ui.type_panels;
+ if !p.glyph_family.is_empty() {
+ return (p.glyph_family.clone(), if p.glyph_style.is_empty() { "Regular".into() } else { p.glyph_style.clone() });
+ }
+ let layer = app.ui.text_edit.as_ref().map(|e| photocraft_doc::LayerId(e.layer)).or_else(|| app.session.active().and_then(|s| s.active_layer));
+ if let Some(st) = app.session.active()
+ && let Some(id) = layer
+ && let Some(photocraft_doc::LayerContent::Text(tl)) = st.doc.layer(id).map(|l| &l.content)
+ && let Some(r) = tl.char_runs().first()
+ {
+ let fam = if r.style.font_family.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { r.style.font_family.clone() };
+ let style = if r.style.font_style.is_empty() { if r.style.italic { "Italic".into() } else { "Regular".into() } } else { r.style.font_style.clone() };
+ return (fam, style);
+ }
+ (photocraft_text::fonts::DEFAULT_FAMILY.into(), "Regular".into())
+}
+
+fn char_style_for(family: &str, style: &str) -> photocraft_doc::text::CharStyle {
+ let mut st = photocraft_doc::text::CharStyle { font_family: family.into(), ..Default::default() };
+ photocraft_engine::type_cmds::apply_char_props(&mut st, &json!({ "fontStyle": style }));
+ st
+}
+
+fn glyph_texture(ctx: &egui::Context, family: &str, style: &str, c: char, px: u32) -> TextureHandle {
+ let id = egui::Id::new(("glyph-tex", family, style, c, px));
+ if let Some(t) = ctx.data(|d| d.get_temp::<TextureHandle>(id)) {
+ return t;
+ }
+ let st = char_style_for(family, style);
+ let (n, alpha) = {
+ let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());
+ photocraft_text::glyphs::preview(&mut eng, &st, c, px)
+ };
+ let img = egui::ColorImage::from_rgba_unmultiplied([n as usize, n as usize], &alpha.iter().flat_map(|a| [255, 255, 255, *a]).collect::<Vec<u8>>());
+ let tex = ctx.load_texture(format!("glyph-{c}-{px}"), img, TextureOptions::LINEAR);
+ ctx.data_mut(|d| d.insert_temp(id, tex.clone()));
+ tex
+}
+
+/// Characters of a face, cached per (family, style).
+fn charmap(ctx: &egui::Context, family: &str, style: &str) -> std::sync::Arc<Vec<char>> {
+ let id = egui::Id::new(("glyph-cmap", family, style));
+ if let Some(v) = ctx.data(|d| d.get_temp::<std::sync::Arc<Vec<char>>>(id)) {
+ return v;
+ }
+ let st = char_style_for(family, style);
+ let v = std::sync::Arc::new(photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.charmap(family, st.weight, st.italic));
+ ctx.data_mut(|d| d.insert_temp(id, v.clone()));
+ v
+}
+
+/// Inserts `g` into the type being edited (replacing the selection), else at the end of the
+/// active type layer. Returns whether it was inserted.
+pub fn insert_glyph(app: &mut PhotocraftApp, g: &str) -> bool {
+ let p = if let Some(ed) = app.ui.text_edit.clone() {
+ let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));
+ json!({ "layer": ed.layer, "text": g, "range": [a, b], "coalesce": ed.session })
+ } else {
+ json!({ "text": g })
+ };
+ let Some(r) = run(app, "type.insertText", p) else { return false };
+ if let (Some(e), Some(c)) = (app.ui.text_edit.as_mut(), r["caret"].as_u64()) {
+ e.caret = c as usize;
+ e.anchor = e.caret;
+ }
+ let rec = &mut app.ui.type_panels.glyph_recent;
+ rec.retain(|x| x != g);
+ rec.insert(0, g.to_string());
+ rec.truncate(12);
+ true
+}
+
+pub fn glyphs_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let t = Tokens::get(ui.ctx());
+ let ctx = ui.ctx().clone();
+ let (family, style) = glyph_font(app);
+ // Font family + style.
+ ui.horizontal(|ui| {
+ let mut f = family.clone();
+ if family_picker(ui, "glyph-family", &mut f) {
+ app.ui.type_panels.glyph_family = f;
+ app.ui.type_panels.glyph_style = "Regular".into();
+ }
+ let styles = crate::type_tool::styles(&family);
+ let mut s = style.clone();
+ let opts: Vec<(String, &str)> = styles.iter().map(|x| (x.clone(), x.as_str())).collect();
+ if crate::widgets::dropdown(ui, "glyph-style", &mut s, &opts, 110.0) {
+ app.ui.type_panels.glyph_family = family.clone();
+ app.ui.type_panels.glyph_style = s;
+ }
+ });
+ // Show: category.
+ let mut cat = if app.ui.type_panels.glyph_category.is_empty() { "Entire Font".to_string() } else { app.ui.type_panels.glyph_category.clone() };
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Show:").color(t.text_dim).size(11.5));
+ let opts: Vec<(String, &str)> = photocraft_text::glyphs::CATEGORIES.iter().map(|c| (c.to_string(), *c)).collect();
+ if crate::widgets::dropdown(ui, "glyph-category", &mut cat, &opts, 160.0) {
+ app.ui.type_panels.glyph_category = cat.clone();
+ }
+ });
+ let size = if app.ui.type_panels.glyph_size <= 0.0 { 32.0 } else { app.ui.type_panels.glyph_size };
+ let ppp = ctx.pixels_per_point();
+ let px = ((size - 6.0) * ppp).round().max(8.0) as u32;
+ let mut clicked: Option<String> = None;
+ let mut activated: Option<String> = None;
+ // Recently used.
+ let recent = app.ui.type_panels.glyph_recent.clone();
+ ui.add_space(2.0);
+ ui.label(RichText::new("Recently Used").color(t.text_faint).size(10.5));
+ let (rr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::hover());
+ ui.painter().rect_filled(rr, 2.0, t.field);
+ for (i, g) in recent.iter().enumerate() {
+ let cell = Rect::from_min_size(pos2(rr.left() + 2.0 + i as f32 * 26.0, rr.top() + 1.0), vec2(24.0, 24.0));
+ if cell.right() > rr.right() {
+ break;
+ }
+ let resp = ui.interact(cell, ui.id().with(("glyph-recent", i)), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(cell, 2.0, t.hover);
+ }
+ if let Some(c) = g.chars().next() {
+ let tex = glyph_texture(&ctx, &family, &style, c, (20.0 * ppp) as u32);
+ ui.painter().image(tex.id(), cell.shrink(2.0), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), t.text);
+ }
+ if resp.double_clicked() || resp.clicked() {
+ activated = Some(g.clone());
+ }
+ }
+ ui.add_space(4.0);
+ // Grid.
+ let cmap = charmap(&ctx, &family, &style);
+ let chars: Vec<char> = cmap.iter().copied().filter(|c| photocraft_text::glyphs::in_category(*c, &cat)).collect();
+ // Leave room for the scroll bar.
+ let width = ui.available_width() - 12.0;
+ let cols = ((width / size).floor() as usize).max(1);
+ let rows = chars.len().div_ceil(cols);
+ let selected = app.ui.type_panels.glyph_selected.clone();
+ egui::ScrollArea::vertical().id_salt("glyph-grid").max_height(260.0).auto_shrink([false, false]).show_rows(ui, size, rows, |ui, range| {
+ for row in range {
+ let (rect, _) = ui.allocate_exact_size(vec2(width, size), Sense::hover());
+ for col in 0..cols {
+ let Some(&c) = chars.get(row * cols + col) else { break };
+ let cell = Rect::from_min_size(pos2(rect.left() + col as f32 * size, rect.top()), vec2(size, size));
+ let resp = ui.interact(cell, ui.id().with(("glyph", c)), Sense::click());
+ let is_sel = selected.as_deref().and_then(|s| s.chars().next()) == Some(c);
+ ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Inside);
+ if is_sel {
+ ui.painter().rect_filled(cell.shrink(1.0), 0.0, t.accent);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(cell.shrink(1.0), 0.0, t.hover);
+ }
+ let tex = glyph_texture(&ctx, &family, &style, c, px);
+ let tint = if is_sel { Color32::WHITE } else { t.text };
+ ui.painter().image(tex.id(), cell.shrink(3.0), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint);
+ let resp = resp.on_hover_text(format!("U+{:04X}", c as u32));
+ if resp.double_clicked() {
+ activated = Some(c.to_string());
+ } else if resp.clicked() {
+ clicked = Some(c.to_string());
+ }
+ }
+ }
+ });
+ // Footer: family name, size slider.
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ let info = selected.as_deref().and_then(|s| s.chars().next()).map(|c| format!("U+{:04X} · {} glyphs", c as u32, chars.len())).unwrap_or_else(|| format!("{} glyphs", chars.len()));
+ ui.label(RichText::new(info).color(t.text_faint).size(10.5));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let mut s = size;
+ ui.add_sized([90.0, 16.0], egui::Slider::new(&mut s, 24.0..=64.0).show_value(false));
+ if (s - size).abs() > 0.1 {
+ app.ui.type_panels.glyph_size = s;
+ }
+ let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());
+ crate::icons::paint(ui, r, "zoom-in", 12.0, t.icon);
+ });
+ });
+ if let Some(c) = clicked {
+ app.ui.type_panels.glyph_selected = Some(c);
+ }
+ if let Some(g) = activated {
+ app.ui.type_panels.glyph_selected = Some(g.clone());
+ if !insert_glyph(app, &g) {
+ app.ui.status = "Select a type layer or click into text to insert glyphs".into();
+ }
+ }
+}
+
+// ------------------------------------------------------------------ spelling
+
+fn refresh_spelling(app: &mut PhotocraftApp) {
+ let Some(d) = app.ui.type_panels.spell.clone() else { return };
+ let p = json!({ "action": "list", "allLayers": d.all_layers, "ignore": d.ignore, "suggestions": 8 });
+ let items = run(app, "edit.checkSpelling", p).and_then(|r| r["misspellings"].as_array().cloned()).unwrap_or_default();
+ if let Some(s) = app.ui.type_panels.spell.as_mut() {
+ s.items = items;
+ s.change_to = s.items.get(s.index).and_then(|i| i["suggestions"][0].as_str()).unwrap_or("").to_string();
+ }
+}
+
+/// Opens Edit › Check Spelling (returns the misspellings).
+pub fn open_spelling(app: &mut PhotocraftApp, all_layers: bool) -> Result<Value, String> {
+ app.session.execute("edit.checkSpelling", json!({ "action": "list", "allLayers": all_layers })).map_err(|e| e.to_string())?;
+ app.ui.type_panels.spell = Some(SpellDialog { all_layers, ..Default::default() });
+ refresh_spelling(app);
+ let d = app.ui.type_panels.spell.as_ref().map(|d| d.items.clone()).unwrap_or_default();
+ Ok(json!({ "dialog": "checkSpelling", "misspellings": d }))
+}
+
+fn spelling_window(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let t = Tokens::get(ctx);
+ let Some(d) = app.ui.type_panels.spell.clone() else { return };
+ let item = d.items.get(d.index).cloned();
+ let mut act: Option<&str> = None;
+ let mut change_to = d.change_to.clone();
+ let mut all_layers = d.all_layers;
+ egui::Window::new("Check Spelling")
+ .id(egui::Id::new("check-spelling"))
+ .collapsible(false)
+ .resizable(false)
+ .frame(float_frame(&t).inner_margin(egui::Margin::same(14)))
+ .title_bar(false)
+ .anchor(Align2::CENTER_CENTER, vec2(0.0, -40.0))
+ .show(ctx, |ui| {
+ ui.set_width(380.0);
+ ui.label(RichText::new("Check Spelling").color(t.text).size(13.0).strong());
+ ui.add_space(6.0);
+ ui.horizontal_top(|ui| {
+ ui.vertical(|ui| {
+ ui.set_width(250.0);
+ ui.label(RichText::new("Not in Dictionary:").color(t.text_dim).size(11.5));
+ let word = item.as_ref().and_then(|i| i["word"].as_str()).unwrap_or("");
+ let shown = if item.is_some() { word.to_string() } else if d.items.is_empty() || d.index >= d.items.len() { "".into() } else { String::new() };
+ ui.add_enabled(false, egui::TextEdit::singleline(&mut shown.clone()).desired_width(240.0));
+ ui.add_space(4.0);
+ ui.label(RichText::new("Change To:").color(t.text_dim).size(11.5));
+ ui.add_enabled(item.is_some(), egui::TextEdit::singleline(&mut change_to).desired_width(240.0));
+ ui.add_space(4.0);
+ ui.label(RichText::new("Suggestions:").color(t.text_dim).size(11.5));
+ egui::Frame::NONE.fill(t.field).corner_radius(CornerRadius::same(3)).inner_margin(egui::Margin::same(4)).show(ui, |ui| {
+ ui.set_min_size(vec2(240.0, 110.0));
+ egui::ScrollArea::vertical().id_salt("spell-sugg").max_height(110.0).show(ui, |ui| {
+ for s in item.as_ref().and_then(|i| i["suggestions"].as_array()).into_iter().flatten() {
+ let s = s.as_str().unwrap_or("");
+ let r = ui.selectable_label(s == change_to, s);
+ if r.clicked() {
+ change_to = s.to_string();
+ }
+ if r.double_clicked() {
+ change_to = s.to_string();
+ act = Some("change");
+ }
+ }
+ });
+ });
+ ui.add_space(4.0);
+ if crate::widgets::checkbox(ui, &mut all_layers, "Check All Layers").changed() {
+ act = Some("relist");
+ }
+ let msg = if item.is_none() { "Spell check complete." } else { "" };
+ if !msg.is_empty() {
+ ui.label(RichText::new(msg).color(t.text).size(11.5));
+ }
+ });
+ ui.vertical(|ui| {
+ ui.spacing_mut().item_spacing.y = 4.0;
+ if crate::widgets::primary_button(ui, "Done", 100.0).clicked() {
+ act = Some("done");
+ }
+ ui.add_space(6.0);
+ ui.add_enabled_ui(item.is_some(), |ui| {
+ for (label, a) in [("Ignore", "ignore"), ("Ignore All", "ignoreAll"), ("Change", "change"), ("Change All", "changeAll"), ("Add", "add")] {
+ if crate::widgets::secondary_button(ui, label, 100.0).clicked() {
+ act = Some(a);
+ }
+ }
+ });
+ });
+ });
+ });
+ if let Some(s) = app.ui.type_panels.spell.as_mut() {
+ s.change_to = change_to.clone();
+ s.all_layers = all_layers;
+ }
+ let Some(a) = act else { return };
+ let word = item.as_ref().and_then(|i| i["word"].as_str()).unwrap_or("").to_string();
+ match a {
+ "done" => app.ui.type_panels.spell = None,
+ "relist" => {
+ if let Some(s) = app.ui.type_panels.spell.as_mut() {
+ s.index = 0;
+ }
+ refresh_spelling(app);
+ }
+ "ignore" => {
+ if let Some(s) = app.ui.type_panels.spell.as_mut() {
+ s.index += 1;
+ s.change_to = s.items.get(s.index).and_then(|i| i["suggestions"][0].as_str()).unwrap_or("").to_string();
+ }
+ }
+ "ignoreAll" => {
+ if let Some(s) = app.ui.type_panels.spell.as_mut() {
+ s.ignore.push(word);
+ }
+ refresh_spelling(app);
+ }
+ "add" => {
+ let _ = run(app, "edit.checkSpelling", json!({ "action": "addToDictionary", "word": word }));
+ refresh_spelling(app);
+ }
+ "change" | "changeAll" => {
+ if let Some(i) = &item {
+ let p = if a == "change" {
+ json!({ "action": "change", "layer": i["layer"], "start": i["start"], "end": i["end"], "word": word, "replace": change_to })
+ } else {
+ json!({ "action": "changeAll", "word": word, "replace": change_to, "allLayers": all_layers })
+ };
+ let _ = run(app, "edit.checkSpelling", p);
+ refresh_spelling(app);
+ }
+ }
+ _ => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn app_with_text(text: &str) -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 300, "height": 120, "background": "white"})).unwrap();
+ app.run("type.create", json!({"x": 10, "y": 60, "text": text})).unwrap();
+ app.sync_views();
+ app
+ }
+
+ #[test]
+ fn menu_toggles_panels() {
+ let mut app = app_with_text("Hi");
+ assert!(handles("window.panel.glyphs") && crate::menus::is_live("type.panels.paragraphStyles"));
+ menu(&mut app, "type.panels.paragraphStyles", &json!({})).unwrap().unwrap();
+ assert!(app.ui.type_panels.styles && app.ui.type_panels.styles_tab == 1);
+ assert_eq!(checked(&app, "window.panel.paragraphStyles"), Some(true));
+ assert_eq!(checked(&app, "window.panel.characterStyles"), Some(false));
+ menu(&mut app, "window.panel.characterStyles", &json!({})).unwrap().unwrap();
+ assert_eq!(app.ui.type_panels.styles_tab, 0);
+ menu(&mut app, "window.panel.characterStyles", &json!({})).unwrap().unwrap();
+ assert!(!app.ui.type_panels.styles);
+ menu(&mut app, "window.panel.glyphs", &json!({"show": true})).unwrap().unwrap();
+ assert!(app.ui.type_panels.glyphs);
+ }
+
+ #[test]
+ fn glyph_insertion_and_recent() {
+ let mut app = app_with_text("ab");
+ assert!(insert_glyph(&mut app, "→"));
+ assert!(insert_glyph(&mut app, "€"));
+ assert!(insert_glyph(&mut app, "→"));
+ assert_eq!(app.ui.type_panels.glyph_recent, vec!["→".to_string(), "€".to_string()]);
+ let st = app.session.active().unwrap();
+ let Some(photocraft_doc::LayerContent::Text(t)) = st.active_layer.and_then(|id| st.doc.layer(id)).map(|l| &l.content) else { panic!() };
+ assert_eq!(t.text, "ab→€→");
+ }
+
+ #[test]
+ fn spelling_dialog_flow() {
+ let mut app = app_with_text("Teh cat");
+ let r = menu(&mut app, "edit.checkSpelling", &json!({})).unwrap().unwrap();
+ assert_eq!(r["misspellings"].as_array().unwrap().len(), 1);
+ let d = app.ui.type_panels.spell.clone().unwrap();
+ assert_eq!(d.change_to, "The");
+ // Headless calls with an action go to the engine.
+ assert!(menu(&mut app, "edit.checkSpelling", &json!({"action": "list"})).is_none());
+ }
+}
diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs
index 8edc7c058..9649d432a 100644
--- a/crates/ui-egui/src/vector_ui.rs
+++ b/crates/ui-egui/src/vector_ui.rs
@@ -22,7 +22,7 @@ pub struct PenPath {
}
pub fn is_shape_tool(t: Tool) -> bool {
- matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line)
+ matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape)
}
fn hex(c: [f32; 4]) -> String {
@@ -64,6 +64,11 @@ pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [
if rect[2] < 1.0 || rect[3] < 1.0 {
return;
}
+ if tool == Tool::CustomShape {
+ // ⇧ keeps the shape's proportions (the rect is already squared).
+ crate::preset_panels::finish_custom_shape(app, rect, mods.shift, fill, stroke);
+ return;
+ }
match tool {
Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4], "fill": fill, "stroke": stroke}),
Tool::Rectangle => json!({"kind": "rect", "rect": rect, "fill": fill, "stroke": stroke}),
@@ -320,6 +325,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
lbl(ui, "Weight:");
crate::widgets::value_field(ui, &mut o.line_weight, 1.0..=1000.0, "px", 58.0);
}
+ Tool::CustomShape => {
+ crate::widgets::vline(ui, 22.0);
+ crate::preset_panels::shape_picker(app, ui);
+ }
_ => {}
}
true
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
index 253585551..d5f5693aa 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -124,6 +124,10 @@ const LAYOUTS: [&str; 10] = ["tileAllVertically", "tileAllHorizontally", "twoUpV
/// Pixel aspect ratio (width / height of a pixel) of a preset id.
pub fn pixel_aspect_ratio(id: &str) -> f32 {
+ // View › Pixel Aspect Ratio › Custom: `custom:<ratio>:<name>` (see `workspace_ui`).
+ if let Some(r) = id.strip_prefix("custom:").and_then(|r| r.split(':').next()?.parse::<f32>().ok()) {
+ return r;
+ }
match id {
"d1DvNtsc" => 0.91,
"d1DvPal" => 1.09,
@@ -366,6 +370,9 @@ fn wraps(id: &str) -> bool {
| "file.automate.batch"
| "file.scripts.imageProcessor"
| "file.scripts.loadFilesIntoStack"
+ | "file.automate.photomerge"
+ | "file.automate.mergeToHdrPro"
+ | "file.automate.lensCorrection"
| "file.export.layersToFiles"
| "file.export.layerCompsToFiles"
| "file.export.artboardsToFiles"
@@ -794,6 +801,22 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
dialog(app, json!({"path": format!("{dir}/{stem}.cube"), "size": 33, "title": stem}), json!({}))
}
"file.scripts.loadFilesIntoStack" => dialog(app, json!({"paths": dir}), json!({})),
+ // Photography automation (photo_cmds / lens_cmds): a folder (or the open documents).
+ "file.automate.photomerge" => dialog(
+ app,
+ json!({"paths": dir, "useOpenDocuments": false, "layout": "auto", "blend": true, "vignetteRemoval": false, "geometricCorrection": false, "contentAwareFill": false}),
+ json!({"layout": ["auto", "perspective", "cylindrical", "spherical", "collage", "reposition"]}),
+ ),
+ "file.automate.mergeToHdrPro" => dialog(
+ app,
+ json!({"paths": dir, "useOpenDocuments": false, "align": true, "removeGhosts": false, "mode": "32", "method": "localAdaptation", "radius": 7.0, "strength": 0.52, "gamma": 1.0, "exposure": 0.0, "detail": 30.0, "saturation": 20.0}),
+ json!({"mode": ["32", "16", "8"], "method": ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"]}),
+ ),
+ "file.automate.lensCorrection" => dialog(
+ app,
+ json!({"input": dir, "output": format!("{dir}/corrected"), "format": "same", "profile": "auto", "correctDistortion": true, "correctVignette": true, "correctCA": true, "autoScale": true, "edge": "transparency"}),
+ json!({"format": ["same", "png", "jpg", "psd", "tiff"], "profile": ["auto", "generic", "none"], "edge": ["transparency", "edgeExtension", "black", "white"]}),
+ ),
"file.scripts.imageProcessor" => dialog(app, json!({"input": dir, "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}), json!({"format": ["jpg", "png", "psd", "tiff"]})),
"file.automate.batch" => {
let a = &app.ui.actions;
diff --git a/crates/ui-egui/src/wide_angle_ui.rs b/crates/ui-egui/src/wide_angle_ui.rs
new file mode 100644
index 000000000..6b12ac269
--- /dev/null
+++ b/crates/ui-egui/src/wide_angle_ui.rs
@@ -0,0 +1,377 @@
+//! Filter › Adaptive Wide Angle…: a full-window dialog like Photoshop's. Drag on the image to
+//! draw a constraint (the scene line between the two points, curved by the lens model); hold
+//! Shift when releasing to make it horizontal or vertical; right-click a constraint to delete
+//! it. The right panel holds the correction model, focal length, crop factor, scale and the
+//! constraint list. The preview solves the mesh warp on a CPU proxy (≤ 800 px); OK runs
+//! `filter.adaptiveWideAngle` with the constraints in document pixels.
+//!
+//! Control channel: `ui.menu.invoke {"id":"filter.adaptiveWideAngle","params":{"ui":{"set":{…},
+//! "add":{"a":[x,y],"b":[x,y],"orientation":"…"}, "remove":i, "commit":true | "cancel":true}}}`.
+
+use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};
+use photocraft_algo::transform::Interp;
+use photocraft_algo::wideangle::{self, Camera, Constraint, Orientation, WideAngle, WideModel};
+use photocraft_color::PixelFormat;
+use photocraft_doc::LayerId;
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+use crate::widgets;
+
+const PROXY_SIDE: usize = 800;
+const PANEL_W: f32 = 300.0;
+
+pub struct WideAngleDialog {
+ pub layer: LayerId,
+ layer_name: String,
+ pub params: WideAngle,
+ /// Canvas frame (document px) and the proxy scale (proxy px per document px).
+ frame: Rect,
+ scale: f64,
+ proxy: Surface,
+ pw: usize,
+ ph: usize,
+ src_tex: Option<TextureHandle>,
+ out_tex: Option<TextureHandle>,
+ dirty: bool,
+ pub preview: bool,
+ drag: Option<([f64; 2], [f64; 2])>,
+ pub residual: f64,
+ pub render_ms: f64,
+}
+
+fn tex_image(s: &Surface, w: usize, h: usize) -> egui::ColorImage {
+ let mut row = vec![[0u8; 4]; w * h];
+ s.read_rgba8_into(Rect::new(0, 0, w as i32, h as i32), &mut row);
+ egui::ColorImage::new([w, h], row.iter().map(|p| Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3])).collect())
+}
+
+impl WideAngleDialog {
+ pub fn describe(&self) -> Value {
+ json!({"layer": self.layer.0, "params": serde_json::to_value(&self.params).unwrap_or(Value::Null), "proxy": [self.pw, self.ph], "residual": self.residual, "renderMs": self.render_ms, "preview": self.preview})
+ }
+
+ fn proxy_params(&self) -> WideAngle {
+ let k = self.scale;
+ let mut p = self.params.clone();
+ let (fx, fy) = (self.frame.x0 as f64, self.frame.y0 as f64);
+ p.constraints = p.constraints.iter().map(|c| Constraint { a: [(c.a[0] - fx) * k, (c.a[1] - fy) * k], b: [(c.b[0] - fx) * k, (c.b[1] - fy) * k], orientation: c.orientation }).collect();
+ p
+ }
+
+ fn render(&mut self, ctx: &egui::Context) {
+ let t0 = crate::gpu_canvas::now_ms();
+ let pf = Rect::new(0, 0, self.pw as i32, self.ph as i32);
+ let p = self.proxy_params();
+ let mesh = wideangle::solve(&p, pf);
+ self.residual = mesh.residual / self.scale;
+ let out = photocraft_algo::warp::warp_triangles(&self.proxy, pf, &mesh.verts, &mesh.triangles(), Interp::Bilinear);
+ let img = tex_image(&out, self.pw, self.ph);
+ match &mut self.out_tex {
+ Some(t) => t.set(img, egui::TextureOptions::LINEAR),
+ None => self.out_tex = Some(ctx.load_texture("awa-out", img, egui::TextureOptions::LINEAR)),
+ }
+ if self.src_tex.is_none() {
+ self.src_tex = Some(ctx.load_texture("awa-src", tex_image(&self.proxy, self.pw, self.ph), egui::TextureOptions::LINEAR));
+ }
+ self.render_ms = crate::gpu_canvas::now_ms() - t0;
+ self.dirty = false;
+ }
+
+ fn command_params(&self) -> Value {
+ let mut v = serde_json::to_value(&self.params).unwrap_or(json!({}));
+ v["layer"] = json!(self.layer.0);
+ v
+ }
+}
+
+pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {
+ photocraft_engine::commands::find("filter.adaptiveWideAngle").map(|c| (c.enabled)(&app.session)).unwrap_or(Err("unknown command".into()))?;
+ let (layer, surf, _) = crate::distort_ui::active_pixels(app)?;
+ let st = app.session.active().ok_or("no document")?;
+ let frame = st.doc.bounds();
+ let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default();
+ let (w, h) = (frame.width() as usize, frame.height() as usize);
+ let k = w.max(h).div_ceil(PROXY_SIDE).max(1);
+ let (pw, ph) = (w.div_ceil(k), h.div_ceil(k));
+ let proxy = photocraft_algo::resample::resize_surface(&surf.convert(PixelFormat::RGBA8), 1.0 / k as f64, 1.0 / k as f64, photocraft_algo::resample::Resample::Bilinear);
+ // Normalise the proxy to start at the origin.
+ let mut px = Surface::new(PixelFormat::RGBA8);
+ let src_r = Rect::new((frame.x0 as f64 / k as f64) as i32, (frame.y0 as f64 / k as f64) as i32, (frame.x0 as f64 / k as f64) as i32 + pw as i32, (frame.y0 as f64 / k as f64) as i32 + ph as i32);
+ px.write_region(Rect::new(0, 0, pw as i32, ph as i32), &proxy.read_region(src_r));
+ // EXIF focal length / crop factor, as the engine would resolve them.
+ let info = st.doc.metadata.exif.as_ref().map(|e| photocraft_algo::exif::read(e));
+ let params = photocraft_engine::lens_cmds::wide_params("filter.adaptiveWideAngle", &json!({}), info.as_ref()).unwrap_or_default();
+ let mut d = WideAngleDialog { layer, layer_name: name, params, frame, scale: 1.0 / k as f64, proxy: px, pw, ph, src_tex: None, out_tex: None, dirty: true, preview: true, drag: None, residual: 0.0, render_ms: 0.0 };
+ d.render(ctx);
+ app.wide_angle = Some(d);
+ Ok(())
+}
+
+fn parse_orientation(s: &str) -> Orientation {
+ match s {
+ "horizontal" => Orientation::Horizontal,
+ "vertical" => Orientation::Vertical,
+ _ => Orientation::Free,
+ }
+}
+
+pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if id != "filter.adaptiveWideAngle" {
+ return None;
+ }
+ if params.as_object().is_none_or(|o| o.is_empty()) {
+ return Some(open(app, ctx).map(|_| app.wide_angle.as_ref().map(|d| d.describe()).unwrap_or(Value::Null)));
+ }
+ let ui = params.get("ui")?;
+ if app.wide_angle.is_none()
+ && let Err(e) = open(app, ctx)
+ {
+ return Some(Err(e));
+ }
+ let d = app.wide_angle.as_mut()?;
+ if let Some(set) = ui.get("set") {
+ 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 {
+ c.insert(k.clone(), v.clone());
+ }
+ }
+ match serde_json::from_value::<WideAngle>(cur) {
+ Ok(p) => d.params = p,
+ Err(e) => return Some(Err(format!("bad Adaptive Wide Angle settings: {e}"))),
+ }
+ d.dirty = true;
+ }
+ if let Some(a) = ui.get("add") {
+ let pt = |k: &str| -> Option<[f64; 2]> { Some([a.get(k)?.get(0)?.as_f64()?, a.get(k)?.get(1)?.as_f64()?]) };
+ let (Some(pa), Some(pb)) = (pt("a"), pt("b")) else { return Some(Err("`add` needs a and b points".into())) };
+ d.params.constraints.push(Constraint { a: pa, b: pb, orientation: parse_orientation(a.get("orientation").and_then(Value::as_str).unwrap_or("free")) });
+ d.dirty = true;
+ }
+ if let Some(i) = ui.get("remove").and_then(Value::as_u64)
+ && (i as usize) < d.params.constraints.len()
+ {
+ d.params.constraints.remove(i as usize);
+ d.dirty = true;
+ }
+ if d.dirty {
+ d.render(ctx);
+ }
+ if ui.get("cancel").and_then(Value::as_bool) == Some(true) {
+ app.wide_angle = None;
+ return Some(Ok(json!({"cancelled": true})));
+ }
+ if ui.get("commit").and_then(Value::as_bool) == Some(true) {
+ return Some(commit(app));
+ }
+ Some(Ok(app.wide_angle.as_ref().map(|d| d.describe()).unwrap_or(Value::Null)))
+}
+
+fn commit(app: &mut PhotocraftApp) -> Result<Value, String> {
+ let d = app.wide_angle.take().ok_or("Adaptive Wide Angle isn't open")?;
+ app.run("filter.adaptiveWideAngle", d.command_params())
+}
+
+pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if app.wide_angle.is_none() {
+ return;
+ }
+ let t = Tokens::get(ctx);
+ let screen = ctx.content_rect();
+ let mut action: Option<&str> = None;
+ let shift = ctx.input(|i| i.modifiers.shift);
+ egui::Area::new(egui::Id::new("awa-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
+ let Some(d) = app.wide_angle.as_mut() else { return };
+ if d.dirty {
+ d.render(ctx);
+ }
+ let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover());
+ let painter = ui.painter().clone();
+ painter.rect_filled(full, 0.0, t.chrome);
+ let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0));
+ painter.rect_filled(title, 0.0, t.dock);
+ painter.text(title.center(), Align2::CENTER_CENTER, format!("Adaptive Wide Angle ({})", d.layer_name), FontId::proportional(13.0), t.text);
+ let footer_h = 48.0;
+ let body = ERect::from_min_max(pos2(full.left(), title.bottom()), pos2(full.right(), full.bottom() - footer_h));
+ let view = ERect::from_min_max(body.min, pos2(body.right() - PANEL_W, body.bottom())).shrink(16.0);
+ painter.rect_filled(view, 0.0, t.canvas);
+ let s = (view.width() / d.pw as f32).min(view.height() / d.ph as f32);
+ let img_r = ERect::from_center_size(view.center(), vec2(d.pw as f32 * s, d.ph as f32 * s));
+ // Screen ↔ document mapping.
+ let k = d.scale;
+ let (fx, fy) = (d.frame.x0 as f64, d.frame.y0 as f64);
+ let to_screen = |p: [f64; 2]| pos2(img_r.left() + ((p[0] - fx) * k) as f32 * s, img_r.top() + ((p[1] - fy) * k) as f32 * s);
+ let to_doc = |q: Pos2| [fx + ((q.x - img_r.left()) / s) as f64 / k, fy + ((q.y - img_r.top()) / s) as f64 / k];
+ let resp = ui.interact(img_r, ui.id().with("awa-image"), Sense::click_and_drag());
+ if let Some(p) = resp.interact_pointer_pos() {
+ if resp.drag_started() {
+ d.drag = Some((to_doc(p), to_doc(p)));
+ } else if resp.dragged()
+ && let Some(dr) = d.drag.as_mut()
+ {
+ dr.1 = to_doc(p);
+ }
+ }
+ if resp.drag_stopped()
+ && let Some((a, b)) = d.drag.take()
+ && (a[0] - b[0]).hypot(a[1] - b[1]) * k * s as f64 > 6.0
+ {
+ let orientation = if shift {
+ if (b[0] - a[0]).abs() >= (b[1] - a[1]).abs() { Orientation::Horizontal } else { Orientation::Vertical }
+ } else {
+ Orientation::Free
+ };
+ d.params.constraints.push(Constraint { a, b, orientation });
+ d.dirty = true;
+ }
+ let cam = Camera::new(&d.params, d.frame);
+ if resp.secondary_clicked()
+ && let Some(p) = resp.interact_pointer_pos()
+ {
+ // Delete the constraint whose curve passes nearest the click.
+ let near = d.params.constraints.iter().enumerate().map(|(i, c)| (i, cam.arc(c.a, c.b, 24).iter().map(|q| (to_screen(*q) - p).length()).fold(f32::MAX, f32::min))).min_by(|a, b| a.1.total_cmp(&b.1));
+ if let Some((i, dist)) = near
+ && dist < 10.0
+ {
+ d.params.constraints.remove(i);
+ d.dirty = true;
+ }
+ }
+ let show_src = !d.preview || d.drag.is_some();
+ let tex = if show_src { d.src_tex.as_ref() } else { d.out_tex.as_ref() };
+ widgets::checker(&painter, img_r, 8.0);
+ if let Some(tex) = tex {
+ painter.image(tex.id(), img_r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ // Constraints: curved over the source; straight end-to-end over the corrected preview.
+ let color = |o: Orientation| match o {
+ Orientation::Free => t.accent,
+ Orientation::Horizontal => t.warning,
+ Orientation::Vertical => t.danger,
+ };
+ let pf = Rect::new(0, 0, d.pw as i32, d.ph as i32);
+ let mesh = (!show_src && !d.params.constraints.is_empty()).then(|| wideangle::solve(&d.proxy_params(), pf));
+ for c in &d.params.constraints {
+ let pts: Vec<Pos2> = match &mesh {
+ Some(m) => cam.arc(c.a, c.b, 24).iter().map(|q| {
+ let pq = m.map(pf, [(q[0] - fx) * k, (q[1] - fy) * k]);
+ to_screen([pq[0] / k + fx, pq[1] / k + fy])
+ }).collect(),
+ None => cam.arc(c.a, c.b, 24).iter().map(|q| to_screen(*q)).collect(),
+ };
+ if let (Some(a), Some(b)) = (pts.first(), pts.last()) {
+ painter.circle_filled(*a, 3.5, color(c.orientation));
+ painter.circle_filled(*b, 3.5, color(c.orientation));
+ }
+ painter.add(egui::Shape::line(pts, Stroke::new(2.0, color(c.orientation))));
+ }
+ if let Some((a, b)) = d.drag {
+ let pts: Vec<Pos2> = cam.arc(a, b, 24).iter().map(|q| to_screen(*q)).collect();
+ painter.add(egui::Shape::line(pts, Stroke::new(2.0, t.accent_soft)));
+ }
+ // Panel.
+ let right = ERect::from_min_max(pos2(body.right() - PANEL_W, body.top()), body.max);
+ painter.rect_filled(right, 0.0, t.dock);
+ painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator));
+ let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 10.0))));
+ egui::ScrollArea::vertical().id_salt("awa-props").show(&mut props, |ui| {
+ ui.spacing_mut().item_spacing.y = 5.0;
+ widgets::section_label(ui, "Correction");
+ let mut model = d.params.model;
+ if widgets::dropdown(ui, "awa-model", &mut model, &[(WideModel::Auto, "Auto"), (WideModel::Fisheye, "Fisheye"), (WideModel::Perspective, "Perspective"), (WideModel::FullSpherical, "Full Spherical")], 200.0) {
+ d.params.model = model;
+ d.dirty = true;
+ }
+ let mut v = d.params.scale as f32;
+ if widgets::slider_row(ui, "Scale", &mut v, 50.0..=150.0, "%", None).changed() {
+ d.params.scale = v as f64;
+ d.dirty = true;
+ }
+ let mut v = d.params.focal_length as f32;
+ if widgets::slider_row(ui, "Focal Length", &mut v, 0.0..=200.0, "mm", None).changed() {
+ d.params.focal_length = v as f64;
+ d.dirty = true;
+ }
+ let mut v = d.params.crop_factor as f32;
+ if widgets::slider_row(ui, "Crop Factor", &mut v, 0.1..=10.0, "", None).changed() {
+ d.params.crop_factor = v as f64;
+ d.dirty = true;
+ }
+ widgets::hairline(ui);
+ widgets::section_label(ui, &format!("Constraints ({})", d.params.constraints.len()));
+ let mut remove = None;
+ for (i, c) in d.params.constraints.iter_mut().enumerate() {
+ ui.horizontal(|ui| {
+ ui.label(format!("{}", i + 1));
+ let mut o = c.orientation;
+ if widgets::dropdown(ui, &format!("awa-o-{i}"), &mut o, &[(Orientation::Free, "Free"), (Orientation::Horizontal, "Horizontal"), (Orientation::Vertical, "Vertical")], 120.0) {
+ c.orientation = o;
+ d.dirty = true;
+ }
+ if widgets::secondary_button(ui, "Delete", 60.0).clicked() {
+ remove = Some(i);
+ }
+ });
+ }
+ if let Some(i) = remove {
+ d.params.constraints.remove(i);
+ d.dirty = true;
+ }
+ widgets::hairline(ui);
+ widgets::checkbox(ui, &mut d.preview, "Preview");
+ ui.label(egui::RichText::new("Drag on the image to add a constraint; Shift for horizontal/vertical; right-click to delete.").color(t.text_faint).size(11.0));
+ });
+ let foot = ERect::from_min_max(pos2(full.left(), full.bottom() - footer_h), full.max);
+ painter.rect_filled(foot, 0.0, t.dock);
+ let mut fu = ui.new_child(egui::UiBuilder::new().max_rect(foot.shrink2(vec2(16.0, 9.0))).layout(egui::Layout::right_to_left(egui::Align::Center)));
+ if widgets::primary_button(&mut fu, "OK", 90.0).clicked() {
+ action = Some("ok");
+ }
+ if widgets::secondary_button(&mut fu, "Cancel", 90.0).clicked() {
+ action = Some("cancel");
+ }
+ fu.label(egui::RichText::new(format!("{:.0} ms · straightness {:.1} px", d.render_ms, d.residual)).color(t.text_faint));
+ });
+ if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ action = Some("cancel");
+ }
+ match action {
+ Some("ok") => {
+ if let Err(e) = commit(app) {
+ app.ui.status = e;
+ }
+ }
+ Some("cancel") => app.wide_angle = None,
+ _ => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dialog_adds_constraints_and_commits() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ let ctx = egui::Context::default();
+ app.run("file.new", json!({"width": 160, "height": 100})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("edit.fill", json!({"color": "#808080"})).unwrap();
+ let r = menu(&mut app, &ctx, "filter.adaptiveWideAngle", &json!({})).unwrap().unwrap();
+ assert_eq!(r["proxy"], json!([160, 100]));
+ let r = menu(&mut app, &ctx, "filter.adaptiveWideAngle", &json!({"ui": {"set": {"model": "fisheye", "focalLength": 10.0}, "add": {"a": [20, 20], "b": [140, 20], "orientation": "horizontal"}}})).unwrap().unwrap();
+ assert_eq!(r["params"]["constraints"].as_array().unwrap().len(), 1);
+ assert!(r["residual"].as_f64().unwrap() < 3.0, "{r}");
+ let r = menu(&mut app, &ctx, "filter.adaptiveWideAngle", &json!({"ui": {"commit": true}})).unwrap().unwrap();
+ assert_eq!(r["model"], "fisheye");
+ assert!(app.wide_angle.is_none());
+ menu(&mut app, &ctx, "filter.adaptiveWideAngle", &json!({})).unwrap().unwrap();
+ assert!(menu(&mut app, &ctx, "filter.adaptiveWideAngle", &json!({"ui": {"add": {"a": [1, 1]}}})).unwrap().is_err());
+ menu(&mut app, &ctx, "filter.adaptiveWideAngle", &json!({"ui": {"cancel": true}})).unwrap().unwrap();
+ assert!(app.wide_angle.is_none());
+ }
+}
diff --git a/crates/ui-egui/src/workspace_ui.rs b/crates/ui-egui/src/workspace_ui.rs
new file mode 100644
index 000000000..9719f1a68
--- /dev/null
+++ b/crates/ui-egui/src/workspace_ui.rs
@@ -0,0 +1,540 @@
+//! Shell-only Window and View items: Window › Workspace › New / Delete / Lock Workspace (saved
+//! in the preferences), Window › Modifier Keys (sticky Shift/⌘/⌥ for touch and pen users),
+//! View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…
+//! and the View › 32-bit Preview Options dialog.
+//!
+//! State is [`ShellUi`] (serialisable, part of `UiState`); saved workspaces and the lock live in
+//! `Preferences::workspaces` / `workspace_locked` so they persist with the preferences.
+
+use egui::{Align2, RichText, vec2};
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+/// A View › Pixel Aspect Ratio › Custom entry.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CustomPar {
+ pub name: String,
+ pub ratio: f32,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ShellUi {
+ /// Window › Modifier Keys panel open, and its latched keys.
+ pub modifier_keys: bool,
+ pub sticky_shift: bool,
+ pub sticky_command: bool,
+ pub sticky_alt: bool,
+ /// Custom pixel aspect ratios (the active one is `ViewOptions::pixel_aspect` = `custom:<ratio>:<name>`).
+ pub custom_pars: Vec<CustomPar>,
+ /// Open dialog: (kind, fields). Kinds: newWorkspace, deleteWorkspace, customPar, preview32,
+ /// extrasOptions.
+ pub dialog: Option<(String, Map<String, Value>)>,
+}
+
+const IDS: [&str; 7] = [
+ "window.panel.modifierKeys",
+ "window.workspace.newWorkspace",
+ "window.workspace.deleteWorkspace",
+ "window.workspace.lockWorkspace",
+ "window.workspace.select",
+ "view.pixelAspectRatio.custom",
+ "view.show.showExtrasOptions",
+];
+
+/// Menu ids handled here (live menu items).
+pub fn handles(id: &str) -> bool {
+ IDS.contains(&id)
+}
+
+pub fn checked(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ match id {
+ "window.panel.modifierKeys" => Some(app.ui.shell.modifier_keys),
+ "window.workspace.lockWorkspace" => Some(app.session.prefs().workspace_locked),
+ "view.pixelAspectRatio.custom" => Some(app.ui.view.pixel_aspect.starts_with("custom:")),
+ _ => None,
+ }
+}
+
+pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option<bool> {
+ Some(match id {
+ "window.workspace.deleteWorkspace" => !app.session.prefs().workspaces.is_empty(),
+ "view.thirtyTwoBitPreviewOptions" => app.session.is_enabled(id),
+ i if handles(i) => true,
+ _ => return None,
+ })
+}
+
+/// Latched Modifier Keys panel keys added to the real ones.
+pub fn sticky_mods(app: &PhotocraftApp, mut m: egui::Modifiers) -> egui::Modifiers {
+ let s = &app.ui.shell;
+ m.shift |= s.sticky_shift;
+ m.alt |= s.sticky_alt;
+ if s.sticky_command {
+ m.command = true;
+ if cfg!(target_os = "macos") {
+ m.mac_cmd = true;
+ } else {
+ m.ctrl = true;
+ }
+ }
+ m
+}
+
+fn no_params(p: &Value) -> bool {
+ p.as_object().is_none_or(|o| o.is_empty())
+}
+
+fn fields(v: Value) -> Map<String, Value> {
+ v.as_object().cloned().unwrap_or_default()
+}
+
+fn open(app: &mut PhotocraftApp, kind: &str, f: Value) -> Result<Value, String> {
+ app.ui.shell.dialog = Some((kind.to_string(), fields(f)));
+ Ok(json!({"dialog": kind}))
+}
+
+/// Built-in workspace names (Window › Workspace presets).
+const PRESETS: [&str; 6] = ["Essentials", "Photography", "Painting", "Pixel Art", "Graphic and Web", "Motion"];
+
+/// Run a shell command, or open its dialog. `None` when `id` isn't ours.
+pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ if id == "view.thirtyTwoBitPreviewOptions" && no_params(params) {
+ let d = app.session.active()?;
+ let h = app.session.color.hdr.get(&d.doc.id).copied().unwrap_or_default();
+ return Some(open(app, "preview32", json!({"method": if h.highlight_compression { "highlightCompression" } else { "exposureGamma" }, "exposure": h.exposure, "gamma": h.gamma})));
+ }
+ if !handles(id) {
+ return None;
+ }
+ let s = &mut app.ui.shell;
+ Some(match id {
+ "window.panel.modifierKeys" => {
+ s.modifier_keys = params.get("show").and_then(Value::as_bool).unwrap_or(!s.modifier_keys);
+ for (k, slot) in [("shift", &mut s.sticky_shift), ("command", &mut s.sticky_command), ("alt", &mut s.sticky_alt)] {
+ if let Some(v) = params.get(k).and_then(Value::as_bool) {
+ *slot = v;
+ }
+ }
+ Ok(json!({"visible": s.modifier_keys, "shift": s.sticky_shift, "command": s.sticky_command, "alt": s.sticky_alt}))
+ }
+ "window.workspace.lockWorkspace" => {
+ let on = params.get("on").and_then(Value::as_bool).unwrap_or(!app.session.prefs().workspace_locked);
+ app.session.prefs.edit(|p| p.workspace_locked = on);
+ Ok(json!({"locked": on}))
+ }
+ "window.workspace.newWorkspace" if no_params(params) => open(app, "newWorkspace", json!({"name": "", "keyboardShortcuts": false, "menus": false, "toolbar": false})),
+ "window.workspace.newWorkspace" => new_workspace(app, params),
+ "window.workspace.deleteWorkspace" if no_params(params) => {
+ let first = app.session.prefs().workspaces.keys().next().cloned().unwrap_or_default();
+ open(app, "deleteWorkspace", json!({"name": first}))
+ }
+ "window.workspace.deleteWorkspace" => delete_workspace(app, params),
+ "window.workspace.select" => select_workspace(app, params),
+ "view.pixelAspectRatio.custom" if no_params(params) => open(app, "customPar", json!({"name": "", "ratio": 1.0})),
+ "view.pixelAspectRatio.custom" => custom_par(app, params),
+ "view.show.showExtrasOptions" if no_params(params) => {
+ let show = serde_json::to_value(app.ui.view.show).unwrap_or_default();
+ open(app, "extrasOptions", show)
+ }
+ "view.show.showExtrasOptions" => {
+ let mut show = serde_json::to_value(app.ui.view.show).unwrap_or_default();
+ if let (Some(o), Some(p)) = (show.as_object_mut(), params.as_object()) {
+ for (k, v) in p {
+ if !o.contains_key(k) || !v.is_boolean() {
+ return Some(Err(format!("unknown Show item `{k}` ({})", o.keys().cloned().collect::<Vec<_>>().join("|"))));
+ }
+ o.insert(k.clone(), v.clone());
+ }
+ }
+ app.ui.view.show = serde_json::from_value(show.clone()).map_err(|e| e.to_string()).ok()?;
+ Ok(show)
+ }
+ _ => return None,
+ })
+}
+
+/// Window › Workspace › New Workspace…: save the panel layout (and optionally keyboard
+/// shortcuts, menus and toolbar) under a name, and make it current.
+fn new_workspace(app: &mut PhotocraftApp, p: &Value) -> Result<Value, String> {
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).unwrap_or("").to_string();
+ if name.is_empty() {
+ return Err("a workspace needs a name".into());
+ }
+ if PRESETS.contains(&name.as_str()) {
+ return Err(format!("\"{name}\" is a built-in workspace"));
+ }
+ let prefs = app.session.prefs().clone();
+ let mut ws = json!({"panels": app.ui.panels, "dockTabs": app.ui.dock_tabs});
+ if p.get("keyboardShortcuts").and_then(Value::as_bool) == Some(true) {
+ ws["shortcuts"] = json!(prefs.shortcuts);
+ }
+ if p.get("menus").and_then(Value::as_bool) == Some(true) {
+ ws["menus"] = serde_json::to_value(&prefs.menus).unwrap_or_default();
+ }
+ if p.get("toolbar").and_then(Value::as_bool) == Some(true) {
+ ws["toolbar"] = serde_json::to_value(&prefs.toolbar).unwrap_or_default();
+ }
+ let replaced = prefs.workspaces.contains_key(&name);
+ app.session.prefs.edit(|pr| pr.workspaces.insert(name.clone(), ws));
+ app.ui.workspace = name.clone();
+ Ok(json!({"workspace": name, "replaced": replaced}))
+}
+
+fn delete_workspace(app: &mut PhotocraftApp, p: &Value) -> Result<Value, String> {
+ let name = p.get("name").and_then(Value::as_str).ok_or("pass `name`")?.to_string();
+ if !app.session.prefs().workspaces.contains_key(&name) {
+ return Err(format!("no saved workspace \"{name}\""));
+ }
+ // Like Photoshop, the current workspace can't be deleted.
+ if app.ui.workspace == name {
+ return Err(format!("\"{name}\" is the current workspace; switch to another first"));
+ }
+ app.session.prefs.edit(|pr| pr.workspaces.remove(&name));
+ Ok(json!({"deleted": name}))
+}
+
+fn select_workspace(app: &mut PhotocraftApp, p: &Value) -> Result<Value, String> {
+ let name = p.get("name").and_then(Value::as_str).ok_or("pass `name`")?.to_string();
+ if PRESETS.contains(&name.as_str()) {
+ app.ui.workspace = name.clone();
+ crate::menus::apply_workspace(app);
+ return Ok(json!({"workspace": name}));
+ }
+ if !app.session.prefs().workspaces.contains_key(&name) {
+ return Err(format!("no workspace \"{name}\""));
+ }
+ app.ui.workspace = name.clone();
+ apply_custom(app);
+ Ok(json!({"workspace": name}))
+}
+
+/// Apply the current workspace when it is a saved one. Returns false for the built-in presets.
+pub fn apply_custom(app: &mut PhotocraftApp) -> bool {
+ let Some(ws) = app.session.prefs().workspaces.get(&app.ui.workspace).cloned() else { return false };
+ if let Ok(p) = serde_json::from_value(ws["panels"].clone()) {
+ app.ui.panels = p;
+ }
+ if let Ok(t) = serde_json::from_value(ws["dockTabs"].clone()) {
+ app.ui.dock_tabs = t;
+ }
+ let (sc, menus, toolbar) = (ws.get("shortcuts").cloned(), ws.get("menus").cloned(), ws.get("toolbar").cloned());
+ if sc.is_some() || menus.is_some() || toolbar.is_some() {
+ app.session.prefs.edit(|p| {
+ if let Some(v) = sc.and_then(|v| serde_json::from_value(v).ok()) {
+ p.shortcuts = v;
+ }
+ if let Some(v) = menus.and_then(|v| serde_json::from_value(v).ok()) {
+ p.menus = v;
+ }
+ if let Some(v) = toolbar.and_then(|v| serde_json::from_value(v).ok()) {
+ p.toolbar = v;
+ }
+ });
+ }
+ true
+}
+
+/// Custom Pixel Aspect Ratio: `{name, ratio}` adds (or updates) and selects; `{delete: name}`
+/// removes; `{select: name}` selects a saved one.
+fn custom_par(app: &mut PhotocraftApp, p: &Value) -> Result<Value, String> {
+ let s = &mut app.ui.shell;
+ if let Some(n) = p.get("delete").and_then(Value::as_str) {
+ let before = s.custom_pars.len();
+ s.custom_pars.retain(|c| c.name != n);
+ if s.custom_pars.len() == before {
+ return Err(format!("no custom pixel aspect ratio \"{n}\""));
+ }
+ if app.ui.view.pixel_aspect.ends_with(&format!(":{n}")) {
+ app.ui.view.pixel_aspect = "square".into();
+ }
+ return Ok(json!({"deleted": n}));
+ }
+ let c = if let Some(n) = p.get("select").and_then(Value::as_str) {
+ s.custom_pars.iter().find(|c| c.name == n).cloned().ok_or_else(|| format!("no custom pixel aspect ratio \"{n}\""))?
+ } else {
+ let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or("pass `name`")?.to_string();
+ let ratio = p.get("ratio").and_then(Value::as_f64).ok_or("pass `ratio`")? as f32;
+ if !(0.1..=10.0).contains(&ratio) {
+ return Err("the ratio must be between 0.100 and 10.000".into());
+ }
+ let c = CustomPar { name, ratio };
+ match s.custom_pars.iter_mut().find(|x| x.name == c.name) {
+ Some(x) => *x = c.clone(),
+ None => s.custom_pars.push(c.clone()),
+ }
+ c
+ };
+ app.ui.view.pixel_aspect = format!("custom:{}:{}", c.ratio, c.name);
+ Ok(json!({"pixelAspectRatio": c.ratio, "name": c.name}))
+}
+
+/// The open dialog's OK as (command id, params).
+pub fn dialog_command(kind: &str, f: &Map<String, Value>) -> Option<(&'static str, Value)> {
+ Some(match kind {
+ "newWorkspace" => ("window.workspace.newWorkspace", Value::Object(f.clone())),
+ "deleteWorkspace" => ("window.workspace.deleteWorkspace", json!({"name": f.get("name")})),
+ "customPar" => ("view.pixelAspectRatio.custom", json!({"name": f.get("name"), "ratio": f.get("ratio")})),
+ "preview32" => ("view.thirtyTwoBitPreviewOptions", Value::Object(f.clone())),
+ "extrasOptions" => ("view.show.showExtrasOptions", Value::Object(f.clone())),
+ _ => return None,
+ })
+}
+
+/// Draws the Modifier Keys panel and the open dialog.
+pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ if app.ui.shell.modifier_keys {
+ let mut close = false;
+ let mut s = app.ui.shell.clone();
+ let cmd = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl" };
+ let alt = if cfg!(target_os = "macos") { "⌥" } else { "Alt" };
+ crate::analysis_ui::panel_window(app, ctx, "modifier-keys", "Modifier Keys", vec2(-420.0, 80.0), 150.0, |ui| {
+ close = crate::analysis_ui::title_row(ui, "Modifier Keys");
+ ui.horizontal(|ui| {
+ for (label, on) in [("⇧", &mut s.sticky_shift), (cmd, &mut s.sticky_command), (alt, &mut s.sticky_alt)] {
+ if ui.add(egui::Button::new(RichText::new(label).size(14.0)).selected(*on).min_size(vec2(40.0, 30.0))).clicked() {
+ *on = !*on;
+ }
+ }
+ });
+ });
+ s.modifier_keys = !close;
+ app.ui.shell = s;
+ }
+ if app.ui.shell.dialog.is_some() {
+ dialog(app, ctx);
+ }
+}
+
+fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let Some((kind, mut f)) = app.ui.shell.dialog.clone() else { return };
+ let t = Tokens::get(ctx);
+ let title = match kind.as_str() {
+ "newWorkspace" => "New Workspace",
+ "deleteWorkspace" => "Delete Workspace",
+ "customPar" => "Save Pixel Aspect Ratio",
+ "preview32" => "32-bit Preview Options",
+ _ => "Show Extras Options",
+ };
+ let names: Vec<String> = app.session.prefs().workspaces.keys().cloned().collect();
+ let mut result: Option<bool> = None;
+ egui::Window::new(title)
+ .id(egui::Id::new("shell-dialog"))
+ .collapsible(false)
+ .resizable(false)
+ .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))
+ .show(ctx, |ui| {
+ ui.label(RichText::new(title).color(t.text).size(13.0).strong());
+ crate::widgets::hairline(ui);
+ ui.add_space(6.0);
+ let text = |ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str| {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(label).color(t.text_dim).size(11.0));
+ let mut v = f.get(key).and_then(Value::as_str).unwrap_or("").to_string();
+ if ui.add(egui::TextEdit::singleline(&mut v).desired_width(180.0)).changed() {
+ f.insert(key.into(), json!(v));
+ }
+ });
+ };
+ let check = |ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str| {
+ let mut on = f.get(key).and_then(Value::as_bool).unwrap_or(false);
+ if crate::widgets::checkbox(ui, &mut on, label).changed() {
+ f.insert(key.into(), json!(on));
+ }
+ };
+ let number = |ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str, range: std::ops::RangeInclusive<f32>| {
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(label).color(t.text_dim).size(11.0));
+ let mut v = f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ if crate::widgets::slider(ui, &mut v, range.clone(), None).changed() | crate::widgets::value_field(ui, &mut v, range, "", 60.0).changed() {
+ f.insert(key.into(), json!(v));
+ }
+ });
+ };
+ match kind.as_str() {
+ "newWorkspace" => {
+ text(ui, &mut f, "name", "Name:");
+ ui.label(RichText::new("Capture").color(t.text_dim).size(11.0));
+ ui.label(RichText::new("Panel locations are saved in the workspace. Keyboard shortcuts, menus and toolbar are optional.").color(t.text_faint).size(10.5));
+ check(ui, &mut f, "keyboardShortcuts", "Keyboard Shortcuts");
+ check(ui, &mut f, "menus", "Menus");
+ check(ui, &mut f, "toolbar", "Toolbar");
+ }
+ "deleteWorkspace" => {
+ let mut cur = f.get("name").and_then(Value::as_str).unwrap_or("").to_string();
+ let opts: Vec<(String, &str)> = names.iter().map(|n| (n.clone(), n.as_str())).collect();
+ if !opts.is_empty() && crate::widgets::dropdown(ui, "ws-delete", &mut cur, &opts, 180.0) {
+ f.insert("name".into(), json!(cur));
+ }
+ }
+ "customPar" => {
+ text(ui, &mut f, "name", "Name:");
+ number(ui, &mut f, "ratio", "Factor:", 0.1..=10.0);
+ }
+ "preview32" => {
+ let mut m = f.get("method").and_then(Value::as_str).unwrap_or("exposureGamma").to_string();
+ if crate::widgets::dropdown(ui, "p32-method", &mut m, &[("exposureGamma".to_string(), "Exposure and Gamma"), ("highlightCompression".to_string(), "Highlight Compression")], 180.0) {
+ f.insert("method".into(), json!(m));
+ }
+ ui.add_enabled_ui(m == "exposureGamma", |ui| {
+ number(ui, &mut f, "exposure", "Exposure:", -20.0..=20.0);
+ number(ui, &mut f, "gamma", "Gamma:", 0.1..=9.99);
+ });
+ }
+ _ => {
+ for (k, label) in [("layerEdges", "Layer Edges"), ("selectionEdges", "Selection Edges"), ("targetPath", "Target Path"), ("notes", "Notes"), ("pixelGrid", "Pixel Grid"), ("slices", "Slices"), ("count", "Count"), ("smartGuides", "Smart Guides"), ("brushPreview", "Brush Preview"), ("mesh", "Mesh"), ("editPins", "Edit Pins"), ("canvasGuides", "Canvas Guides"), ("artboardGuides", "Artboard Guides")] {
+ check(ui, &mut f, k, label);
+ }
+ }
+ }
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let ok = if kind == "deleteWorkspace" { "Delete" } else { "OK" };
+ if crate::widgets::primary_button(ui, ok, 70.0).clicked() {
+ result = Some(true);
+ }
+ if crate::widgets::secondary_button(ui, "Cancel", 70.0).clicked() {
+ result = Some(false);
+ }
+ });
+ });
+ });
+ match result {
+ Some(true) => {
+ if let Some((id, p)) = dialog_command(&kind, &f) {
+ match crate::menus::invoke(app, ctx, id, p) {
+ Ok(_) => app.ui.shell.dialog = None,
+ Err(e) => {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ app.ui.shell.dialog = Some((kind, f));
+ }
+ }
+ }
+ }
+ Some(false) => app.ui.shell.dialog = None,
+ None => app.ui.shell.dialog = Some((kind, f)),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::state::Tool;
+
+ fn app() -> (PhotocraftApp, egui::Context) {
+ (PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()), egui::Context::default())
+ }
+
+ #[test]
+ fn new_select_delete_workspaces() {
+ let (mut app, ctx) = app();
+ let inv = |app: &mut PhotocraftApp, id: &str, p: Value| crate::menus::invoke(app, &ctx, id, p);
+ assert!(!crate::menus::is_enabled(&app, "window.workspace.deleteWorkspace"));
+ assert_eq!(inv(&mut app, "window.workspace.newWorkspace", json!({})).unwrap()["dialog"], "newWorkspace");
+ app.ui.panels.history = true;
+ app.ui.panels.navigator = true;
+ app.session.prefs.edit(|p| {
+ p.shortcuts.insert("filter.blur.gaussian".into(), "Cmd+Alt+G".into());
+ });
+ inv(&mut app, "window.workspace.newWorkspace", json!({"name": "Retouch", "keyboardShortcuts": true})).unwrap();
+ assert_eq!(app.ui.workspace, "Retouch");
+ assert!(inv(&mut app, "window.workspace.newWorkspace", json!({"name": "Painting"})).is_err());
+ assert!(inv(&mut app, "window.workspace.newWorkspace", json!({"name": " "})).is_err());
+ // The current workspace can't be deleted.
+ assert!(inv(&mut app, "window.workspace.deleteWorkspace", json!({"name": "Retouch"})).is_err());
+ inv(&mut app, "window.workspace.painting", json!({})).unwrap();
+ assert!(!app.ui.panels.history);
+ app.session.prefs.edit(|p| p.shortcuts.clear());
+ // Switching back restores the panels and the captured shortcuts.
+ inv(&mut app, "window.workspace.select", json!({"name": "Retouch"})).unwrap();
+ assert!(app.ui.panels.history && app.ui.panels.navigator);
+ assert_eq!(app.session.prefs().shortcuts.get("filter.blur.gaussian").map(String::as_str), Some("Cmd+Alt+G"));
+ // Reset Workspace re-applies the saved layout.
+ app.ui.panels.history = false;
+ inv(&mut app, "window.workspace.resetWorkspace", json!({})).unwrap();
+ assert!(app.ui.panels.history);
+ inv(&mut app, "window.workspace.essentials", json!({})).unwrap();
+ assert!(crate::menus::is_enabled(&app, "window.workspace.deleteWorkspace"));
+ inv(&mut app, "window.workspace.deleteWorkspace", json!({"name": "Retouch"})).unwrap();
+ assert!(app.session.prefs().workspaces.is_empty());
+ // Saved workspaces persist with the preferences.
+ inv(&mut app, "window.workspace.newWorkspace", json!({"name": "Mine"})).unwrap();
+ let json = app.session.prefs_to_json();
+ let mut s2 = photocraft_engine::Session::new();
+ s2.load_prefs_json(&json).unwrap();
+ assert!(s2.prefs().workspaces.contains_key("Mine"));
+ }
+
+ #[test]
+ fn lock_workspace_toggles_and_persists() {
+ let (mut app, ctx) = app();
+ crate::menus::invoke(&mut app, &ctx, "window.workspace.lockWorkspace", json!({})).unwrap();
+ assert!(app.session.prefs().workspace_locked);
+ assert_eq!(checked(&app, "window.workspace.lockWorkspace"), Some(true));
+ let items = crate::menus::menu_items(&app);
+ assert!(items.iter().any(|i| i.id == "window.workspace.lockWorkspace" && i.checked == Some(true)));
+ crate::menus::invoke(&mut app, &ctx, "window.workspace.lockWorkspace", json!({"on": false})).unwrap();
+ assert!(!app.session.prefs().workspace_locked);
+ }
+
+ #[test]
+ fn modifier_keys_latch_into_tool_events() {
+ let (mut app, ctx) = app();
+ crate::menus::invoke(&mut app, &ctx, "window.panel.modifierKeys", json!({"alt": true})).unwrap();
+ assert!(app.ui.shell.modifier_keys);
+ let m = sticky_mods(&app, egui::Modifiers::NONE);
+ assert!(m.alt && !m.shift);
+ // ⌥ latched: a Count-tool click on a marker removes it.
+ app.run("file.new", json!({"width": 50, "height": 50})).unwrap();
+ app.run("count.add", json!({"x": 10, "y": 10})).unwrap();
+ app.ui.tool = Tool::Count;
+ crate::canvas::tool_event(&mut app, crate::canvas::ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE);
+ crate::canvas::tool_event(&mut app, crate::canvas::ToolEvent::Up { x: 10.0, y: 10.0 }, egui::Modifiers::NONE);
+ assert_eq!(app.session.active().unwrap().doc.measurement.count_total(), 0);
+ crate::analysis_ui::tests::render(&mut app, &ctx, windows);
+ }
+
+ #[test]
+ fn custom_pixel_aspect_ratio_and_extras_options() {
+ let (mut app, ctx) = app();
+ let inv = |app: &mut PhotocraftApp, id: &str, p: Value| crate::menus::invoke(app, &ctx, id, p);
+ assert_eq!(inv(&mut app, "view.pixelAspectRatio.custom", json!({})).unwrap()["dialog"], "customPar");
+ inv(&mut app, "view.pixelAspectRatio.custom", json!({"name": "Cinema", "ratio": 1.25})).unwrap();
+ assert_eq!(crate::view_cmds::pixel_aspect_ratio(&app.ui.view.pixel_aspect), 1.25);
+ assert_eq!(checked(&app, "view.pixelAspectRatio.custom"), Some(true));
+ assert!(inv(&mut app, "view.pixelAspectRatio.custom", json!({"name": "x", "ratio": 50})).is_err());
+ inv(&mut app, "view.pixelAspectRatio.square", json!({})).unwrap();
+ inv(&mut app, "view.pixelAspectRatio.custom", json!({"select": "Cinema"})).unwrap();
+ assert_eq!(crate::view_cmds::pixel_aspect_ratio(&app.ui.view.pixel_aspect), 1.25);
+ inv(&mut app, "view.pixelAspectRatio.custom", json!({"delete": "Cinema"})).unwrap();
+ assert_eq!(app.ui.view.pixel_aspect, "square");
+ // Show Extras Options.
+ assert_eq!(inv(&mut app, "view.show.showExtrasOptions", json!({})).unwrap()["dialog"], "extrasOptions");
+ let (kind, mut f) = app.ui.shell.dialog.clone().unwrap();
+ f.insert("count".into(), json!(false));
+ let (id, p) = dialog_command(&kind, &f).unwrap();
+ inv(&mut app, id, p).unwrap();
+ assert!(!app.ui.view.show.count);
+ assert!(inv(&mut app, "view.show.showExtrasOptions", json!({"bogus": true})).is_err());
+ crate::analysis_ui::tests::render(&mut app, &ctx, windows);
+ }
+
+ #[test]
+ fn thirty_two_bit_preview_dialog() {
+ let (mut app, ctx) = app();
+ app.run("file.new", json!({"width": 20, "height": 20, "depth": 32})).unwrap();
+ let r = crate::menus::invoke(&mut app, &ctx, "view.thirtyTwoBitPreviewOptions", json!({})).unwrap();
+ assert_eq!(r["dialog"], "preview32");
+ let (kind, mut f) = app.ui.shell.dialog.clone().unwrap();
+ f.insert("exposure".into(), json!(1.5));
+ let (id, p) = dialog_command(&kind, &f).unwrap();
+ crate::menus::invoke(&mut app, &ctx, id, p).unwrap();
+ let d = app.session.active().unwrap().doc.id;
+ assert_eq!(app.session.color.hdr[&d].exposure, 1.5);
+ }
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 3e00a13bf..472e3ed77 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -22,7 +22,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options
- `ui.set {tool?, panels?, dockTabs?, maskTarget?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?}`: change UI state (`brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes)
- `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree
-- `ui.dialog.open {kind, fields?}` / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`
+- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`
- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?}], modifiers?}`: drive the active tool in document coordinates
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`
diff --git a/docs/images/SOURCES.md b/docs/images/SOURCES.md
index 75d17a556..723d1837f 100644
--- a/docs/images/SOURCES.md
+++ b/docs/images/SOURCES.md
@@ -13,3 +13,9 @@
| `photocraft-export-light.jpg` | Photocraft UI screenshot (offscreen snapshot) with *The Kiss*, Gustav Klimt, 1907–1908 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Gustav_Klimt_016.jpg). UI: this project. |
Screenshots must use famous public-domain artwork (or content made in the app), never personal photos.
+
+# Other bundled data
+
+| File | Content | Source / licence |
+|---|---|---|
+| `assets/dict/en_US-scowl-50.txt.gz` | English word list (72,403 words, American spelling) for Edit › Check Spelling | [SCOWL](http://wordlist.aspell.net/) 2020.12.07, size 50, by Kevin Atkinson: permissive licence (use, copy, modify, distribute and sell, keeping the notice); full text and build recipe in `assets/dict/LICENSE-SCOWL.txt`. |
diff --git a/docs/parity.md b/docs/parity.md
index 3d8fc697c..01cf03135 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -2,67 +2,42 @@
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.
-**532 of 625 menu items live (85.1%).**
+**600 of 625 menu items live (96.0%).**
| Menu | Live | Total | % |
|---|---:|---:|---:|
-| File | 28 | 50 | 56% |
-| Edit | 73 | 75 | 97% |
-| Image | 50 | 61 | 82% |
-| Layer | 145 | 160 | 91% |
-| Type | 41 | 44 | 93% |
-| Select | 22 | 25 | 88% |
-| Filter | 67 | 75 | 89% |
-| View | 61 | 74 | 82% |
-| Window | 45 | 61 | 74% |
+| File | 45 | 50 | 90% |
+| Edit | 74 | 75 | 99% |
+| Image | 57 | 61 | 93% |
+| Layer | 146 | 160 | 91% |
+| Type | 44 | 44 | 100% |
+| Select | 25 | 25 | 100% |
+| Filter | 75 | 75 | 100% |
+| View | 74 | 74 | 100% |
+| Window | 60 | 61 | 98% |
## Not yet implemented
-### File (22)
+### File (5)
-- Export › Export Preferences… (`file.export.exportPreferences`)
-- Export › Save for Web (Legacy)… (`file.export.saveForWebLegacy`)
- Export › Data Sets as Files… (`file.export.dataSetsAsFiles`)
-- Export › Paths to Illustrator… (`file.export.pathsToIllustrator`)
- Export › Render Video… (`file.export.renderVideo`)
-- Generate › Image Assets (`file.generate.imageAssets`)
-- Package… (`file.package`)
-- Automate › Create Droplet… (`file.automate.createDroplet`)
-- Automate › Crop and Straighten Photos (`file.automate.cropAndStraightenPhotos`)
-- Automate › Contact Sheet II… (`file.automate.contactSheetII`)
-- Automate › Lens Correction… (`file.automate.lensCorrection`)
-- Automate › Merge to HDR Pro… (`file.automate.mergeToHdrPro`)
-- Automate › Photomerge… (`file.automate.photomerge`)
-- Scripts › Script Events Manager… (`file.scripts.scriptEventsManager`)
-- Scripts › Statistics… (`file.scripts.statistics`)
-- Scripts › Browse… (`file.scripts.browse`)
- Import › Variable Data Sets… (`file.import.variableDataSets`)
- Import › Video Frames to Layers… (`file.import.videoFramesToLayers`)
-- Import › Notes… (`file.import.notes`)
- Import › WIA Support… (`file.import.wiaSupport`)
-- Print… (`file.print`)
-- Print One Copy (`file.printOneCopy`)
-### Edit (2)
+### Edit (1)
-- Check Spelling… (`edit.checkSpelling`)
- Presets › Migrate Presets (`edit.presets.migratePresets`)
-### Image (11)
+### Image (4)
-- Mode › Multichannel (`image.mode.multichannel`)
- Variables › Define… (`image.variables.define`)
- Variables › Data Sets… (`image.variables.dataSets`)
- Apply Data Set… (`image.applyDataSet`)
- Trap… (`image.trap`)
-- Analysis › Set Measurement Scale… (`image.analysis.setMeasurementScale`)
-- Analysis › Select Data Points… (`image.analysis.selectDataPoints`)
-- Analysis › Record Measurements (`image.analysis.recordMeasurements`)
-- Analysis › Ruler Tool (`image.analysis.rulerTool`)
-- Analysis › Count Tool (`image.analysis.countTool`)
-- Analysis › Place Scale Marker… (`image.analysis.placeScaleMarker`)
-### Layer (15)
+### Layer (14)
- New › Frame from Layers (`layer.new.frameFromLayers`)
- Video Layers › New Blank Video Layer (`layer.videoLayers.newBlankVideoLayer`)
@@ -78,62 +53,7 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Pho
- Video Layers › Reload Frame (`layer.videoLayers.reloadFrame`)
- Video Layers › Rasterize (`layer.videoLayers.rasterize`)
- Rasterize › Video (`layer.rasterize.video`)
-- New Layer Based Slice (`layer.newLayerBasedSlice`)
-### Type (3)
+### Window (1)
-- Panels › Glyphs Panel (`type.panels.glyphs`)
-- Panels › Character Styles Panel (`type.panels.characterStyles`)
-- Panels › Paragraph Styles Panel (`type.panels.paragraphStyles`)
-
-### Select (3)
-
-- Isolate Layers (`select.isolateLayers`)
-- Sky (`select.sky`)
-- Transform Selection (`select.transformSelection`)
-
-### Filter (8)
-
-- Filter Gallery… (`filter.filterGallery`)
-- Camera Raw Filter… (`filter.cameraRaw`)
-- Adaptive Wide Angle… (`filter.adaptiveWideAngle`)
-- Lens Correction… (`filter.lensCorrection`)
-- Vanishing Point… (`filter.vanishingPoint`)
-- Render › Flame… (`filter.render.flame`)
-- Render › Picture Frame… (`filter.render.pictureFrame`)
-- Render › Tree… (`filter.render.tree`)
-
-### View (13)
-
-- Proof Setup › Working Cyan Plate (`view.proofSetup.workingCyanPlate`)
-- Proof Setup › Working Magenta Plate (`view.proofSetup.workingMagentaPlate`)
-- Proof Setup › Working Yellow Plate (`view.proofSetup.workingYellowPlate`)
-- Proof Setup › Working Black Plate (`view.proofSetup.workingBlackPlate`)
-- Proof Setup › Working CMY Plate (`view.proofSetup.workingCmyPlate`)
-- Proof Setup › Legacy Macintosh RGB (`view.proofSetup.legacyMacintoshRgb`)
-- Proof Setup › Color Blindness — Protanopia-type (`view.proofSetup.colorBlindnessProtanopia`)
-- Proof Setup › Color Blindness — Deuteranopia-type (`view.proofSetup.colorBlindnessDeuteranopia`)
-- Pixel Aspect Ratio › Custom Pixel Aspect Ratio… (`view.pixelAspectRatio.custom`)
-- 32-bit Preview Options… (`view.thirtyTwoBitPreviewOptions`)
-- Show › Show Extras Options… (`view.show.showExtrasOptions`)
-- Lock Slices (`view.lockSlices`)
-- Clear Slices (`view.clearSlices`)
-
-### Window (16)
-
-- Workspace › New Workspace… (`window.workspace.newWorkspace`)
-- Workspace › Delete Workspace… (`window.workspace.deleteWorkspace`)
-- Workspace › Lock Workspace (`window.workspace.lockWorkspace`)
-- Character Styles (`window.panel.characterStyles`)
-- Clone Source (`window.panel.cloneSource`)
-- Glyphs (`window.panel.glyphs`)
-- Gradients (`window.panel.gradients`)
-- Measurement Log (`window.panel.measurementLog`)
-- Modifier Keys (`window.panel.modifierKeys`)
-- Notes (`window.panel.notes`)
-- Paragraph Styles (`window.panel.paragraphStyles`)
-- Patterns (`window.panel.patterns`)
-- Shapes (`window.panel.shapes`)
-- Styles (`window.panel.styles`)
- Timeline (`window.panel.timeline`)
-- Tool Presets (`window.panel.toolPresets`)