mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-17 07:25:16 +00:00
Merge upstream CLI action sets while retaining the local model backend
This commit is contained in:
commit
1d96c25306
55 files changed
+2207
-369
No files matched your search
+2
-1
@@ -20,7 +20,7 @@ next to them.
|
||||
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
|
||||
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/{check,chevron-down,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
@@ -30,6 +30,7 @@ next to them.
|
||||
| `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/pen-add-anchor.svg`, `assets/icons/pen-delete-anchor.svg` | Add Anchor Point and Delete Anchor Point tool glyphs: Lucide `pen-tool` plus a + or − mark | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/painting-symmetry.svg` | Painting symmetry glyph: Lucide `heart` with a central axis | Lucide Icons and Contributors; adapted by @shorbank | Derived from <https://github.com/lucide-icons/lucide> `icons/heart.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) |
|
||||
| `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | <https://thenounproject.com/icon/magnetic-lasso-tool-177513/> | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) |
|
||||
|
||||
@@ -178,8 +178,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🧰 56 tools</h4>
|
||||
Move · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
|
||||
<h4>🧰 58 tools</h4>
|
||||
Move · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Add Anchor Point · Delete Anchor Point · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🖌️ A real brush engine</h4>
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use photocraft_automation::{AuthorizedWorkspace, Headless, PhotocraftMcp, files, security};
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
use photocraft_io::ExportOptions;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -23,11 +24,14 @@ USAGE:
|
||||
photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers]
|
||||
Open a file, run engine commands in order, save the result. Each --params
|
||||
applies to the preceding --cmd. Prints each command's JSON result.
|
||||
photocraft-cli batch --actions <actions.json> --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers]
|
||||
photocraft-cli batch --actions <actions.json> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers]
|
||||
Apply an action list to every image in a directory. Steps are [id, params] pairs,
|
||||
{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them
|
||||
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An --out folder that is the
|
||||
--in folder is refused, as the results would replace the originals; --in-place allows it.
|
||||
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An Actions set (the Actions
|
||||
panel's actions.json, {\"actions\": [{\"name\", \"steps\"}…]}) plays the action --action names (needed
|
||||
when the set holds more than one) with the whole set loaded, so its steps can play other actions
|
||||
of the set. An --out folder that is the --in folder is refused, as the results would replace
|
||||
the originals; --in-place allows it.
|
||||
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>]
|
||||
@@ -64,7 +68,12 @@ const SUBCOMMANDS: &[Subcommand] = &[
|
||||
Subcommand { name: "convert", values: &["--format", "--quality"], bare: &["--tiff-layers"], run: convert },
|
||||
Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },
|
||||
Subcommand { name: "run", values: &["--new", "--cmd", "--params", "--out", "--format", "--quality"], bare: &["--tiff-layers"], run: run_cmds },
|
||||
Subcommand { name: "batch", values: &["--actions", "--in", "--out", "--format", "--quality"], bare: &["--in-place", "--tiff-layers"], run: batch },
|
||||
Subcommand {
|
||||
name: "batch",
|
||||
values: &["--actions", "--action", "--in", "--out", "--format", "--quality"],
|
||||
bare: &["--in-place", "--tiff-layers"],
|
||||
run: batch,
|
||||
},
|
||||
Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },
|
||||
Subcommand { name: "commands", values: &["--filter"], bare: &["--json"], run: |a, out, _| commands(a, out) },
|
||||
Subcommand {
|
||||
@@ -347,7 +356,39 @@ fn run_cmds(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
/// list or wrapped in `{"actions": […]}`, `{"steps": […]}` or a droplet (#489).
|
||||
pub fn parse_actions(text: &str) -> Result<Vec<(String, Value)>, String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;
|
||||
photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(&v), "batch --actions").map_err(|e| e.to_string())
|
||||
steps_of(&v)
|
||||
}
|
||||
|
||||
fn steps_of(v: &Value) -> Result<Steps, String> {
|
||||
photocraft_engine::automate_cmds::parse_action(v.get("actions").unwrap_or(v), "batch --actions").map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Engine commands to run in order: `(id, params)`.
|
||||
pub type Steps = Vec<(String, Value)>;
|
||||
|
||||
/// The steps `batch` plays on each file, and the actions they can call. An Actions set (the
|
||||
/// Actions panel's `actions.json`: `{"actions": [{"name", "steps"}…]}`, or the bare list) plays
|
||||
/// the action `name` picks (optional when the set holds one) with the whole set loaded, as
|
||||
/// Photoshop's Batch does; anything else is one action's steps ([`parse_actions`]) (#2786).
|
||||
pub fn load_actions(text: &str, name: Option<&str>) -> Result<(Steps, Vec<Action>), String> {
|
||||
let v: Value = serde_json::from_str(text).map_err(|e| format!("actions JSON: {e}"))?;
|
||||
let list = v.get("actions").unwrap_or(&v);
|
||||
let is_set = list.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|x| x.get("name").is_some_and(Value::is_string)));
|
||||
if !is_set {
|
||||
if name.is_some() {
|
||||
return Err("--action picks an action from an Actions set ({\"actions\": [{\"name\", \"steps\"}…]}), but this file holds one action's steps".into());
|
||||
}
|
||||
return Ok((steps_of(&v)?, Vec::new()));
|
||||
}
|
||||
let set: Vec<Action> = serde_json::from_value(list.clone()).map_err(|e| format!("Actions set: {e}"))?;
|
||||
let names = || set.iter().map(|a| format!("`{}`", a.name)).collect::<Vec<_>>().join(", ");
|
||||
let action = match (name, set.as_slice()) {
|
||||
(Some(n), _) => set.iter().find(|a| a.name == n).ok_or_else(|| format!("no action named `{n}` in the set (it holds {})", names()))?,
|
||||
(None, [only]) => only,
|
||||
(None, _) => return Err(format!("the Actions set holds {} actions: pick one with --action <name> ({})", set.len(), names())),
|
||||
};
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, set))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
|
||||
@@ -369,7 +410,7 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let in_dir = PathBuf::from(a.get("--in").ok_or("batch needs --in <dir>")?);
|
||||
let out_dir = PathBuf::from(a.get("--out").ok_or("batch needs --out <dir>")?);
|
||||
let text = std::fs::read_to_string(actions_path).map_err(|e| format!("{actions_path}: {e}"))?;
|
||||
let actions = parse_actions(&text)?;
|
||||
let (actions, set) = load_actions(&text, a.get("--action"))?;
|
||||
let opts = export_opts(a)?;
|
||||
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
|
||||
// replace the originals (#492).
|
||||
@@ -399,9 +440,16 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
written.check(&target_text)?;
|
||||
let mut h = Headless::trusted_local();
|
||||
h.session.model_backend = model_backend.clone();
|
||||
// Steps that play another action find it in the set; the session's playback stack
|
||||
// stops an action that calls itself.
|
||||
h.session.actions.list = set.clone();
|
||||
h.open(input).map_err(|e| e.to_string())?;
|
||||
for (id, p) in &actions {
|
||||
h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?;
|
||||
let r = h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?;
|
||||
// A failed step inside a called action makes this file an error, not a saved result.
|
||||
if let Some(e) = photocraft_engine::actions_cmds::nested_failure(id, &r) {
|
||||
return Err(format!("`{id}`: {e}"));
|
||||
}
|
||||
}
|
||||
let r = h.save(None, Some(&target), Some(&ext), &opts).map_err(|e| e.to_string())?;
|
||||
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
|
||||
@@ -611,3 +659,54 @@ mod missing_font_warning_tests {
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod batch_action_set_tests {
|
||||
use super::*;
|
||||
|
||||
fn invoke(args: &[&str]) -> (i32, String, String) {
|
||||
let (mut output, mut errors) = (Vec::new(), Vec::new());
|
||||
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
|
||||
let code = run(&args, &mut output, &mut errors);
|
||||
(code, String::from_utf8(output).unwrap(), String::from_utf8(errors).unwrap())
|
||||
}
|
||||
|
||||
/// A batched action that plays another action of its set finds it in every file's session; a
|
||||
/// failure inside the called action fails the file, and a self-call stops instead of looping.
|
||||
#[test]
|
||||
fn batch_plays_an_action_that_calls_another_action_of_its_set() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-cli-action-set-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = |name: &str| dir.join(name).to_string_lossy().to_string();
|
||||
std::fs::create_dir_all(dir.join("in")).unwrap();
|
||||
for name in ["a", "b"] {
|
||||
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path(&format!("in/{name}.png"))]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
}
|
||||
let set = json!({"version": 1, "actions": [
|
||||
{"name": "Outer", "steps": [["actions.play", {"action": "Rotate"}]]},
|
||||
{"name": "Rotate", "steps": [["image.imageRotation.90cw", {}]]},
|
||||
{"name": "Calls bad", "steps": [["actions.play", {"action": "Bad"}]]},
|
||||
{"name": "Bad", "steps": [["layer.delete", {"layer": 999_999}]]},
|
||||
{"name": "Loop", "steps": [["actions.play", {"action": "Loop"}]]},
|
||||
]});
|
||||
std::fs::write(dir.join("actions.json"), set.to_string()).unwrap();
|
||||
let batch = |action: &str| invoke(&["batch", "--actions", &path("actions.json"), "--action", action, "--in", &path("in"), "--out", &path(action)]);
|
||||
|
||||
let (code, stdout, stderr) = batch("Outer");
|
||||
assert_eq!(code, 0, "{stdout}{stderr}");
|
||||
for name in ["a", "b"] {
|
||||
let (code, info, stderr) = invoke(&["info", &path(&format!("Outer/{name}.png")), "--compact"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
let info: Value = serde_json::from_str(&info).unwrap();
|
||||
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "rotated by the called action");
|
||||
}
|
||||
for action in ["Calls bad", "Loop"] {
|
||||
let (code, stdout, stderr) = batch(action);
|
||||
assert_ne!(code, 0, "{stdout}");
|
||||
assert_eq!(stderr.matches("FAIL").count(), 2, "{stderr}");
|
||||
assert!(!dir.join(action).join("a.png").exists(), "a file whose called action failed is not saved");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<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.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
|
||||
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
|
||||
<path d="m2.3 2.3 7.286 7.286" />
|
||||
<circle cx="11" cy="11" r="2" />
|
||||
<path d="M18 3.5h5" />
|
||||
<path d="M20.5 1v5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 594 B |
@@ -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="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
|
||||
<path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
|
||||
<path d="m2.3 2.3 7.286 7.286" />
|
||||
<circle cx="11" cy="11" r="2" />
|
||||
<path d="M18 3.5h5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 569 B |
@@ -98,3 +98,6 @@ sync_github_name = true
|
||||
|
||||
[people.FinnNk]
|
||||
sync_github_name = true
|
||||
|
||||
[people.TheTeslak]
|
||||
sync_github_name = true
|
||||
@@ -729,6 +729,8 @@ mod tests {
|
||||
| "path.moveHandle"
|
||||
| "path.bendSegment"
|
||||
| "path.convertPoint"
|
||||
| "path.addAnchor"
|
||||
| "path.deleteAnchor"
|
||||
| "path.clippingPath.set"
|
||||
| "path.rename"
|
||||
| "select.toWorkPath"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Point-level path edits, what Photoshop's Direct Selection (A) and Convert Point tools do on
|
||||
//! the canvas: move anchors, drag direction handles, bend segments and convert points. The
|
||||
//! Point-level path edits, what Photoshop's Direct Selection (A), Convert Point and Add / Delete
|
||||
//! Anchor Point tools do on the canvas: move anchors, drag direction handles, bend segments,
|
||||
//! convert points, and insert or remove anchors. The
|
||||
//! geometry is `photocraft_vector::edit`; the canvas previews a drag with it and commits the
|
||||
//! whole drag as one command (one history step).
|
||||
//!
|
||||
@@ -109,6 +110,38 @@ fn convert_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
edit_path(s, CMD, p, "Convert Point", |path| edit::convert_point(path, k, out))
|
||||
}
|
||||
|
||||
fn add_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.addAnchor";
|
||||
let k = knot(CMD, p)?;
|
||||
let t = match p.get("t") {
|
||||
Some(v) => v.as_f64().filter(|t| *t > 0.0 && *t < 1.0).ok_or_else(|| bad(CMD, "`t` must be strictly between 0 and 1"))?,
|
||||
None => 0.5,
|
||||
};
|
||||
let mut added = None;
|
||||
let mut r = edit_path(s, CMD, p, "Add Anchor Point", |path| {
|
||||
added = Some(edit::add_anchor(path, k, t)?);
|
||||
Ok(())
|
||||
})?;
|
||||
if let (Some(o), Some([sp, kn])) = (r.as_object_mut(), added) {
|
||||
o.insert("anchor".into(), json!({"subpath": sp, "knot": kn}));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn delete_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "path.deleteAnchor";
|
||||
let k = knot(CMD, p)?;
|
||||
let mut removed = false;
|
||||
let mut r = edit_path(s, CMD, p, "Delete Anchor Point", |path| {
|
||||
removed = edit::delete_anchor(path, k)?;
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(o) = r.as_object_mut() {
|
||||
o.insert("subpathRemoved".into(), json!(removed));
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#;
|
||||
let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result<Value>| CommandSpec {
|
||||
@@ -141,6 +174,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r#""subpath":i,"knot":j,"out":[x,y]? (none: corner with retracted handles; given: smooth with this out handle and its mirror)"#.into(),
|
||||
convert_point,
|
||||
),
|
||||
spec(
|
||||
"path.addAnchor",
|
||||
"Add Anchor Point",
|
||||
r#""subpath":i,"knot":j (the segment leaving it),"t":0<t<1=0.5 (where on the segment) (a curve is split there without changing its shape and gets a smooth anchor; a straight segment gets a corner) (the result also has anchor:{subpath,knot})"#.into(),
|
||||
add_anchor,
|
||||
),
|
||||
spec(
|
||||
"path.deleteAnchor",
|
||||
"Delete Anchor Point",
|
||||
r#""subpath":i,"knot":j (its neighbours are joined, keeping their handles; a subpath's last anchor removes the subpath; the path's only anchor is refused) (the result also has subpathRemoved:bool)"#.into(),
|
||||
delete_anchor,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -233,6 +278,87 @@ mod tests {
|
||||
assert_eq!(vm.path.subpaths[0].knots[0].anchor, photocraft_geom::Point::new(5.0, 5.0));
|
||||
}
|
||||
|
||||
fn curve() -> serde_json::Value {
|
||||
json!({"subpaths": [{"closed": false, "knots": [
|
||||
{"anchor": [10, 80], "in": [10, 80], "out": [10, 20]},
|
||||
{"anchor": [60, 50], "in": [40, 20], "out": [80, 80], "smooth": true},
|
||||
{"anchor": [110, 80], "in": [110, 20], "out": [110, 80]}
|
||||
]}]})
|
||||
}
|
||||
|
||||
fn knots(s: &Session) -> usize {
|
||||
work(s).subpaths.iter().map(|sp| sp.knots.len()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_are_added_and_deleted_in_one_undoable_step_each() {
|
||||
let mut s = session();
|
||||
s.execute("path.set", json!({"path": curve()})).unwrap();
|
||||
let before = work(&s);
|
||||
let steps = s.active().unwrap().history.entries().len();
|
||||
let r = s.execute("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 0.5})).unwrap();
|
||||
assert_eq!(r["anchor"], json!({"subpath": 0, "knot": 1}));
|
||||
assert_eq!((knots(&s), s.active().unwrap().history.entries().len()), (4, steps + 1));
|
||||
assert_eq!(s.active().unwrap().history.undo_label(), Some("Add Anchor Point"));
|
||||
assert!(work(&s).subpaths[0].knots[1].smooth);
|
||||
let added = work(&s);
|
||||
assert!(s.undo());
|
||||
assert_eq!(work(&s), before, "one undo restores the path exactly");
|
||||
assert!(s.redo());
|
||||
assert_eq!(work(&s), added);
|
||||
let r = s.execute("path.deleteAnchor", json!({"subpath": 0, "knot": 1})).unwrap();
|
||||
assert_eq!(r["subpathRemoved"], json!(false));
|
||||
assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete Anchor Point"));
|
||||
assert_eq!(knots(&s), 3);
|
||||
// Deleting the middle anchor of the original curve joins the ends with their own handles.
|
||||
s.execute("path.set", json!({"path": curve()})).unwrap();
|
||||
s.execute("path.deleteAnchor", json!({"subpath": 0, "knot": 1})).unwrap();
|
||||
let k = &work(&s).subpaths[0].knots;
|
||||
assert_eq!((k.len(), k[0].out_ctrl, k[1].in_ctrl), (2, before.subpaths[0].knots[0].out_ctrl, before.subpaths[0].knots[2].in_ctrl));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchor_tools_edit_saved_paths_shapes_and_vector_masks() {
|
||||
let mut s = session();
|
||||
s.execute("path.set", json!({"name": "Outline", "path": square()})).unwrap();
|
||||
let r = s.execute("path.deleteAnchor", json!({"name": "Outline", "subpath": 0, "knot": 0})).unwrap();
|
||||
assert_eq!((r["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), r["path"]["subpaths"][0]["closed"].clone()), (3, json!(true)));
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth})).unwrap();
|
||||
let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
// Top edge, then pull the new midpoint up: the layer re-renders from the edited path.
|
||||
let r = s.execute("path.addAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0, "t": 0.5})).unwrap();
|
||||
assert_eq!(anchor(&r, 1), [30.0, 10.0]);
|
||||
s.execute("path.moveAnchors", json!({"name": "layer", "layer": id, "anchors": [[0, 1]], "move": [0, -8]})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let photocraft_doc::LayerContent::Shape(ShapeLayer { live, cache, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") };
|
||||
assert!(live.is_none());
|
||||
assert_eq!(cache.as_ref().unwrap().content_bounds().y0, 2, "depth {depth}: re-rendered");
|
||||
s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 1})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let photocraft_doc::LayerContent::Shape(ShapeLayer { cache, path, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") };
|
||||
assert_eq!((path.subpaths[0].knots.len(), cache.as_ref().unwrap().content_bounds().y0), (4, 10), "depth {depth}");
|
||||
}
|
||||
let id = s.active().unwrap().active_layer.unwrap().0;
|
||||
s.execute("layer.vectorMask.add", json!({"layer": id, "path": square()})).unwrap();
|
||||
s.execute("path.addAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 3, "t": 0.5})).unwrap();
|
||||
let vm = s.active().unwrap().doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap();
|
||||
assert_eq!(vm.path.subpaths[0].knots[4].anchor, photocraft_geom::Point::new(10.0, 35.0), "the closing segment's midpoint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_anchor_of_a_shape_is_refused() {
|
||||
let mut s = session();
|
||||
let one = json!({"subpaths": [{"closed": false, "knots": [[10, 10], [50, 10]]}]});
|
||||
let id = s.execute("shape.create", json!({"kind": "path", "path": one, "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0})).unwrap();
|
||||
let steps = s.active().unwrap().history.entries().len();
|
||||
let e = s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0})).unwrap_err();
|
||||
assert!(e.to_string().contains("only anchor"), "{e}");
|
||||
assert_eq!(s.active().unwrap().history.entries().len(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_fail_without_an_edit() {
|
||||
let mut s = session();
|
||||
@@ -254,6 +380,18 @@ mod tests {
|
||||
("path.convertPoint", json!({"subpath": 0, "knot": 0, "out": "x"})),
|
||||
("path.convertPoint", json!({"name": "nope", "subpath": 0, "knot": 0})),
|
||||
("path.convertPoint", json!({"name": "layer", "subpath": 0, "knot": 0})),
|
||||
("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 0})),
|
||||
("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 1})),
|
||||
("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": -0.5})),
|
||||
("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": "half"})),
|
||||
("path.addAnchor", json!({"subpath": 0, "knot": 4})),
|
||||
("path.addAnchor", json!({"subpath": 1, "knot": 0})),
|
||||
("path.addAnchor", json!({"knot": 0})),
|
||||
("path.addAnchor", json!({"name": "nope", "subpath": 0, "knot": 0})),
|
||||
("path.deleteAnchor", json!({"subpath": 0, "knot": 4})),
|
||||
("path.deleteAnchor", json!({"subpath": 0, "knot": -1})),
|
||||
("path.deleteAnchor", json!({"subpath": 0})),
|
||||
("path.deleteAnchor", json!({"name": "layer", "subpath": 0, "knot": 0})),
|
||||
] {
|
||||
assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");
|
||||
}
|
||||
|
||||
@@ -897,9 +897,52 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
},
|
||||
},
|
||||
size_key("type.increaseSize", "Increase Type Size", "Cmd+Shift+.", |s, p| step_size(s, p, true, 2.0)),
|
||||
size_key("type.decreaseSize", "Decrease Type Size", "Cmd+Shift+,", |s, p| step_size(s, p, false, 2.0)),
|
||||
size_key("type.increaseSizeMore", "Increase Type Size by 10", "Cmd+Alt+Shift+.", |s, p| step_size(s, p, true, 10.0)),
|
||||
size_key("type.decreaseSizeMore", "Decrease Type Size by 10", "Cmd+Alt+Shift+,", |s, p| step_size(s, p, false, 10.0)),
|
||||
]
|
||||
}
|
||||
|
||||
fn has_type_layer(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
match st.active_layer.and_then(|id| st.doc.layer(id)) {
|
||||
Some(l) if matches!(l.content, LayerContent::Text(_)) => Ok(()),
|
||||
_ => Err("the active layer is not a type layer".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Photoshop's ⇧⌘> / ⇧⌘< (⌥ for bigger steps). On a US keyboard > and < share the . and , keys.
|
||||
fn size_key(id: &'static str, label: &'static str, shortcut: &'static str, run: fn(&mut Session, &Value) -> Result<Value>) -> CommandSpec {
|
||||
CommandSpec {
|
||||
id,
|
||||
label,
|
||||
menu: &[],
|
||||
shortcut: Some(shortcut),
|
||||
params: r##"{"layer":id?,"range":[startChar,endChar]? (default all),"by":pt? (as the layer appears)}"##,
|
||||
enabled: has_type_layer,
|
||||
journal: true,
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
||||
/// Grows or shrinks every character in the range by `by` points as the layer appears, so mixed
|
||||
/// sizes keep their differences and a scaled layer steps in the points its size field shows.
|
||||
fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result<Value> {
|
||||
let id = layer_id(s, p)?;
|
||||
let by = f32p(p, "by").filter(|v| v.is_finite()).unwrap_or(default_by).abs().min(TYPE_SIZE_MAX_PT as f32);
|
||||
with_text_layer(s, p, "Change Type Size", |t, _, _| {
|
||||
let m = t.transform.m;
|
||||
let scale = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() as f32;
|
||||
let scale = if scale.is_finite() && scale > 1e-3 { scale } else { 1.0 };
|
||||
let delta = if up { by } else { -by } / scale;
|
||||
let (a, b) = range_param(&t.text, p);
|
||||
style_range(t, a, b, &|st| st.size_pt = (st.size_pt + delta).clamp(TYPE_SIZE_MIN_PT as f32, TYPE_SIZE_MAX_PT as f32));
|
||||
Ok(())
|
||||
})?;
|
||||
info(s, &json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1036,6 +1079,42 @@ mod tests {
|
||||
assert_eq!(layer_name_of(&s, id), "Type Layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_keys_step_each_run_and_respect_layer_scale() {
|
||||
let mut s = session();
|
||||
let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap();
|
||||
s.execute("type.increaseSize", json!({})).unwrap();
|
||||
let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::<Vec<_>>();
|
||||
assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt");
|
||||
s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap();
|
||||
assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt");
|
||||
for _ in 0..2 {
|
||||
s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap();
|
||||
}
|
||||
assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size");
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(sizes(&s)[0], 2.0, "one undo step per press");
|
||||
|
||||
let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap();
|
||||
s.execute("type.increaseSize", json!({"layer": scaled})).unwrap();
|
||||
assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_keys_need_a_type_layer() {
|
||||
let mut s = session();
|
||||
assert!(s.execute("type.increaseSize", json!({})).is_err());
|
||||
let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap();
|
||||
s.execute("type.increaseSize", json!({"by": "big"})).unwrap();
|
||||
s.execute("type.increaseSize", json!({"by": -3})).unwrap();
|
||||
s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap();
|
||||
assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic");
|
||||
assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+."));
|
||||
assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_name_skips_leading_blank_lines() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -499,7 +499,7 @@ pub fn guess_from_postscript(ps: &str) -> ResolvedFont {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path::PathBuf>) {
|
||||
pub(crate) fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path::PathBuf>) {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
@@ -516,7 +516,7 @@ fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec<std::path
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn system_font_dirs() -> Vec<std::path::PathBuf> {
|
||||
pub(crate) fn system_font_dirs() -> Vec<std::path::PathBuf> {
|
||||
use std::path::PathBuf;
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let mut v = Vec::new();
|
||||
|
||||
@@ -26,6 +26,7 @@ pub mod psd;
|
||||
pub mod psd_styles;
|
||||
pub mod raster;
|
||||
pub mod render;
|
||||
pub mod scripts;
|
||||
pub mod served;
|
||||
pub mod spell;
|
||||
pub mod warp;
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
//! UI fallback fonts for the non-CJK scripts the bundled Inter / JetBrains Mono don't draw
|
||||
//! (Thai, Arabic, Hebrew, the Indic scripts, ...): which characters belong to which script, and
|
||||
//! which installed font files to try for it.
|
||||
//!
|
||||
//! Candidates come from the file names in the platform font directories (the same directories
|
||||
//! [`crate::fonts::FontDb`] scans), listed once per process and only when first asked for, so
|
||||
//! nothing is read at startup and no path is hard-coded per distribution. Noto fonts are matched
|
||||
//! by their family-derived file names (`NotoSansThai-Regular.ttf`, `NotoSansThai[wght].ttf`),
|
||||
//! platform fonts by their known file names (Leelawadee UI, Nirmala UI, Segoe UI, Geeza Pro,
|
||||
//! Kohinoor, DejaVu Sans, Lohit, ...). A file name is only a hint: callers check that a face
|
||||
//! really maps the character ([`covering_face`]) before using it. CJK has its own,
|
||||
//! locale-ordered lists ([`crate::cjk`]).
|
||||
|
||||
/// A script that needs a UI fallback font.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Script {
|
||||
Thai,
|
||||
Lao,
|
||||
Khmer,
|
||||
Myanmar,
|
||||
Tibetan,
|
||||
Arabic,
|
||||
Hebrew,
|
||||
Armenian,
|
||||
Georgian,
|
||||
Ethiopic,
|
||||
Devanagari,
|
||||
Bengali,
|
||||
Gurmukhi,
|
||||
Gujarati,
|
||||
Oriya,
|
||||
Tamil,
|
||||
Telugu,
|
||||
Kannada,
|
||||
Malayalam,
|
||||
Sinhala,
|
||||
}
|
||||
|
||||
impl Script {
|
||||
pub const ALL: [Script; 20] = [
|
||||
Script::Thai,
|
||||
Script::Lao,
|
||||
Script::Khmer,
|
||||
Script::Myanmar,
|
||||
Script::Tibetan,
|
||||
Script::Arabic,
|
||||
Script::Hebrew,
|
||||
Script::Armenian,
|
||||
Script::Georgian,
|
||||
Script::Ethiopic,
|
||||
Script::Devanagari,
|
||||
Script::Bengali,
|
||||
Script::Gurmukhi,
|
||||
Script::Gujarati,
|
||||
Script::Oriya,
|
||||
Script::Tamil,
|
||||
Script::Telugu,
|
||||
Script::Kannada,
|
||||
Script::Malayalam,
|
||||
Script::Sinhala,
|
||||
];
|
||||
|
||||
/// Font file names for this script, most preferred first: lowercase, without extension,
|
||||
/// spaces, underscores or style suffix (`NotoSansThai-Bold.ttf` and `NotoSansThai[wght].ttf`
|
||||
/// are both `notosansthai`). Noto first (the usual Linux font), then Windows, macOS and
|
||||
/// other Linux families.
|
||||
fn file_names(self) -> &'static [&'static str] {
|
||||
use Script::*;
|
||||
match self {
|
||||
Thai => &[
|
||||
"notosansthai",
|
||||
"notosansthailooped",
|
||||
"notosansthaiui",
|
||||
"notoserifthai",
|
||||
"leelawui",
|
||||
"leelawad",
|
||||
"tahoma",
|
||||
"thonburi",
|
||||
"sukhumvitset",
|
||||
"ayuthaya",
|
||||
"loma",
|
||||
"garuda",
|
||||
"waree",
|
||||
"kinnari",
|
||||
"norasi",
|
||||
],
|
||||
Lao => &["notosanslao", "notosanslaoui", "notoseriflao", "leelawui", "laosangammn", "laomn", "phetsarathot", "saysetthaot"],
|
||||
Khmer => &["notosanskhmer", "notosanskhmerui", "notoserifkhmer", "leelawui", "daunpenh", "khmersangammn", "khmermn", "khmeros", "khmerossys"],
|
||||
Myanmar => &["notosansmyanmar", "notosansmyanmarui", "notoserifmyanmar", "mmrtext", "myanmarsangammn", "myanmarmn", "padauk"],
|
||||
Tibetan => &["notoseriftibetan", "himalaya", "kailasa", "jomolhari", "tibetanmachineuni"],
|
||||
Arabic => &[
|
||||
"notosansarabic",
|
||||
"notosansarabicui",
|
||||
"notonaskharabic",
|
||||
"notonaskharabicui",
|
||||
"notokufiarabic",
|
||||
"segoeui",
|
||||
"tahoma",
|
||||
"geezapro",
|
||||
"sfarabic",
|
||||
"dejavusans",
|
||||
"kacstone",
|
||||
"kacstbook",
|
||||
"amiri",
|
||||
"arial",
|
||||
],
|
||||
Hebrew => &["notosanshebrew", "notoserifhebrew", "segoeui", "arialhb", "sfhebrew", "dejavusans", "arial", "freesans", "culmus"],
|
||||
Armenian => &["notosansarmenian", "notoserifarmenian", "segoeui", "sylfaen", "mshtakan", "dejavusans", "freesans"],
|
||||
Georgian => &["notosansgeorgian", "notoserifgeorgian", "segoeui", "sylfaen", "dejavusans", "freesans"],
|
||||
Ethiopic => &["notosansethiopic", "notoserifethiopic", "ebrima", "kefa", "abyssinicasil"],
|
||||
Devanagari => &[
|
||||
"notosansdevanagari",
|
||||
"notosansdevanagariui",
|
||||
"notoserifdevanagari",
|
||||
"nirmala",
|
||||
"mangal",
|
||||
"kohinoor",
|
||||
"kohinoordevanagari",
|
||||
"itfdevanagari",
|
||||
"devanagarimt",
|
||||
"devanagarisangammn",
|
||||
"lohitdevanagari",
|
||||
"lohit-devanagari",
|
||||
"gargi",
|
||||
"freesans",
|
||||
],
|
||||
Bengali => &[
|
||||
"notosansbengali",
|
||||
"notosansbengaliui",
|
||||
"notoserifbengali",
|
||||
"nirmala",
|
||||
"vrinda",
|
||||
"kohinoorbangla",
|
||||
"banglasangammn",
|
||||
"banglamn",
|
||||
"lohitbengali",
|
||||
"lohit-bengali",
|
||||
"lohit-assamese",
|
||||
],
|
||||
Gurmukhi => &[
|
||||
"notosansgurmukhi",
|
||||
"notosansgurmukhiui",
|
||||
"notoserifgurmukhi",
|
||||
"nirmala",
|
||||
"raavi",
|
||||
"gurmukhisangammn",
|
||||
"gurmukhimn",
|
||||
"lohit-gurmukhi",
|
||||
"lohit-punjabi",
|
||||
],
|
||||
Gujarati => &[
|
||||
"notosansgujarati",
|
||||
"notosansgujaratiui",
|
||||
"notoserifgujarati",
|
||||
"nirmala",
|
||||
"shruti",
|
||||
"kohinoorgujarati",
|
||||
"gujaratisangammn",
|
||||
"gujaratimt",
|
||||
"lohit-gujarati",
|
||||
],
|
||||
Oriya => &["notosansoriya", "notosansoriyaui", "notoseriforiya", "nirmala", "kalinga", "oriyasangammn", "oriyamn", "lohit-odia", "lohit-oriya"],
|
||||
Tamil => &["notosanstamil", "notosanstamilui", "notoseriftamil", "nirmala", "latha", "tamilsangammn", "tamilmn", "lohit-tamil"],
|
||||
Telugu => {
|
||||
&["notosanstelugu", "notosansteluguui", "notoseriftelugu", "nirmala", "gautami", "kohinoortelugu", "telugusangammn", "telugumn", "lohit-telugu"]
|
||||
}
|
||||
Kannada => &["notosanskannada", "notosanskannadaui", "notoserifkannada", "nirmala", "tunga", "kannadasangammn", "kannadamn", "lohit-kannada"],
|
||||
Malayalam => {
|
||||
&["notosansmalayalam", "notosansmalayalamui", "notoserifmalayalam", "nirmala", "kartika", "malayalamsangammn", "malayalammn", "lohit-malayalam"]
|
||||
}
|
||||
Sinhala => &["notosanssinhala", "notosanssinhalaui", "notoserifsinhala", "nirmala", "iskpota", "sinhalasangammn", "sinhalamn", "lklug"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The script of a character that needs a non-CJK fallback font, or `None`.
|
||||
pub fn classify(c: char) -> Option<Script> {
|
||||
use Script::*;
|
||||
Some(match c as u32 {
|
||||
0x0E00..=0x0E7F => Thai,
|
||||
0x0E80..=0x0EFF => Lao,
|
||||
0x1780..=0x17FF | 0x19E0..=0x19FF => Khmer,
|
||||
0x1000..=0x109F | 0xA9E0..=0xA9FF | 0xAA60..=0xAA7F => Myanmar,
|
||||
0x0F00..=0x0FFF => Tibetan,
|
||||
0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => Arabic,
|
||||
0x0590..=0x05FF | 0xFB1D..=0xFB4F => Hebrew,
|
||||
0x0530..=0x058F | 0xFB13..=0xFB17 => Armenian,
|
||||
0x10A0..=0x10FF | 0x1C90..=0x1CBF | 0x2D00..=0x2D2F => Georgian,
|
||||
0x1200..=0x139F | 0x2D80..=0x2DDF | 0xAB00..=0xAB2F => Ethiopic,
|
||||
0x0900..=0x097F | 0xA8E0..=0xA8FF => Devanagari,
|
||||
0x0980..=0x09FF => Bengali,
|
||||
0x0A00..=0x0A7F => Gurmukhi,
|
||||
0x0A80..=0x0AFF => Gujarati,
|
||||
0x0B00..=0x0B7F => Oriya,
|
||||
0x0B80..=0x0BFF => Tamil,
|
||||
0x0C00..=0x0C7F => Telugu,
|
||||
0x0C80..=0x0CFF => Kannada,
|
||||
0x0D00..=0x0D7F => Malayalam,
|
||||
0x0D80..=0x0DFF => Sinhala,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `(name, stem, style rank)` of a font file: [`Script::file_names`] form, the file stem, and 0
|
||||
/// for the regular face, 1 for a variable font, 2 for other weights, 3 for bold, italic and
|
||||
/// condensed faces. Non-font files give `None`.
|
||||
fn file_key(path: &std::path::Path) -> Option<(String, &str, u8)> {
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
if !matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") {
|
||||
return None;
|
||||
}
|
||||
let stem = path.file_stem()?.to_str()?;
|
||||
let squash = |s: &str| s.chars().filter(|c| !matches!(c, ' ' | '_')).collect::<String>().to_lowercase();
|
||||
let style = |s: &str| {
|
||||
let s = s.to_ascii_lowercase();
|
||||
if s.is_empty() || s == "-regular" {
|
||||
0
|
||||
} else if s.starts_with('[') {
|
||||
1
|
||||
} else if ["bold", "italic", "oblique", "condensed", "narrow", "black", "heavy", "thin", "light"].iter().any(|w| s.contains(w)) {
|
||||
3
|
||||
} else {
|
||||
2
|
||||
}
|
||||
};
|
||||
let cut = stem.find(['-', '[']).unwrap_or(stem.len());
|
||||
let (base, rest) = stem.split_at(cut);
|
||||
Some((squash(base), stem, style(rest)))
|
||||
}
|
||||
|
||||
/// Font files among `files` that may cover `script`, most preferred first (at most
|
||||
/// `MAX_CANDIDATES`). Pure, so tests pass their own listing.
|
||||
pub fn candidates(script: Script, files: &[std::path::PathBuf]) -> Vec<std::path::PathBuf> {
|
||||
const MAX_CANDIDATES: usize = 16;
|
||||
let names = script.file_names();
|
||||
let mut ranked: Vec<(usize, u8, &std::path::PathBuf)> = files
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let (base, stem, style) = file_key(p)?;
|
||||
// A name with a hyphen ("lohit-tamil") matches the whole stem.
|
||||
let full = stem.to_lowercase().replace([' ', '_'], "");
|
||||
let rank = names.iter().position(|n| *n == base || *n == full)?;
|
||||
Some((rank, if *names.get(rank)? == full { 0 } else { style }, p))
|
||||
})
|
||||
.collect();
|
||||
ranked.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)));
|
||||
ranked.into_iter().take(MAX_CANDIDATES).map(|(_, _, p)| p.clone()).collect()
|
||||
}
|
||||
|
||||
/// Every font file in the platform font directories, listed on first use and cached for the
|
||||
/// process (names only; nothing is opened).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn system_font_files() -> &'static [std::path::PathBuf] {
|
||||
static FILES: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
|
||||
FILES.get_or_init(|| {
|
||||
let mut files = Vec::new();
|
||||
for d in crate::fonts::system_font_dirs() {
|
||||
crate::fonts::collect_font_files(&d, 0, &mut files);
|
||||
}
|
||||
files.sort();
|
||||
files.dedup();
|
||||
files
|
||||
})
|
||||
}
|
||||
|
||||
/// Installed font files that may cover `script`, most preferred first.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn system_candidates(script: Script) -> Vec<std::path::PathBuf> {
|
||||
candidates(script, system_font_files())
|
||||
}
|
||||
|
||||
/// Index of the first face in `bytes` (a font or a collection) whose character map has `c`.
|
||||
/// `None` for fonts without it and for data that doesn't parse. Never panics.
|
||||
pub fn covering_face(bytes: &[u8], c: char) -> Option<u32> {
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::raw::FileRef;
|
||||
match FileRef::new(bytes).ok()? {
|
||||
FileRef::Font(f) => f.charmap().map(c).map(|_| 0),
|
||||
FileRef::Collection(col) => col.iter().position(|f| f.is_ok_and(|f| f.charmap().map(c).is_some())).and_then(|i| u32::try_from(i).ok()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn classifies_scripts_and_leaves_latin_and_cjk_alone() {
|
||||
for (c, s) in [
|
||||
('ส', Script::Thai),
|
||||
('ม', Script::Thai),
|
||||
('ر', Script::Arabic),
|
||||
('ﻻ', Script::Arabic),
|
||||
('ש', Script::Hebrew),
|
||||
('न', Script::Devanagari),
|
||||
('த', Script::Tamil),
|
||||
('ក', Script::Khmer),
|
||||
('ა', Script::Georgian),
|
||||
] {
|
||||
assert_eq!(classify(c), Some(s), "{c}");
|
||||
}
|
||||
for c in ['A', 'é', 'Ж', 'Ω', '–', '日', 'カ', '한', ' '] {
|
||||
assert_eq!(classify(c), None, "{c}");
|
||||
}
|
||||
for s in Script::ALL {
|
||||
assert!(!s.file_names().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidates_match_file_names_regular_first_across_layouts() {
|
||||
let files: Vec<PathBuf> = [
|
||||
"/usr/share/fonts/google-noto/NotoSansThai-Bold.ttf",
|
||||
"/usr/share/fonts/google-noto-vf/NotoSansThai[wght].ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoSansThai-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoSansThaiLooped-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/noto/NotoSansThaana-Regular.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
|
||||
"/usr/share/fonts/truetype/lohit-devanagari/Lohit-Devanagari.ttf",
|
||||
"/usr/share/fonts/Lohit-Tamil.ttf",
|
||||
"/mnt/c/Windows/Fonts/LeelawUI.ttf",
|
||||
"/mnt/c/Windows/Fonts/Nirmala.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Thonburi.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Kohinoor.ttc",
|
||||
"/usr/share/fonts/README.txt",
|
||||
]
|
||||
.into_iter()
|
||||
.map(PathBuf::from)
|
||||
.collect();
|
||||
let names = |s| candidates(s, &files).into_iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
names(Script::Thai),
|
||||
["NotoSansThai-Regular.ttf", "NotoSansThai[wght].ttf", "NotoSansThai-Bold.ttf", "NotoSansThaiLooped-Regular.ttf", "LeelawUI.ttf", "Thonburi.ttc"]
|
||||
);
|
||||
assert_eq!(names(Script::Arabic), ["DejaVuSans.ttf", "DejaVuSans-Bold.ttf"]);
|
||||
assert_eq!(names(Script::Devanagari), ["Nirmala.ttc", "Kohinoor.ttc", "Lohit-Devanagari.ttf"]);
|
||||
assert_eq!(names(Script::Tamil), ["Nirmala.ttc", "Lohit-Tamil.ttf"]);
|
||||
assert!(names(Script::Ethiopic).is_empty());
|
||||
assert!(candidates(Script::Thai, &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn covering_face_checks_the_character_map_and_rejects_garbage() {
|
||||
let inter = crate::fonts::INTER_REGULAR.as_slice();
|
||||
assert_eq!(covering_face(inter, 'A'), Some(0));
|
||||
assert_eq!(covering_face(inter, 'ส'), None);
|
||||
assert_eq!(covering_face(inter, 'ر'), None);
|
||||
for bad in [&b""[..], b"ttcf", b"ttcf\0\x01\0\0\0\0\0\x02\xff\xff\xff\xff\0\0\0\x10", b"\0\x01\0\0\0\xff"] {
|
||||
assert_eq!(covering_face(bad, 'A'), None);
|
||||
}
|
||||
}
|
||||
|
||||
/// With the real system fonts, each script that has a candidate installed has one that
|
||||
/// covers it (skipped per script when the machine has none, e.g. CI Linux).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn system_candidates_cover_their_script() {
|
||||
for (s, c) in [(Script::Thai, 'ส'), (Script::Arabic, 'ر'), (Script::Hebrew, 'ש'), (Script::Devanagari, 'न')] {
|
||||
let found = system_candidates(s).iter().take(4).any(|p| std::fs::read(p).ok().and_then(|b| covering_face(&b, c)).is_some());
|
||||
eprintln!("{s:?}: {}", if found { "covered" } else { "no installed font" });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Add Anchor Point and Delete Anchor Point tools (P group with the Pen, #1044), as in Photoshop.
|
||||
//! They edit the paths Direct Selection edits, front first: the targeted vector mask or the active
|
||||
//! shape layer's path, then the work path.
|
||||
//!
|
||||
//! * Add Anchor Point: hovering a segment highlights it and shows where the anchor would go; a
|
||||
//! click inserts it there (`path.addAnchor`). A curve is split without changing its shape.
|
||||
//! * Delete Anchor Point: hovering an anchor highlights it; a click removes it
|
||||
//! (`path.deleteAnchor`), joining its neighbours.
|
||||
//! * ⌥ swaps the two tools and ⌘/Ctrl is Direct Selection (`direct_select`) while held.
|
||||
//!
|
||||
//! Each click is one command and one history step; a click on nothing it can edit does nothing.
|
||||
|
||||
use egui::{Color32, Modifiers, Pos2, Stroke};
|
||||
use photocraft_doc::vector::Path;
|
||||
use photocraft_geom::Point;
|
||||
use photocraft_vector::edit::{self, Hit};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::canvas::ToolEvent;
|
||||
use crate::direct_select::{DirectSelection, PathRef};
|
||||
use crate::state::Tool;
|
||||
|
||||
/// The anchor tool in effect, if the current tool is one: ⌥ swaps Add and Delete.
|
||||
pub fn effective(tool: Tool, mods: Modifiers) -> Option<Tool> {
|
||||
let (add, delete) = (Tool::AddAnchorPoint, Tool::DeleteAnchorPoint);
|
||||
match tool {
|
||||
Tool::AddAnchorPoint => Some(if mods.alt { delete } else { add }),
|
||||
Tool::DeleteAnchorPoint => Some(if mods.alt { add } else { delete }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click at `p` would edit with `tool`: the frontmost path under the pointer and the
|
||||
/// segment (Add) or anchor (Delete) hit on it. An anchor hit with Add, or a segment with Delete,
|
||||
/// edits nothing.
|
||||
fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> {
|
||||
let tol = 6.0 / f64::from(app.point_zoom().max(0.01));
|
||||
let (r, path, hit) =
|
||||
crate::direct_select::candidates(app).into_iter().find_map(|(r, path)| edit::hit(&path, Point::new(p[0], p[1]), tol, &[]).map(|h| (r, path, h)))?;
|
||||
match (tool, hit) {
|
||||
(Tool::AddAnchorPoint, Hit::Segment(..)) | (Tool::DeleteAnchorPoint, Hit::Anchor(_)) => Some((r, path, hit)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Canvas pointer events for the anchor tools; false when the current tool isn't one.
|
||||
pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {
|
||||
let Some(tool) = effective(app.ui.tool, mods) else { return false };
|
||||
if let ToolEvent::Down { x, y, .. } = ev {
|
||||
click(app, tool, [x, y]);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn click(app: &mut PhotocraftApp, tool: Tool, p: [f64; 2]) {
|
||||
let Some((r, _, hit)) = target(app, tool, p) else { return };
|
||||
let (id, mut params) = match hit {
|
||||
Hit::Segment([s, k], t) => ("path.addAnchor", serde_json::json!({"subpath": s, "knot": k, "t": t})),
|
||||
Hit::Anchor([s, k]) => ("path.deleteAnchor", serde_json::json!({"subpath": s, "knot": k})),
|
||||
Hit::Handle(..) => return,
|
||||
};
|
||||
// A hit right at a segment's end is an anchor (anchors win the hit test), so `t` is inside.
|
||||
if let (Some(o), Some(t)) = (params.as_object_mut(), r.params().as_object()) {
|
||||
o.extend(t.clone());
|
||||
}
|
||||
match app.run(id, params) {
|
||||
// The anchors shift: a Direct Selection on this path would point at the wrong ones.
|
||||
Ok(_) if app.ui.direct_selection.target == Some(r) => app.ui.direct_selection = DirectSelection { target: Some(r), ..Default::default() },
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The hover feedback over the Direct Selection overlay: Add highlights the segment under the
|
||||
/// pointer and shows the anchor a click would add; Delete highlights the anchor it would remove.
|
||||
pub fn draw_hover(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32, mods: Modifiers) {
|
||||
let (Some(tool), Some(p)) = (effective(app.ui.tool, mods), app.hover_doc) else { return };
|
||||
if mods.command {
|
||||
return;
|
||||
}
|
||||
let Some((_, path, hit)) = target(app, tool, p) else { return };
|
||||
match hit {
|
||||
Hit::Segment([s, k], t) => {
|
||||
let Some(seg) = path.subpaths.get(s).and_then(|sp| sp.segments().get(k).copied()) else { return };
|
||||
let pts: Vec<Pos2> = (0..=48).map(|i| edit::eval(&seg, f64::from(i) / 48.0)).map(|q| to_scr([q.x, q.y])).collect();
|
||||
painter.add(egui::Shape::line(pts, Stroke::new(2.5, accent)));
|
||||
let q = edit::eval(&seg, t);
|
||||
crate::vector_ui::draw_anchor(painter, to_scr([q.x, q.y]), false, accent);
|
||||
}
|
||||
Hit::Anchor([s, k]) => {
|
||||
let Some(kn) = path.subpaths.get(s).and_then(|sp| sp.knots.get(k)) else { return };
|
||||
let c = to_scr([kn.anchor.x, kn.anchor.y]);
|
||||
painter.rect_stroke(egui::Rect::from_center_size(c, egui::vec2(11.0, 11.0)), 0.0, Stroke::new(1.5, accent), egui::StrokeKind::Inside);
|
||||
crate::vector_ui::draw_anchor(painter, c, true, accent);
|
||||
}
|
||||
Hit::Handle(..) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "anchor_tools_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,152 @@
|
||||
//! #1044: the Add Anchor Point and Delete Anchor Point tools insert and remove anchors on the
|
||||
//! paths Direct Selection edits, one history step per click.
|
||||
|
||||
use egui::Modifiers;
|
||||
use photocraft_doc::vector::Path;
|
||||
use photocraft_geom::Point;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::canvas::{ToolEvent, tool_event};
|
||||
use crate::direct_select::PathRef;
|
||||
use crate::state::Tool;
|
||||
|
||||
fn app(tool: Tool) -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.sync_views();
|
||||
app.ui.tool = tool;
|
||||
app
|
||||
}
|
||||
|
||||
/// A square work path; knot 1 at (120, 40) is smooth, so the top edge (0 → 1) is a curve.
|
||||
fn with_path(app: &mut PhotocraftApp) {
|
||||
let path = json!({"subpaths": [{"closed": true, "knots": [
|
||||
[40, 40],
|
||||
{"anchor": [120, 40], "in": [100, 20], "out": [140, 60], "smooth": true},
|
||||
[120, 120],
|
||||
[40, 120],
|
||||
]}]});
|
||||
app.run("path.set", json!({"name": "work", "path": path})).unwrap();
|
||||
}
|
||||
|
||||
fn work(app: &PhotocraftApp) -> Path {
|
||||
app.session.active().unwrap().doc.work_path.clone().unwrap()
|
||||
}
|
||||
|
||||
fn steps(app: &PhotocraftApp) -> usize {
|
||||
app.session.active().unwrap().history.entries().len()
|
||||
}
|
||||
|
||||
fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) {
|
||||
tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, mods);
|
||||
tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, mods);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_tools_join_the_pen_group() {
|
||||
let group: Vec<Tool> = Tool::ALL.iter().copied().filter(|t| t.key() == 'P').collect();
|
||||
assert_eq!(group, vec![Tool::Pen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint], "P cycles Pen → Add → Delete");
|
||||
let mut app = app(Tool::Brush);
|
||||
app.ui.tool = Tool::from_name("addAnchorPoint").unwrap();
|
||||
assert_eq!(app.ui.tool, Tool::AddAnchorPoint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_on_a_straight_segment_inserts_a_corner_in_one_step() {
|
||||
let mut app = app(Tool::AddAnchorPoint);
|
||||
with_path(&mut app);
|
||||
let (before, n) = (work(&app), steps(&app));
|
||||
click(&mut app, [80.0, 121.0], Modifiers::NONE);
|
||||
let p = work(&app);
|
||||
assert_eq!(p.subpaths[0].knots.len(), 5);
|
||||
let k = p.subpaths[0].knots[3];
|
||||
assert!(!k.smooth && (k.anchor.y - 120.0).abs() < 1e-9 && (k.anchor.x - 80.0).abs() < 1.0, "a corner on the bottom edge: {k:?}");
|
||||
assert_eq!(steps(&app), n + 1);
|
||||
assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point"));
|
||||
assert!(app.session.undo());
|
||||
assert_eq!(work(&app), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_on_a_curve_splits_it_where_clicked() {
|
||||
let mut app = app(Tool::AddAnchorPoint);
|
||||
with_path(&mut app);
|
||||
let seg = work(&app).subpaths[0].segments()[0];
|
||||
let on = photocraft_vector::edit::eval(&seg, 0.5);
|
||||
click(&mut app, [on.x, on.y], Modifiers::NONE);
|
||||
let p = work(&app);
|
||||
let k = p.subpaths[0].knots[1];
|
||||
assert!(k.smooth && (k.anchor.x - on.x).hypot(k.anchor.y - on.y) < 0.2, "a smooth anchor where clicked: {k:?}");
|
||||
// The two halves still pass through the old curve's quarter points.
|
||||
let halves = &p.subpaths[0].segments()[..2];
|
||||
for t in [0.25, 0.75] {
|
||||
let old = photocraft_vector::edit::eval(&seg, t);
|
||||
let near = halves
|
||||
.iter()
|
||||
.flat_map(|s| (0..=400).map(move |i| photocraft_vector::edit::eval(s, f64::from(i) / 400.0)))
|
||||
.fold(f64::MAX, |d, q| d.min((q.x - old.x).hypot(q.y - old.y)));
|
||||
assert!(near < 0.1, "t={t}: {near}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_removes_the_clicked_anchor_and_alt_swaps_the_tools() {
|
||||
let mut app = app(Tool::DeleteAnchorPoint);
|
||||
with_path(&mut app);
|
||||
let n = steps(&app);
|
||||
click(&mut app, [120.0, 120.0], Modifiers::NONE);
|
||||
let p = work(&app);
|
||||
assert_eq!((p.subpaths[0].knots.len(), p.subpaths[0].closed), (3, true));
|
||||
assert_eq!(p.subpaths[0].knots[2].anchor, Point::new(40.0, 120.0));
|
||||
assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point"));
|
||||
// ⌥ with Delete adds; ⌥ with Add deletes.
|
||||
click(&mut app, [80.0, 120.0], Modifiers::ALT);
|
||||
assert_eq!(work(&app).subpaths[0].knots.len(), 3, "the bottom edge is gone; ⌥ on empty canvas adds nothing");
|
||||
click(&mut app, [40.0, 80.0], Modifiers::ALT);
|
||||
assert_eq!(work(&app).subpaths[0].knots.len(), 4);
|
||||
app.ui.tool = Tool::AddAnchorPoint;
|
||||
click(&mut app, [40.0, 80.0], Modifiers::ALT);
|
||||
assert_eq!(work(&app).subpaths[0].knots.len(), 3);
|
||||
assert_eq!(steps(&app), n + 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicks_on_nothing_editable_change_nothing() {
|
||||
let mut app = app(Tool::AddAnchorPoint);
|
||||
with_path(&mut app);
|
||||
let (before, n) = (work(&app), steps(&app));
|
||||
click(&mut app, [80.0, 80.0], Modifiers::NONE);
|
||||
click(&mut app, [40.0, 40.0], Modifiers::NONE);
|
||||
app.ui.tool = Tool::DeleteAnchorPoint;
|
||||
click(&mut app, [80.0, 80.0], Modifiers::NONE);
|
||||
click(&mut app, [40.0, 80.0], Modifiers::NONE);
|
||||
assert_eq!((work(&app), steps(&app)), (before, n), "empty canvas, an anchor with Add, a segment with Delete");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_layer_paths_are_edited_and_a_direct_selection_is_cleared() {
|
||||
let mut app = app(Tool::DirectSelection);
|
||||
let id = app.run("shape.create", json!({"kind": "rect", "rect": [20, 20, 60, 60], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap();
|
||||
click(&mut app, [80.0, 80.0], Modifiers::NONE);
|
||||
assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Layer(id)), vec![[0, 2]]));
|
||||
app.ui.tool = Tool::AddAnchorPoint;
|
||||
click(&mut app, [50.0, 20.0], Modifiers::NONE);
|
||||
let info = app.run("shape.info", json!({"layer": id})).unwrap();
|
||||
assert_eq!(info["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), 5);
|
||||
assert!(app.ui.direct_selection.anchors.is_empty(), "the selection no longer points at a shifted anchor");
|
||||
app.ui.tool = Tool::DeleteAnchorPoint;
|
||||
click(&mut app, [20.0, 80.0], Modifiers::NONE);
|
||||
let info = app.run("shape.info", json!({"layer": id})).unwrap();
|
||||
assert_eq!(info["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_shows_plus_or_minus() {
|
||||
use crate::tool_feedback::{Badge, badge};
|
||||
let app = app(Tool::AddAnchorPoint);
|
||||
assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add));
|
||||
assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract));
|
||||
assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract));
|
||||
assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::COMMAND), None, "⌘ is Direct Selection");
|
||||
}
|
||||
+221
-191
@@ -2479,214 +2479,225 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
None => paint_dots(ui, rect, app.session.prefs().interface.show_canvas_dots),
|
||||
}
|
||||
let border = app.session.prefs().interface.canvas_border;
|
||||
let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow;
|
||||
// Drop shadow, checkerboard, document image.
|
||||
let img_rect = xf.doc_rect(doc.bounds());
|
||||
// Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas
|
||||
// (whose edge blends into them) and without its shadow.
|
||||
let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output);
|
||||
let drop_shadow = drop_shadow && !beyond;
|
||||
// Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless
|
||||
// Preferences › Performance › Low Resolution Previews is off.
|
||||
let mut on_gpu = false;
|
||||
// A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader
|
||||
// has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform.
|
||||
let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect);
|
||||
if app.gpu.is_some()
|
||||
&& gpu_ok
|
||||
&& let Some((k, key, preview_size)) =
|
||||
ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx))
|
||||
{
|
||||
on_gpu = true;
|
||||
let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)];
|
||||
let params = crate::gpu_canvas::ViewParams {
|
||||
doc: key,
|
||||
doc_size: preview_size,
|
||||
zoom: view.zoom * k as f32 / ppp,
|
||||
// A size-changing preview grows around the old image center; keep the view's pan.
|
||||
center: [
|
||||
view.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0,
|
||||
view.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0,
|
||||
],
|
||||
rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 },
|
||||
shadow: {
|
||||
let t = crate::theme::Tokens::get(&ctx);
|
||||
!t.bevel && !t.pro && drop_shadow
|
||||
},
|
||||
pixel_grid: false,
|
||||
view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(),
|
||||
display: sync_display_lut(app, &doc, key, output),
|
||||
output: output.unwrap_or(0),
|
||||
hdr: hdr_preview(app, &doc),
|
||||
};
|
||||
crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);
|
||||
} else if gpu_ok && ensure_gpu(app, idx, visible_doc_rect(&xf)) {
|
||||
on_gpu = true;
|
||||
app.perf.gpu = true;
|
||||
// Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs).
|
||||
let params = crate::gpu_canvas::ViewParams {
|
||||
doc: doc.id.0,
|
||||
doc_size: [doc.size.width, doc.size.height],
|
||||
zoom: point_zoom,
|
||||
center: view.center,
|
||||
rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 },
|
||||
shadow: {
|
||||
let t = crate::theme::Tokens::get(&ctx);
|
||||
!t.bevel && !t.pro && drop_shadow
|
||||
},
|
||||
pixel_grid,
|
||||
view_key: egui::Id::new(("pc-canvas", ctx.viewport_id(), idx)).value(),
|
||||
display: sync_display_lut(app, &doc, doc.id.0, output),
|
||||
output: output.unwrap_or(0),
|
||||
hdr: hdr_preview(app, &doc),
|
||||
};
|
||||
crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);
|
||||
} else {
|
||||
if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow {
|
||||
painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0));
|
||||
}
|
||||
let rotated = view.rotation.abs() > 0.05;
|
||||
let size = [doc.size.width as f32, doc.size.height as f32];
|
||||
match app.session.prefs().transparency_and_gamut.square() {
|
||||
Some(square) => {
|
||||
let checker_id = checker(app, &ctx);
|
||||
if rotated {
|
||||
let tiles = vec2(size[0], size[1]) / (2.0 * square);
|
||||
paint_mapped_image(&painter, &xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE);
|
||||
} else {
|
||||
let tiles = img_rect.size() / (2.0 * square);
|
||||
painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE);
|
||||
// Default-mode Crop changes its camera during input. Defer its image until the new camera
|
||||
// is known; other tools keep their existing paint order and texture/outline snapshots.
|
||||
let crop_camera = primary && crate::crop_mode::moves_image(app);
|
||||
let paint_canvas = |app: &mut PhotocraftApp, ui: &egui::Ui, view: &View, xf: ViewXform| {
|
||||
let point_zoom = view.zoom / ppp;
|
||||
let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow;
|
||||
// Drop shadow, checkerboard, document image.
|
||||
let img_rect = xf.doc_rect(doc.bounds());
|
||||
// Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas
|
||||
// (whose edge blends into them) and without its shadow.
|
||||
let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output);
|
||||
let drop_shadow = drop_shadow && !beyond;
|
||||
// Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless
|
||||
// Preferences › Performance › Low Resolution Previews is off.
|
||||
let mut on_gpu = false;
|
||||
// A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader
|
||||
// has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform.
|
||||
let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect);
|
||||
if app.gpu.is_some()
|
||||
&& gpu_ok
|
||||
&& let Some((k, key, preview_size)) =
|
||||
ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx))
|
||||
{
|
||||
on_gpu = true;
|
||||
let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)];
|
||||
let params = crate::gpu_canvas::ViewParams {
|
||||
doc: key,
|
||||
doc_size: preview_size,
|
||||
zoom: view.zoom * k as f32 / ppp,
|
||||
// A size-changing preview grows around the old image center; keep the view's pan.
|
||||
center: [
|
||||
view.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0,
|
||||
view.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0,
|
||||
],
|
||||
rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 },
|
||||
shadow: {
|
||||
let t = crate::theme::Tokens::get(&ctx);
|
||||
!t.bevel && !t.pro && drop_shadow
|
||||
},
|
||||
pixel_grid: false,
|
||||
view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(),
|
||||
display: sync_display_lut(app, &doc, key, output),
|
||||
output: output.unwrap_or(0),
|
||||
hdr: hdr_preview(app, &doc),
|
||||
};
|
||||
crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);
|
||||
} else if gpu_ok && ensure_gpu(app, idx, visible_doc_rect(&xf)) {
|
||||
on_gpu = true;
|
||||
app.perf.gpu = true;
|
||||
// Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs).
|
||||
let params = crate::gpu_canvas::ViewParams {
|
||||
doc: doc.id.0,
|
||||
doc_size: [doc.size.width, doc.size.height],
|
||||
zoom: point_zoom,
|
||||
center: view.center,
|
||||
rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 },
|
||||
shadow: {
|
||||
let t = crate::theme::Tokens::get(&ctx);
|
||||
!t.bevel && !t.pro && drop_shadow
|
||||
},
|
||||
pixel_grid,
|
||||
view_key: egui::Id::new(("pc-canvas", ctx.viewport_id(), idx)).value(),
|
||||
display: sync_display_lut(app, &doc, doc.id.0, output),
|
||||
output: output.unwrap_or(0),
|
||||
hdr: hdr_preview(app, &doc),
|
||||
};
|
||||
crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params);
|
||||
} else {
|
||||
if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow {
|
||||
painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0));
|
||||
}
|
||||
let rotated = view.rotation.abs() > 0.05;
|
||||
let size = [doc.size.width as f32, doc.size.height as f32];
|
||||
match app.session.prefs().transparency_and_gamut.square() {
|
||||
Some(square) => {
|
||||
let checker_id = checker(app, &ctx);
|
||||
if rotated {
|
||||
let tiles = vec2(size[0], size[1]) / (2.0 * square);
|
||||
paint_mapped_image(&painter, &xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE);
|
||||
} else {
|
||||
let tiles = img_rect.size() / (2.0 * square);
|
||||
painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if rotated {
|
||||
paint_mapped_quad(&painter, &xf, size, Color32::WHITE);
|
||||
} else {
|
||||
painter.rect_filled(img_rect, 0.0, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx, output) {
|
||||
if rotated {
|
||||
paint_mapped_quad(&painter, &xf, size, Color32::WHITE);
|
||||
paint_mapped_image(&painter, &xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE);
|
||||
} else {
|
||||
painter.rect_filled(img_rect, 0.0, Color32::WHITE);
|
||||
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
|
||||
painter.image(tex, img_rect, uv, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx, output) {
|
||||
if rotated {
|
||||
paint_mapped_image(&painter, &xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE);
|
||||
// Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs).
|
||||
if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) {
|
||||
if view.rotation.abs() > 0.05 {
|
||||
paint_mapped_image(
|
||||
&painter,
|
||||
&xf,
|
||||
tex,
|
||||
Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)),
|
||||
[doc.size.width as f32, doc.size.height as f32],
|
||||
Color32::WHITE,
|
||||
);
|
||||
} else {
|
||||
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
|
||||
painter.image(tex, img_rect, uv, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs).
|
||||
if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) {
|
||||
if view.rotation.abs() > 0.05 {
|
||||
paint_mapped_image(
|
||||
&painter,
|
||||
&xf,
|
||||
tex,
|
||||
Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)),
|
||||
[doc.size.width as f32, doc.size.height as f32],
|
||||
Color32::WHITE,
|
||||
);
|
||||
} else {
|
||||
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
|
||||
painter.image(tex, img_rect, uv, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip);
|
||||
// Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs).
|
||||
if doc.has_artboards() {
|
||||
let t = crate::theme::Tokens::get(&ctx);
|
||||
let pasteboard = crate::prefs_ui::pasteboard_color(app);
|
||||
let dot_tex = dots(&ctx, &t);
|
||||
for r in crate::artboard_ui::pasteboard_rects(&xf, &doc) {
|
||||
let r = r.intersect(rect);
|
||||
if !r.is_positive() {
|
||||
continue;
|
||||
}
|
||||
match pasteboard {
|
||||
Some(c) => {
|
||||
painter.rect_filled(r, 0.0, c);
|
||||
crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip);
|
||||
// Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs).
|
||||
if doc.has_artboards() {
|
||||
let t = crate::theme::Tokens::get(&ctx);
|
||||
let pasteboard = crate::prefs_ui::pasteboard_color(app);
|
||||
let dot_tex = dots(&ctx, &t);
|
||||
for r in crate::artboard_ui::pasteboard_rects(&xf, &doc) {
|
||||
let r = r.intersect(rect);
|
||||
if !r.is_positive() {
|
||||
continue;
|
||||
}
|
||||
None => {
|
||||
painter.rect_filled(r, 0.0, t.canvas);
|
||||
if let Some(id) = dot_tex {
|
||||
// Same phase as the dots around the document.
|
||||
let uv = Rect::from_min_max(((r.min - rect.min) / 22.0).to_pos2(), ((r.max - rect.min) / 22.0).to_pos2());
|
||||
painter.image(id, r, uv, Color32::WHITE);
|
||||
match pasteboard {
|
||||
Some(c) => {
|
||||
painter.rect_filled(r, 0.0, c);
|
||||
}
|
||||
None => {
|
||||
painter.rect_filled(r, 0.0, t.canvas);
|
||||
if let Some(id) = dot_tex {
|
||||
// Same phase as the dots around the document.
|
||||
let uv = Rect::from_min_max(((r.min - rect.min) / 22.0).to_pos2(), ((r.max - rect.min) / 22.0).to_pos2());
|
||||
painter.image(id, r, uv, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if primary {
|
||||
crate::artboard_ui::draw_frames(app, &painter, &xf);
|
||||
}
|
||||
}
|
||||
|
||||
// Pixel grid at high zoom, over pixels with content only (the GPU path draws its own).
|
||||
if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) {
|
||||
crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf));
|
||||
}
|
||||
|
||||
// View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are
|
||||
// in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer.
|
||||
let layer_edges = painter.add(egui::Shape::Noop);
|
||||
|
||||
// Selection outline: true boundary, animated marching ants (cached per revision).
|
||||
if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) {
|
||||
// Trace at display resolution over the visible part only; key by the mask's tile identity
|
||||
// (not the document revision) so unrelated edits don't re-trace it. The step is in
|
||||
// device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px
|
||||
// selection still traces at 100% on a scaled display.
|
||||
let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32;
|
||||
let corners = [rect.min, pos2(rect.max.x, rect.min.y), rect.max, pos2(rect.min.x, rect.max.y)];
|
||||
let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])];
|
||||
let mut x0 = docs[0][0];
|
||||
let mut y0 = docs[0][1];
|
||||
let mut x1 = x0;
|
||||
let mut y1 = y0;
|
||||
for d in docs {
|
||||
x0 = x0.min(d[0]);
|
||||
y0 = y0.min(d[1]);
|
||||
x1 = x1.max(d[0]);
|
||||
y1 = y1.max(d[1]);
|
||||
}
|
||||
let q = 256 * step as i32; // quantise the region so small pans reuse the cache
|
||||
// The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document
|
||||
// to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there.
|
||||
let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32;
|
||||
let vis = photocraft_geom::Rect::new(
|
||||
px(x0.floor()).div_euclid(q) * q - q,
|
||||
px(y0.floor()).div_euclid(q) * q - q,
|
||||
(px(x1.ceil()).div_euclid(q) + 2) * q,
|
||||
(px(y1.ceil()).div_euclid(q) + 2) * q,
|
||||
);
|
||||
let key = crate::surface_fingerprint(sel)
|
||||
^ (step as u64) << 56
|
||||
^ doc.id.0.rotate_left(17)
|
||||
^ (vis.x0 as u64) << 8
|
||||
^ (vis.y0 as u64) << 24
|
||||
^ (vis.x1 as u64) << 36
|
||||
^ (vis.y1 as u64) << 48;
|
||||
let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key);
|
||||
if !fresh {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let b = app.cached_bounds(u64::MAX - doc.id.0, sel).intersect(&vis);
|
||||
// Filters can occupy every worker in Rayon's global pool. A parallel scan here would
|
||||
// block the UI thread waiting for those workers, preventing job cancellation (#1554).
|
||||
let segs = if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) };
|
||||
app.perf.span("outline", crate::gpu_canvas::now_ms() - t0);
|
||||
app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs)));
|
||||
}
|
||||
if let Some((_, _, segs)) = &app.outline_cache {
|
||||
let time = ui.input(|i| i.time);
|
||||
// A floating piece (and a selection being dragged) draws its ants where it is shown.
|
||||
let mut shown = xf;
|
||||
if let Some((dx, dy)) = selection_shown_offset(app) {
|
||||
shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32];
|
||||
if primary {
|
||||
crate::artboard_ui::draw_frames(app, &painter, &xf);
|
||||
}
|
||||
marching_ants_segments(&painter, &shown, segs, time);
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
// Pixel grid at high zoom, over pixels with content only (the GPU path draws its own).
|
||||
if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) {
|
||||
crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf));
|
||||
}
|
||||
|
||||
// View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are
|
||||
// in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer.
|
||||
let layer_edges = painter.add(egui::Shape::Noop);
|
||||
|
||||
// Selection outline: true boundary, animated marching ants (cached per revision).
|
||||
if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) {
|
||||
// Trace at display resolution over the visible part only; key by the mask's tile identity
|
||||
// (not the document revision) so unrelated edits don't re-trace it. The step is in
|
||||
// device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px
|
||||
// selection still traces at 100% on a scaled display.
|
||||
let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32;
|
||||
let corners = [rect.min, pos2(rect.max.x, rect.min.y), rect.max, pos2(rect.min.x, rect.max.y)];
|
||||
let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])];
|
||||
let mut x0 = docs[0][0];
|
||||
let mut y0 = docs[0][1];
|
||||
let mut x1 = x0;
|
||||
let mut y1 = y0;
|
||||
for d in docs {
|
||||
x0 = x0.min(d[0]);
|
||||
y0 = y0.min(d[1]);
|
||||
x1 = x1.max(d[0]);
|
||||
y1 = y1.max(d[1]);
|
||||
}
|
||||
let q = 256 * step as i32; // quantise the region so small pans reuse the cache
|
||||
// The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document
|
||||
// to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there.
|
||||
let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32;
|
||||
let vis = photocraft_geom::Rect::new(
|
||||
px(x0.floor()).div_euclid(q) * q - q,
|
||||
px(y0.floor()).div_euclid(q) * q - q,
|
||||
(px(x1.ceil()).div_euclid(q) + 2) * q,
|
||||
(px(y1.ceil()).div_euclid(q) + 2) * q,
|
||||
);
|
||||
let key = crate::surface_fingerprint(sel)
|
||||
^ (step as u64) << 56
|
||||
^ doc.id.0.rotate_left(17)
|
||||
^ (vis.x0 as u64) << 8
|
||||
^ (vis.y0 as u64) << 24
|
||||
^ (vis.x1 as u64) << 36
|
||||
^ (vis.y1 as u64) << 48;
|
||||
let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key);
|
||||
if !fresh {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let b = app.cached_bounds(u64::MAX - doc.id.0, sel).intersect(&vis);
|
||||
// Filters can occupy every worker in Rayon's global pool. A parallel scan here would
|
||||
// block the UI thread waiting for those workers, preventing job cancellation (#1554).
|
||||
let segs =
|
||||
if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) };
|
||||
app.perf.span("outline", crate::gpu_canvas::now_ms() - t0);
|
||||
app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs)));
|
||||
}
|
||||
if let Some((_, _, segs)) = &app.outline_cache {
|
||||
let time = ui.input(|i| i.time);
|
||||
// A floating piece (and a selection being dragged) draws its ants where it is shown.
|
||||
let mut shown = xf;
|
||||
if let Some((dx, dy)) = selection_shown_offset(app) {
|
||||
shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32];
|
||||
}
|
||||
marching_ants_segments(&painter, &shown, segs, time);
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
(img_rect, beyond, layer_edges)
|
||||
};
|
||||
let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &view, xf)) };
|
||||
let img_rect = xf.doc_rect(doc.bounds());
|
||||
|
||||
// Under an open dialog the canvas widget is inert, but the image still pans and zooms.
|
||||
let under_dialog = !app.ui.dialogs.is_empty();
|
||||
@@ -3092,6 +3103,20 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
if tool.is_type() && response.double_clicked() && !crate::type_transform::visible(app, crate::workspace_ui::sticky_mods(app, mods)) {
|
||||
crate::type_tool::select_word(app);
|
||||
}
|
||||
}
|
||||
if crop_camera && let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) {
|
||||
if now.center != center {
|
||||
view.center = now.center;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if now.rotation != rotation {
|
||||
view.rotation = now.rotation;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
let xf = if crop_camera { ViewXform { center: view.center, rotation: view.rotation, ..xf } } else { xf };
|
||||
let (img_rect, beyond, layer_edges) = painted.unwrap_or_else(|| paint_canvas(app, ui, &view, xf));
|
||||
if primary && !(hand_pan && response.dragged()) {
|
||||
if app.ui.extras.grid && app.ui.view.extras {
|
||||
crate::rulers::draw_grid(app, &painter, &xf, &doc);
|
||||
}
|
||||
@@ -3330,7 +3355,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
}
|
||||
crate::rotate_view::overlay(app, &ctx, &painter, &xf, &mut view, &response);
|
||||
if primary {
|
||||
// The camera the tools set this frame wins over the copy's.
|
||||
// Tool input can change the stored camera while navigation edits the local view.
|
||||
// Merge changed camera values so write-back preserves tool-driven pan and rotation.
|
||||
if let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) {
|
||||
if now.center != center {
|
||||
view.center = now.center;
|
||||
@@ -4075,6 +4101,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
|
||||
if crate::direct_select::pointer(app, ev, mods) {
|
||||
return;
|
||||
}
|
||||
// Add / Delete Anchor Point tools (#1044).
|
||||
if crate::anchor_tools::pointer(app, ev, mods) {
|
||||
return;
|
||||
}
|
||||
// Ruler, Count and Note tools.
|
||||
if crate::analysis_ui::pointer(app, ev, mods) {
|
||||
return;
|
||||
|
||||
+283
-109
@@ -1,12 +1,17 @@
|
||||
//! Lazy CJK and Thai fallback fonts for the UI.
|
||||
//! Lazy CJK and other-script fallback fonts for the UI.
|
||||
//!
|
||||
//! The bundled Inter / JetBrains Mono have no Japanese, Chinese or Korean glyphs, and the OS
|
||||
//! fonts that do are large (Hiragino ~10 MB, Apple SD Gothic Neo 28 MB, PingFang 78 MB, Noto
|
||||
//! Sans CJK ~20 MB). Instead of reading them at startup, an egui plugin scans each frame's text
|
||||
//! for CJK characters no registered font covers, and registers the next system font for that
|
||||
//! character's script (`ctx.add_font`, active from the next frame, which it requests). Fonts are
|
||||
//! appended at the lowest priority to every family, so Latin text keeps Inter. Thai has its own
|
||||
//! candidate list and attempt state, independent of the locale-dependent CJK order.
|
||||
//! appended at the lowest priority to every family, so Latin text keeps Inter.
|
||||
//!
|
||||
//! Other scripts the bundled fonts lack (Thai, Arabic, Hebrew, Devanagari and the other Indic
|
||||
//! scripts, ...: [`photocraft_text::scripts`]) work the same way, each with its own attempt state,
|
||||
//! independent of the CJK order: the first installed candidate file whose character map really
|
||||
//! has the missing character is registered, once per script. egui shapes each font run with
|
||||
//! HarfRust, so Thai marks and Arabic joining come from the font; it has no bidi reordering yet.
|
||||
//!
|
||||
//! Script order follows the UI locale ([`photocraft_text::cjk::script_order`]): Kana prefers a
|
||||
//! Japanese font, Hangul a Korean one, Bopomofo a Traditional Chinese one, and Han the
|
||||
@@ -22,10 +27,13 @@ use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily};
|
||||
use egui::{FontData, FontFamily, FontId, Shape};
|
||||
use photocraft_text::cjk::{self, CjkChar, CjkScript, FontFile};
|
||||
use photocraft_text::craft_fonts::{self, CraftFont};
|
||||
use photocraft_text::scripts::{self, Script};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Skip absurdly large files (a corrupt or non-font path must not eat memory).
|
||||
pub const MAX_FONT_BYTES: u64 = 128 << 20;
|
||||
/// At most this many candidate files are read for one script (bounded I/O on a miss).
|
||||
const MAX_SCRIPT_READS: usize = 6;
|
||||
/// Name prefix of the registered fallback fonts.
|
||||
pub const FONT_PREFIX: &str = "system-cjk";
|
||||
|
||||
@@ -35,8 +43,11 @@ pub struct Sources {
|
||||
pub locale: fn() -> Option<String>,
|
||||
pub files: fn(CjkScript) -> Vec<FontFile>,
|
||||
pub last_resort: fn() -> Vec<FontFile>,
|
||||
/// Thai fonts, loaded only when a visible Thai character is missing.
|
||||
pub thai: fn() -> Vec<FontFile>,
|
||||
/// Candidate files for a non-CJK script, most preferred first; read only when a visible
|
||||
/// character of that script is missing.
|
||||
pub scripts: fn(Script) -> Vec<PathBuf>,
|
||||
/// The face of a font file whose character map has the character (`None`: not this file).
|
||||
pub covers: fn(&[u8], char) -> Option<u32>,
|
||||
/// Embedded fonts tried before `files` for a script (craft-fonts' Japanese fonts).
|
||||
pub embedded: fn(CjkScript) -> Vec<&'static CraftFont>,
|
||||
}
|
||||
@@ -61,13 +72,21 @@ impl Sources {
|
||||
},
|
||||
files: cjk::font_files,
|
||||
last_resort: cjk::last_resort_files,
|
||||
thai: thai_font_files,
|
||||
scripts: scripts::system_candidates,
|
||||
covers: scripts::covering_face,
|
||||
embedded: craft_embedded,
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn system() -> Self {
|
||||
Self { locale: || None, files: |_| Vec::new(), last_resort: Vec::new, thai: Vec::new, embedded: craft_embedded }
|
||||
Self {
|
||||
locale: || None,
|
||||
files: |_| Vec::new(),
|
||||
last_resort: Vec::new,
|
||||
scripts: |_| Vec::new(),
|
||||
covers: scripts::covering_face,
|
||||
embedded: craft_embedded,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +98,8 @@ pub struct CjkFallback {
|
||||
order: Option<[CjkScript; 4]>,
|
||||
tried: Vec<CjkScript>,
|
||||
last_resort_tried: bool,
|
||||
thai_tried: bool,
|
||||
/// Non-CJK scripts whose candidates were tried (each at most once per install).
|
||||
scripts_tried: Vec<Script>,
|
||||
loaded: Vec<PathBuf>,
|
||||
/// Fonts registered so far: (name, path, face index).
|
||||
pub registered: Vec<(String, PathBuf, u32)>,
|
||||
@@ -93,7 +113,7 @@ impl CjkFallback {
|
||||
order: None,
|
||||
tried: Vec::new(),
|
||||
last_resort_tried: false,
|
||||
thai_tried: false,
|
||||
scripts_tried: Vec::new(),
|
||||
loaded: Vec::new(),
|
||||
registered: Vec::new(),
|
||||
}
|
||||
@@ -136,11 +156,39 @@ impl CjkFallback {
|
||||
None
|
||||
}
|
||||
|
||||
fn next_thai_font(&mut self) -> Option<(String, FontData)> {
|
||||
if std::mem::replace(&mut self.thai_tried, true) {
|
||||
/// Every non-CJK script has been tried.
|
||||
pub fn scripts_exhausted(&self) -> bool {
|
||||
self.scripts_tried.len() >= Script::ALL.len()
|
||||
}
|
||||
|
||||
/// The first candidate font for `c`'s script that really maps `c`; the script is tried once.
|
||||
pub fn next_script_font(&mut self, c: char) -> Option<(String, FontData)> {
|
||||
let script = scripts::classify(c)?;
|
||||
if self.scripts_tried.contains(&script) {
|
||||
return None;
|
||||
}
|
||||
self.load_first(&(self.sources.thai)())
|
||||
self.scripts_tried.push(script);
|
||||
let mut reads = 0;
|
||||
for path in (self.sources.scripts)(script) {
|
||||
if reads >= MAX_SCRIPT_READS {
|
||||
break;
|
||||
}
|
||||
if self.loaded.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
let Some(bytes) = read_font(&path) else { continue };
|
||||
reads += 1;
|
||||
let Some(index) = (self.sources.covers)(&bytes, c) else { continue };
|
||||
self.loaded.push(path.clone());
|
||||
let name = format!("{FONT_PREFIX}-{}", self.registered.len());
|
||||
log::info!("UI font fallback: registered {} (face {index}) for {script:?} as {name}", path.display());
|
||||
self.registered.push((name.clone(), path, index));
|
||||
let mut data = FontData::from_owned(bytes);
|
||||
data.index = index;
|
||||
return Some((name, data));
|
||||
}
|
||||
log::info!("UI font fallback: no installed font covers {script:?}");
|
||||
None
|
||||
}
|
||||
|
||||
/// The first embedded (craft-fonts) font for `s`, registered from its static bytes.
|
||||
@@ -162,11 +210,7 @@ impl CjkFallback {
|
||||
if self.loaded.contains(&f.path) {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::metadata(&f.path) else { continue };
|
||||
if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_FONT_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(&f.path) else { continue };
|
||||
let Some(bytes) = read_font(&f.path) else { continue };
|
||||
let index = cjk::face_index_for_family(&bytes, f.family);
|
||||
self.loaded.push(f.path.clone());
|
||||
let name = format!("{FONT_PREFIX}-{}", self.registered.len());
|
||||
@@ -180,18 +224,24 @@ impl CjkFallback {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_thai(c: char) -> bool {
|
||||
matches!(c, '\u{0e00}'..='\u{0e7f}')
|
||||
/// A font file's bytes, or `None` for missing, empty, oversized or unreadable files.
|
||||
fn read_font(path: &std::path::Path) -> Option<Vec<u8>> {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_FONT_BYTES {
|
||||
return None;
|
||||
}
|
||||
std::fs::read(path).ok()
|
||||
}
|
||||
|
||||
/// First supported missing character for which a fallback has not yet been exhausted.
|
||||
fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape], fallback: &CjkFallback) -> Option<char> {
|
||||
fn collect(shape: &Shape, out: &mut Vec<char>, cjk_pending: bool, thai_pending: bool) {
|
||||
fn collect(shape: &Shape, out: &mut Vec<char>, fallback: &CjkFallback, cjk_pending: bool) {
|
||||
let wanted = |c: char| (cjk_pending && cjk::classify(c).is_some()) || scripts::classify(c).is_some_and(|s| !fallback.scripts_tried.contains(&s));
|
||||
match shape {
|
||||
Shape::Text(t) => {
|
||||
let text = &t.galley.job.text;
|
||||
if !text.is_ascii() {
|
||||
for c in text.chars().filter(|c| (cjk_pending && cjk::classify(*c).is_some()) || (thai_pending && is_thai(*c))) {
|
||||
for c in text.chars().filter(|c| wanted(*c)) {
|
||||
if out.len() >= 256 {
|
||||
return;
|
||||
}
|
||||
@@ -201,13 +251,13 @@ fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape], fall
|
||||
}
|
||||
}
|
||||
}
|
||||
Shape::Vec(v) => v.iter().for_each(|s| collect(s, out, cjk_pending, thai_pending)),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| collect(s, out, fallback, cjk_pending)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut chars = Vec::new();
|
||||
for s in shapes {
|
||||
collect(&s.shape, &mut chars, !fallback.exhausted(), !fallback.thai_tried);
|
||||
collect(&s.shape, &mut chars, fallback, !fallback.exhausted());
|
||||
}
|
||||
if chars.is_empty() {
|
||||
return None;
|
||||
@@ -287,22 +337,25 @@ impl egui::Plugin for CjkFontPlugin {
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
if self.0.exhausted() && self.0.thai_tried {
|
||||
if self.0.exhausted() && self.0.scripts_exhausted() {
|
||||
return;
|
||||
}
|
||||
let Some(c) = missing_char(ctx, &output.shapes, &self.0) else { return };
|
||||
let font = if is_thai(c) { self.0.next_thai_font() } else { cjk::classify(c).and_then(|kind| self.0.next_font(kind)) };
|
||||
let font = match cjk::classify(c) {
|
||||
Some(kind) => self.0.next_font(kind),
|
||||
None => self.0.next_script_font(c),
|
||||
};
|
||||
if let Some((name, data)) = font {
|
||||
add_to_all_families(ctx, name, data);
|
||||
ctx.request_repaint();
|
||||
} else if !self.0.exhausted() || !self.0.thai_tried {
|
||||
} else if !self.0.exhausted() || !self.0.scripts_exhausted() {
|
||||
// Nothing readable for this script; try the next one on the next frame.
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the lazy CJK and Thai fallback (system fonts; nothing on the web).
|
||||
/// Installs the lazy CJK and other-script fallback (system fonts; nothing on the web).
|
||||
pub fn install(ctx: &egui::Context) {
|
||||
install_with(ctx, Sources::system());
|
||||
}
|
||||
@@ -323,38 +376,6 @@ pub fn install_with(ctx: &egui::Context, sources: Sources) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Common native Thai fonts. Keep discovery lazy, as with the CJK candidates: no full
|
||||
/// system font scan on the UI thread and no extra font files embedded in the web build.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn thai_font_files() -> Vec<FontFile> {
|
||||
let f = |path: &str, family| FontFile { path: path.into(), family };
|
||||
if cfg!(target_os = "macos") {
|
||||
vec![f("/System/Library/Fonts/Supplemental/Thonburi.ttc", "Thonburi"), f("/System/Library/Fonts/Supplemental/SukhumvitSet.ttc", "Sukhumvit Set")]
|
||||
} else if cfg!(target_os = "windows") {
|
||||
let dir = std::env::var_os("WINDIR").map_or_else(|| PathBuf::from("C:\\Windows"), PathBuf::from).join("Fonts");
|
||||
[("Leelawui.ttf", "Leelawadee UI"), ("leelawad.ttf", "Leelawadee"), ("tahoma.ttf", "Tahoma")]
|
||||
.into_iter()
|
||||
.map(|(file, family)| FontFile { path: dir.join(file), family })
|
||||
.collect()
|
||||
} else {
|
||||
thai_unix_font_files()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn thai_unix_font_files() -> Vec<FontFile> {
|
||||
// Fedora's static and variable packages, Debian/Ubuntu, then Arch/Noto installations.
|
||||
// Flatpak exposes the host's /usr/share/fonts as /run/host/fonts.
|
||||
["google-noto/NotoSansThai-Regular.ttf", "google-noto-vf/NotoSansThai[wght].ttf", "truetype/noto/NotoSansThai-Regular.ttf", "noto/NotoSansThai-Regular.ttf"]
|
||||
.into_iter()
|
||||
.flat_map(|file| {
|
||||
["/usr/share/fonts", "/run/host/fonts", "/usr/local/share/fonts"]
|
||||
.into_iter()
|
||||
.map(move |root| FontFile { path: std::path::Path::new(root).join(file), family: "Noto Sans Thai" })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod tests {
|
||||
@@ -417,6 +438,9 @@ mod tests {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("font.ttf"), include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap();
|
||||
std::fs::write(dir.join("empty.ttf"), b"").unwrap();
|
||||
std::fs::write(dir.join("thai.ttf"), synthetic_font(&[(0x0E01, 0x0E5B)])).unwrap();
|
||||
std::fs::write(dir.join("arabic.ttf"), synthetic_font(&[(0x0600, 0x06FF)])).unwrap();
|
||||
std::fs::write(dir.join("devanagari.ttf"), synthetic_font(&[(0x0900, 0x097F)])).unwrap();
|
||||
dir
|
||||
})
|
||||
.clone()
|
||||
@@ -436,7 +460,8 @@ mod tests {
|
||||
_ => vec![],
|
||||
},
|
||||
last_resort: || vec![fake("font.ttf")],
|
||||
thai: Vec::new,
|
||||
scripts: |_| Vec::new(),
|
||||
covers: scripts::covering_face,
|
||||
embedded: no_embedded,
|
||||
}
|
||||
}
|
||||
@@ -467,7 +492,14 @@ mod tests {
|
||||
("zh-Hant-TW", CjkScript::TraditionalChinese),
|
||||
("ko_KR", CjkScript::Korean),
|
||||
] {
|
||||
let mut fb = CjkFallback::new(Sources { locale: || None, files: |_| vec![], last_resort: Vec::new, thai: Vec::new, embedded: no_embedded });
|
||||
let mut fb = CjkFallback::new(Sources {
|
||||
locale: || None,
|
||||
files: |_| vec![],
|
||||
last_resort: Vec::new,
|
||||
scripts: |_| Vec::new(),
|
||||
covers: scripts::covering_face,
|
||||
embedded: no_embedded,
|
||||
});
|
||||
fb.order = Some(cjk::script_order(Some(loc)));
|
||||
assert!(fb.next_font(CjkChar::Han).is_none());
|
||||
assert_eq!(fb.tried[0], first, "{loc}");
|
||||
@@ -485,66 +517,198 @@ mod tests {
|
||||
ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(12.0), &text.replace(' ', "")))
|
||||
}
|
||||
|
||||
/// A minimal TrueType font mapping the `ranges` (inclusive) to box glyphs, so tests have a
|
||||
/// font for a script without committing font files.
|
||||
fn synthetic_font(ranges: &[(u32, u32)]) -> Vec<u8> {
|
||||
let be16 = |v: &mut Vec<u8>, x: i32| v.extend((x as u16).to_be_bytes());
|
||||
let be32 = |v: &mut Vec<u8>, x: u32| v.extend(x.to_be_bytes());
|
||||
let chars: u32 = ranges.iter().map(|(a, b)| b - a + 1).sum();
|
||||
let glyphs = chars as i32 + 1;
|
||||
// One 500x700 box (contour of four on-curve points); glyph 0 (.notdef) is empty.
|
||||
let mut boxed = Vec::new();
|
||||
for x in [1, 50, 0, 550, 700, 3, 0] {
|
||||
be16(&mut boxed, x);
|
||||
}
|
||||
boxed.extend([1u8; 4]);
|
||||
for x in [50, 0, 500, 0, 0, 700, 0, -700] {
|
||||
be16(&mut boxed, x);
|
||||
}
|
||||
boxed.extend([0, 0]);
|
||||
let glyf: Vec<u8> = boxed.repeat(chars as usize);
|
||||
let mut loca = Vec::new();
|
||||
be32(&mut loca, 0);
|
||||
for i in 0..chars {
|
||||
be32(&mut loca, i * boxed.len() as u32);
|
||||
}
|
||||
be32(&mut loca, chars * boxed.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
for x in [0x0001_0000, 0x0001_0000, 0, 0x5F0F_3CF5] {
|
||||
be32(&mut head, x);
|
||||
}
|
||||
for x in [0x000B, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, -200, 600, 800, 0, 8, 2, 1, 0] {
|
||||
be16(&mut head, x);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
for x in [800, -200, 0, 600, 0, 0, 550, 1, 0, 0, 0, 0, 0, 0, 0, glyphs] {
|
||||
be16(&mut hhea, x);
|
||||
}
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
for x in [glyphs, 4, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, x);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..glyphs {
|
||||
be16(&mut hmtx, 600);
|
||||
be16(&mut hmtx, 50);
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for x in [0, 1, 3, 10] {
|
||||
be16(&mut cmap, x);
|
||||
}
|
||||
be32(&mut cmap, 12);
|
||||
be16(&mut cmap, 12);
|
||||
be16(&mut cmap, 0);
|
||||
be32(&mut cmap, 16 + 12 * ranges.len() as u32);
|
||||
be32(&mut cmap, 0);
|
||||
be32(&mut cmap, ranges.len() as u32);
|
||||
let mut gid = 1;
|
||||
for (a, b) in ranges {
|
||||
for x in [*a, *b, gid] {
|
||||
be32(&mut cmap, x);
|
||||
}
|
||||
gid += b - a + 1;
|
||||
}
|
||||
let tables: [(&[u8; 4], Vec<u8>); 7] =
|
||||
[(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
let mut font = Vec::new();
|
||||
be32(&mut font, 0x0001_0000);
|
||||
for x in [7, 64, 2, 48] {
|
||||
be16(&mut font, x);
|
||||
}
|
||||
let mut offset = 12 + 16 * tables.len() as u32;
|
||||
for (tag, data) in &tables {
|
||||
font.extend(*tag);
|
||||
be32(&mut font, 0);
|
||||
be32(&mut font, offset);
|
||||
be32(&mut font, data.len() as u32);
|
||||
offset += (data.len() as u32).next_multiple_of(4);
|
||||
}
|
||||
for (_, data) in &tables {
|
||||
font.extend(data);
|
||||
font.resize(font.len().next_multiple_of(4), 0);
|
||||
}
|
||||
font
|
||||
}
|
||||
|
||||
/// Thai, Arabic and Devanagari each have a synthetic font; Thai's list starts with unreadable
|
||||
/// files and Inter, which doesn't map Thai. No other script has a font.
|
||||
fn script_sources() -> Sources {
|
||||
Sources {
|
||||
locale: || Some("en".into()),
|
||||
files: |_| vec![],
|
||||
last_resort: Vec::new,
|
||||
scripts: |s| {
|
||||
let f = |name: &str| fake_dir().join(name);
|
||||
match s {
|
||||
Script::Thai => vec![f("missing.ttf"), f("empty.ttf"), f("font.ttf"), f("thai.ttf")],
|
||||
Script::Arabic => vec![f("arabic.ttf")],
|
||||
Script::Devanagari => vec![f("devanagari.ttf")],
|
||||
_ => vec![],
|
||||
}
|
||||
},
|
||||
covers: scripts::covering_face,
|
||||
embedded: no_embedded,
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback_files(ctx: &egui::Context) -> Vec<String> {
|
||||
ctx.with_plugin::<CjkFontPlugin, _>(|p| p.0.registered.iter().map(|(_, path, _)| path.file_name().unwrap().to_string_lossy().into_owned()).collect())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thai_candidates_include_fedora_static_variable_and_flatpak_fonts() {
|
||||
let files = thai_unix_font_files();
|
||||
for root in ["/usr/share/fonts", "/run/host/fonts"] {
|
||||
for file in ["google-noto/NotoSansThai-Regular.ttf", "google-noto-vf/NotoSansThai[wght].ttf"] {
|
||||
assert!(files.iter().any(|f| f.path == std::path::Path::new(root).join(file) && f.family == "Noto Sans Thai"));
|
||||
fn layer_names_in_other_scripts_load_a_covering_font_once() {
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 {
|
||||
crate::theme::install_fonts_with(&ctx, script_sources());
|
||||
assert!(render(&ctx, "Layer 1 – café"));
|
||||
ctx.with_plugin::<CjkFontPlugin, _>(|p| assert!(p.0.scripts_tried.is_empty(), "Latin text reads no font")).unwrap();
|
||||
assert!(fallback_files(&ctx).is_empty());
|
||||
// A Thai type layer's name (#2275), Arabic (#1693) and Devanagari: no missing glyphs.
|
||||
for text in ["สวัสดี", "ภาพถ่าย/วันหยุดพักผ่อน", "مرحبا بالعالم", "नमस्ते दुनिया"]
|
||||
{
|
||||
assert!(render(&ctx, text), "tofu in {text}");
|
||||
}
|
||||
assert_eq!(fallback_files(&ctx), ["thai.ttf", "arabic.ttf", "devanagari.ttf"], "the first file that maps the character, never Inter");
|
||||
// Hebrew has no font here: tried once, then left alone (no reload or repaint loop).
|
||||
assert!(!render(&ctx, "שלום"));
|
||||
assert!(!render(&ctx, "שלום"));
|
||||
ctx.with_plugin::<CjkFontPlugin, _>(|p| {
|
||||
assert!(p.0.scripts_tried.contains(&Script::Hebrew));
|
||||
assert_eq!(p.0.registered.len(), 3);
|
||||
})
|
||||
.unwrap();
|
||||
let fonts = ctx.fonts(|f| f.definitions().clone());
|
||||
assert_eq!(fonts.families[&FontFamily::Proportional].first().map(String::as_str), Some("Inter"));
|
||||
for stack in fonts.families.values() {
|
||||
assert_eq!(stack.iter().filter(|n| n.starts_with(FONT_PREFIX)).count(), 3);
|
||||
assert_eq!(stack.last().map(String::as_str), Some("system-cjk-2"), "appended last so Latin keeps Inter");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thai_loading_is_lazy_once_per_install_and_independent_of_cjk() {
|
||||
let sources = Sources {
|
||||
locale: || Some("en".into()),
|
||||
files: |_| vec![],
|
||||
last_resort: Vec::new,
|
||||
thai: || vec![fake("missing.ttf"), fake("empty.ttf"), fake("font.ttf")],
|
||||
embedded: no_embedded,
|
||||
};
|
||||
fn a_missing_cjk_font_does_not_block_other_scripts_and_vice_versa() {
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 {
|
||||
crate::theme::install_fonts_with(&ctx, sources.clone());
|
||||
assert!(render(&ctx, "Recent file.png"));
|
||||
ctx.with_plugin::<CjkFontPlugin, _>(|p| {
|
||||
assert!(!p.0.thai_tried, "Latin-only frames do not request Thai fonts");
|
||||
assert!(p.0.registered.is_empty());
|
||||
});
|
||||
// The stand-in does not draw Thai. An unavailable CJK glyph preceding Thai must
|
||||
// not prevent trying the Thai font, nor cause registration/repaint loops.
|
||||
assert!(!render(&ctx, "日本語/ภาพถ่าย/วันหยุดพักผ่อน.png"));
|
||||
ctx.with_plugin::<CjkFontPlugin, _>(|p| {
|
||||
assert!(p.0.exhausted());
|
||||
assert!(p.0.thai_tried);
|
||||
assert_eq!(p.0.registered.len(), 1);
|
||||
});
|
||||
let fonts = ctx.fonts(|f| f.definitions().clone());
|
||||
assert_eq!(fonts.families[&FontFamily::Proportional].first().map(String::as_str), Some("Inter"));
|
||||
for stack in fonts.families.values() {
|
||||
assert_eq!(stack.iter().filter(|n| n.starts_with(FONT_PREFIX)).count(), 1);
|
||||
assert_eq!(stack.last().map(String::as_str), Some("system-cjk-0"));
|
||||
}
|
||||
}
|
||||
// Exhausting Thai first must likewise leave CJK available.
|
||||
crate::theme::install_fonts_with(&ctx, script_sources());
|
||||
assert!(!render(&ctx, "日本語/ภาพถ่าย/วันหยุดพักผ่อน.png"));
|
||||
assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png"));
|
||||
ctx.with_plugin::<CjkFontPlugin, _>(|p| assert!(p.0.exhausted())).unwrap();
|
||||
assert_eq!(fallback_files(&ctx), ["thai.ttf"]);
|
||||
// A script with no font leaves CJK available.
|
||||
let mut fallback = CjkFallback::new(fake_sources(|| Some("ko".into())));
|
||||
assert!(fallback.next_thai_font().is_none());
|
||||
assert!(fallback.next_script_font('ส').is_none());
|
||||
assert!(fallback.next_script_font('ส').is_none());
|
||||
assert!(fallback.next_script_font('A').is_none(), "Latin is never a fallback script");
|
||||
assert_eq!(fallback.scripts_tried, [Script::Thai]);
|
||||
assert!(fallback.next_font(CjkChar::Hangul).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_fonts_cover_thai_recent_file_names() {
|
||||
// Like the CJK system-font test, run when this machine has the script's fonts.
|
||||
// The deterministic lazy-loading test above does not require installed fonts.
|
||||
let files = thai_font_files();
|
||||
if !files.iter().any(|f| f.path.is_file()) {
|
||||
eprintln!("skipping: no Thai system font");
|
||||
return;
|
||||
}
|
||||
fn script_candidates_are_read_a_bounded_number_of_times() {
|
||||
static CHECKED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let mut fallback = CjkFallback::new(Sources {
|
||||
scripts: |_| (0..20).map(|i| fake_dir().join(if i % 2 == 0 { "font.ttf" } else { "thai.ttf" })).collect(),
|
||||
covers: |_, _| {
|
||||
CHECKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
None
|
||||
},
|
||||
..script_sources()
|
||||
});
|
||||
assert!(fallback.next_script_font('ش').is_none());
|
||||
assert!(fallback.next_script_font('ش').is_none());
|
||||
assert_eq!(CHECKED.load(std::sync::atomic::Ordering::Relaxed), MAX_SCRIPT_READS, "one bounded pass per script");
|
||||
assert!(fallback.registered.is_empty());
|
||||
assert!(!fallback.scripts_exhausted());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_fonts_cover_other_script_samples() {
|
||||
// Like the CJK system-font test, run per script when this machine has a font for it.
|
||||
// The deterministic tests above do not need installed fonts.
|
||||
let samples = [("ภาพถ่าย/วันหยุดพักผ่อน", 'ภ'), ("مرحبا", 'م'), ("שלום", 'ש'), ("नमस्ते", 'न')];
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png"), "Thai filename and combining marks still have missing glyphs");
|
||||
for (text, c) in samples {
|
||||
let Some(script) = scripts::classify(c) else { continue };
|
||||
if !scripts::system_candidates(script).iter().any(|p| read_font(p).and_then(|b| scripts::covering_face(&b, c)).is_some()) {
|
||||
eprintln!("skipping {text}: no {script:?} system font");
|
||||
continue;
|
||||
}
|
||||
assert!(render(&ctx, text), "{text} still has missing glyphs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -587,7 +751,7 @@ mod tests {
|
||||
|
||||
/// No system fonts at all: craft-fonts alone draws Japanese.
|
||||
fn craft_only(locale: fn() -> Option<String>) -> Sources {
|
||||
Sources { locale, files: |_| vec![], last_resort: Vec::new, thai: Vec::new, embedded: craft_embedded }
|
||||
Sources { locale, files: |_| vec![], last_resort: Vec::new, scripts: |_| Vec::new(), covers: scripts::covering_face, embedded: craft_embedded }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -617,7 +781,17 @@ mod tests {
|
||||
// The pre-craft-fonts behaviour: no embedded fonts, no system fonts. Latin renders,
|
||||
// Japanese is tried (and stays missing) without panicking, and the loader exhausts.
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts_with(&ctx, Sources { locale: || None, files: |_| vec![], last_resort: Vec::new, thai: Vec::new, embedded: no_embedded });
|
||||
crate::theme::install_fonts_with(
|
||||
&ctx,
|
||||
Sources {
|
||||
locale: || None,
|
||||
files: |_| vec![],
|
||||
last_resort: Vec::new,
|
||||
scripts: |_| Vec::new(),
|
||||
covers: scripts::covering_face,
|
||||
embedded: no_embedded,
|
||||
},
|
||||
);
|
||||
assert!(render(&ctx, "Layer 1 – café"));
|
||||
assert!(!render(&ctx, "日本語の文字"));
|
||||
let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count());
|
||||
|
||||
@@ -132,7 +132,8 @@ pub struct LiveResize {
|
||||
/// press and grows or shrinks symmetrically there, so the handle stays under the pointer, while on
|
||||
/// the image the opposite edge stays put (the centre with ⌥), as in a plain resize. Everything is
|
||||
/// computed from the press, so the view following the frame can't feed back into the drag.
|
||||
pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) {
|
||||
/// Returns the proposed frame and the camera's document-space offset without changing the app.
|
||||
pub(crate) fn resized_frame(g: LiveResize) -> Option<([f64; 4], [f64; 2])> {
|
||||
let LiveResize { rect, deg, hx, hy, start, q, ratio, alt } = g;
|
||||
let c0 = crate::crop_ui::center(rect);
|
||||
let (w0, h0) = (rect[2] - rect[0], rect[3] - rect[1]);
|
||||
@@ -147,9 +148,12 @@ pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) {
|
||||
let s = crate::crop_ui::turn(shift, [0.0, 0.0], deg);
|
||||
let c1 = [c0[0] + s[0], c0[1] + s[1]];
|
||||
let f = [c1[0] - w1 / 2.0, c1[1] - h1 / 2.0, c1[0] + w1 / 2.0, c1[1] + h1 / 2.0];
|
||||
if !f.iter().all(|v| v.is_finite()) {
|
||||
return;
|
||||
}
|
||||
f.iter().all(|v| v.is_finite()).then_some((f, s))
|
||||
}
|
||||
|
||||
/// Move the camera with the resized frame to keep the crop box's centre stationary on screen.
|
||||
pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) {
|
||||
let Some((f, s)) = resized_frame(g) else { return };
|
||||
app.ui.crop_rect = Some(f);
|
||||
// The view follows the centre, so the box stays where it was on screen.
|
||||
if let Some(v) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) {
|
||||
@@ -216,6 +220,14 @@ pub fn to_press(app: &PhotocraftApp, press: Option<PressView>, p: [f64; 2]) -> [
|
||||
}
|
||||
}
|
||||
|
||||
/// A press-view point mapped back into the current camera after snapping the crop handle.
|
||||
pub(crate) fn from_press(app: &PhotocraftApp, press: PressView, p: [f64; 2]) -> [f64; 2] {
|
||||
match press_view(app) {
|
||||
Some(now) => remap(p, press, now, app.ui.view.flip_horizontal),
|
||||
None => p,
|
||||
}
|
||||
}
|
||||
|
||||
/// The control channel's `ui.pointer` gives document points as the view showed them at the press
|
||||
/// (it can't know how the view turns and pans with the image): during a default-mode drag, the
|
||||
/// point the canvas would report for the same screen position now.
|
||||
@@ -337,6 +349,45 @@ mod tests {
|
||||
app.crop.default_frame = false;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_resize_snaps_the_handle_without_feedback_from_the_camera() {
|
||||
for (hx, hy) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] {
|
||||
for alt in [false, true] {
|
||||
for (zoom, ppp, flip, ratio) in [(1.0, 1.0, false, false), (0.5, 1.0, false, true), (3.0, 2.0, false, false), (3.0, 2.0, true, true)] {
|
||||
let mut app = app();
|
||||
app.ppp = ppp;
|
||||
app.ui.views[0].zoom = zoom;
|
||||
app.ui.view.flip_horizontal = flip;
|
||||
if ratio {
|
||||
app.ui.tool_options.crop_ratio = "original".into();
|
||||
}
|
||||
app.ui.extras.snap = true;
|
||||
crate::crop_ui::ensure_frame(&mut app);
|
||||
let box0 = screen_box(&app);
|
||||
let c = mid_of(box0);
|
||||
let from = xf(&app).to_screen(100.0 + hx as f32 * 100.0, 50.0 + hy as f32 * 50.0);
|
||||
let direction = (from - c).normalized();
|
||||
let mods = if alt { Modifiers::ALT } else { NONE };
|
||||
let d = xf(&app).to_doc(from);
|
||||
tool_event(&mut app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods);
|
||||
// Leave the snap radius, then return just inside it. A still pointer must
|
||||
// settle on the canvas edge instead of alternating on opposite sides of it.
|
||||
for offset in [20.0, -2.0, -2.0, -2.0, -2.0, -2.0] {
|
||||
let p = from + direction * offset;
|
||||
let d = xf(&app).to_doc(p);
|
||||
tool_event(&mut app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods);
|
||||
if offset == -2.0 {
|
||||
assert!(close(screen_box(&app), box0), "handle ({hx}, {hy}), Alt {alt}: {:?}", app.ui.crop_rect);
|
||||
}
|
||||
}
|
||||
let d = xf(&app).to_doc(from + direction * -2.0);
|
||||
tool_event(&mut app, ToolEvent::Up { x: d[0], y: d[1] }, mods);
|
||||
assert!(close(screen_box(&app), box0), "release: {:?}", app.ui.crop_rect);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_outside_turns_the_image_and_the_box_stays_upright() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -156,8 +156,8 @@ pub fn ratio(o: &ToolOptions, doc_dpi: f64) -> Option<f64> {
|
||||
|
||||
/// Editable W and H shown for a custom aspect ratio. An existing valid ratio is authoritative;
|
||||
/// when either side is zero, use the in-progress values retained in ToolOptions.
|
||||
pub fn custom_ratio_fields(o: &ToolOptions) -> (f32, f32) {
|
||||
crate::chrome_ui::crop_ratio(&o.crop_ratio, 0.0, 0.0)
|
||||
pub fn custom_ratio_fields(o: &ToolOptions, doc_size: (f64, f64)) -> (f32, f32) {
|
||||
crate::chrome_ui::crop_ratio(&o.crop_ratio, doc_size.0, doc_size.1)
|
||||
.filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0 && *w <= 99_999.0 && *h <= 99_999.0)
|
||||
.map(|(w, h)| (w as f32, h as f32))
|
||||
.unwrap_or((o.crop_custom_ratio_width, o.crop_custom_ratio_height))
|
||||
@@ -247,6 +247,7 @@ pub fn chosen(app: &mut PhotocraftApp) {
|
||||
o.crop_resolution = (*r).into();
|
||||
o.crop_resolution_unit = PX_PER_IN.into();
|
||||
}
|
||||
crate::crop_ui::apply_ratio(app);
|
||||
}
|
||||
|
||||
/// I with the Crop tool (no text field focused, which the caller checks): Front Image. Returns
|
||||
@@ -257,6 +258,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
}
|
||||
if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, egui::Key::I)) {
|
||||
front_image(app);
|
||||
crate::crop_ui::apply_ratio(app);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
@@ -343,12 +345,12 @@ mod tests {
|
||||
set_custom_ratio_fields(&mut options, 4.0, 0.0);
|
||||
|
||||
assert_eq!(options.crop_ratio, "", "an incomplete ratio stays unconstrained");
|
||||
assert_eq!(custom_ratio_fields(&options), (4.0, 0.0), "first entry survives the next frame");
|
||||
assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (4.0, 0.0), "first entry survives the next frame");
|
||||
|
||||
let (width, _) = custom_ratio_fields(&options);
|
||||
let (width, _) = custom_ratio_fields(&options, (0.0, 0.0));
|
||||
set_custom_ratio_fields(&mut options, width, 3.0);
|
||||
assert_eq!(options.crop_ratio, "4:3");
|
||||
assert_eq!(custom_ratio_fields(&options), (4.0, 3.0));
|
||||
assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (4.0, 3.0));
|
||||
let (width, height) = crate::chrome_ui::crop_ratio(&options.crop_ratio, 0.0, 0.0).unwrap_or_default();
|
||||
assert_eq!(width / height, 4.0 / 3.0);
|
||||
}
|
||||
@@ -357,11 +359,11 @@ mod tests {
|
||||
fn selecting_free_ratio_clears_previous_custom_dimensions() {
|
||||
let mut options = ToolOptions { crop_ratio: "16:9".into(), ..ToolOptions::default() };
|
||||
select_custom_ratio(&mut options);
|
||||
assert_eq!(custom_ratio_fields(&options), (16.0, 9.0));
|
||||
assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (16.0, 9.0));
|
||||
|
||||
options.crop_ratio.clear();
|
||||
select_custom_ratio(&mut options);
|
||||
assert_eq!(custom_ratio_fields(&options), (0.0, 0.0));
|
||||
assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (0.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -469,6 +471,19 @@ mod tests {
|
||||
|
||||
/// Committing a W x H x Resolution crop resamples the frame's area to exactly W x H px and sets
|
||||
/// the resolution, in one undo step, at 8 and 16 bits.
|
||||
#[test]
|
||||
fn choosing_a_size_with_the_canvas_ratio_commits_without_a_resize() {
|
||||
let mut app = app(SampleType::U8);
|
||||
crate::crop_ui::ensure_frame(&mut app);
|
||||
app.ui.tool_options = whr("800 px", "600 px", "92", PX_PER_IN);
|
||||
chosen(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 400.0, 300.0]));
|
||||
assert!(!app.crop.default_frame, "an output size is a pending crop even when the frame fits");
|
||||
crate::canvas::commit_crop(&mut app);
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
assert_eq!((doc.size, doc.resolution_dpi), (Size::new(800, 600), 92.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_resamples_to_the_target_size_and_resolution() {
|
||||
for depth in [SampleType::U8, SampleType::U16] {
|
||||
|
||||
@@ -200,7 +200,7 @@ fn size_ok(r: [f64; 4]) -> bool {
|
||||
}
|
||||
|
||||
/// The options-bar ratio preset as width / height (W : H in W x H x Resolution mode).
|
||||
fn preset_ratio(app: &PhotocraftApp) -> Option<f64> {
|
||||
pub(crate) fn preset_ratio(app: &PhotocraftApp) -> Option<f64> {
|
||||
if app.ui.tool_options.crop_ratio == crate::crop_size::WHR {
|
||||
let dpi = app.session.active().map_or(72.0, |s| f64::from(s.doc.resolution_dpi));
|
||||
return crate::crop_size::ratio(&app.ui.tool_options, dpi);
|
||||
@@ -209,6 +209,43 @@ fn preset_ratio(app: &PhotocraftApp) -> Option<f64> {
|
||||
crate::chrome_ui::crop_ratio(&app.ui.tool_options.crop_ratio, size.0, size.1).map(|(w, h)| w / h).filter(|k| k.is_finite() && *k > 0.0)
|
||||
}
|
||||
|
||||
/// Largest centred rectangle of `ratio` contained in the current frame; never adds area.
|
||||
fn fitted_ratio(r: [f64; 4], ratio: f64) -> Option<[f64; 4]> {
|
||||
let (w, h) = (r[2] - r[0], r[3] - r[1]);
|
||||
if !r.iter().all(|v| v.is_finite()) || !w.is_finite() || !h.is_finite() || w <= 0.0 || h <= 0.0 || !ratio.is_finite() || ratio <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
if ((w / h) / ratio - 1.0).abs() < 1e-12 {
|
||||
return Some(r);
|
||||
}
|
||||
let c = [r[0] + w / 2.0, r[1] + h / 2.0];
|
||||
let (w, h) = if w / h > ratio { (h * ratio, h) } else { (w, w / ratio) };
|
||||
let fitted = [c[0] - w / 2.0, c[1] - h / 2.0, c[0] + w / 2.0, c[1] + h / 2.0];
|
||||
(fitted.iter().all(|v| v.is_finite()) && fitted[2] > fitted[0] && fitted[3] > fitted[1]).then_some(fitted)
|
||||
}
|
||||
|
||||
/// Apply committed options to the preview now, before a resize or confirmation is needed.
|
||||
pub(crate) fn apply_ratio(app: &mut PhotocraftApp) {
|
||||
if app.ui.tool != Tool::Crop || app.crop.drag.is_some() {
|
||||
return;
|
||||
}
|
||||
frame(app);
|
||||
fit_frame(app);
|
||||
crate::crop_mode::sync_frame(app);
|
||||
}
|
||||
|
||||
fn fit_frame(app: &mut PhotocraftApp) {
|
||||
let dpi = app.session.active().map_or(72.0, |s| f64::from(s.doc.resolution_dpi));
|
||||
if let Some(r) = app.ui.crop_rect
|
||||
&& let Some(ratio) = preset_ratio(app)
|
||||
&& let Some(fitted) = fitted_ratio(r, ratio)
|
||||
// W x H x Resolution can change output size even when the frame already fits.
|
||||
&& (fitted != r || crate::crop_size::target(&app.ui.tool_options, dpi).is_some())
|
||||
{
|
||||
keyed(app, fitted);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new frame drawn from `anchor` to `cur`: ⇧ square, ⌥ from the centre, `ratio` held.
|
||||
pub fn drawn(anchor: [f64; 2], cur: [f64; 2], ratio: Option<f64>, mods: Modifiers) -> [f64; 4] {
|
||||
let e = match ratio {
|
||||
@@ -308,6 +345,7 @@ fn frame(app: &mut PhotocraftApp) {
|
||||
app.crop.frame_for = key;
|
||||
app.crop.editing = false;
|
||||
claim(app);
|
||||
fit_frame(app);
|
||||
}
|
||||
|
||||
/// A crop gesture is in progress: Space repositions the frame rather than panning.
|
||||
@@ -408,7 +446,7 @@ pub fn press(app: &mut PhotocraftApp) -> bool {
|
||||
new
|
||||
}
|
||||
|
||||
fn tolerance(app: &PhotocraftApp) -> f64 {
|
||||
pub(crate) fn tolerance(app: &PhotocraftApp) -> f64 {
|
||||
HANDLE_PX / (app.point_zoom() as f64).max(0.01)
|
||||
}
|
||||
|
||||
@@ -522,9 +560,13 @@ pub fn swap_orientation(app: &mut PhotocraftApp) -> bool {
|
||||
{
|
||||
app.ui.tool_options.crop_ratio = k;
|
||||
}
|
||||
keyed(app, swapped(r));
|
||||
crate::crop_mode::sync_frame(app);
|
||||
crate::crop_mode::auto_center(app);
|
||||
if preset_ratio(app).is_some() {
|
||||
apply_ratio(app);
|
||||
} else {
|
||||
keyed(app, swapped(r));
|
||||
crate::crop_mode::sync_frame(app);
|
||||
crate::crop_mode::auto_center(app);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -668,8 +710,7 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) {
|
||||
// Auto Center Preview: the box stays centred where it was while the handle follows
|
||||
// the pointer.
|
||||
let q = crate::crop_mode::to_press(app, Some(view), p);
|
||||
let keep = (rect[2] - rect[0] > 0.0 && rect[3] - rect[1] > 0.0).then(|| (rect[2] - rect[0]) / (rect[3] - rect[1]));
|
||||
let ratio = ratio.or(if mods.shift { keep } else { None });
|
||||
let ratio = resize_ratio(app, rect, mods);
|
||||
crate::crop_mode::live_resize(app, crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio, alt: mods.alt }, view);
|
||||
return;
|
||||
}
|
||||
@@ -709,6 +750,12 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) {
|
||||
app.ui.crop_rect = Some(rect);
|
||||
}
|
||||
|
||||
/// Geometry and snapping must use the same ratio so constrained handles stay aligned.
|
||||
pub(crate) fn resize_ratio(app: &PhotocraftApp, rect: [f64; 4], mods: Modifiers) -> Option<f64> {
|
||||
let keep = (rect[2] - rect[0] > 0.0 && rect[3] - rect[1] > 0.0).then(|| (rect[2] - rect[0]) / (rect[3] - rect[1]));
|
||||
preset_ratio(app).or(if mods.shift { keep } else { None })
|
||||
}
|
||||
|
||||
/// Cursor over the canvas at document point `p`: resize arrows on the edges, move inside.
|
||||
pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option<CursorIcon> {
|
||||
if app.ui.tool != Tool::Crop {
|
||||
@@ -835,6 +882,57 @@ mod tests {
|
||||
tool_event(app, ToolEvent::Up { x: last[0], y: last[1] }, mods);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fitting_a_ratio_keeps_the_centre_angle_and_area() {
|
||||
let mut app = app(SampleType::U8);
|
||||
app.ui.crop_rect = Some([20.0, 10.0, 180.0, 90.0]);
|
||||
app.ui.crop_angle = 25.0;
|
||||
for key in ["1:1", "16:9", "9:16", "", "0:0"] {
|
||||
let before = app.ui.crop_rect.unwrap();
|
||||
app.ui.tool_options.crop_ratio = key.into();
|
||||
crate::crop_size::chosen(&mut app);
|
||||
let after = app.ui.crop_rect.unwrap();
|
||||
assert_eq!(center(after), center(before));
|
||||
assert_eq!(app.ui.crop_angle, 25.0);
|
||||
assert!(after[0] >= before[0] && after[1] >= before[1] && after[2] <= before[2] && after[3] <= before[3]);
|
||||
if let Some(ratio) = preset_ratio(&app) {
|
||||
assert!(((after[2] - after[0]) / (after[3] - after[1]) - ratio).abs() < 1e-10);
|
||||
} else {
|
||||
assert_eq!(after, before);
|
||||
}
|
||||
}
|
||||
for ratio in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(fitted_ratio([0.0, 0.0, 200.0, 100.0], ratio).is_none());
|
||||
}
|
||||
assert!(fitted_ratio([-f64::MAX, 0.0, f64::MAX, 100.0], 1.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_a_ratio_fits_and_commits_without_a_resize() {
|
||||
for classic in [false, true] {
|
||||
let mut app = app(SampleType::U8);
|
||||
app.ui.tool_options.crop_shield.classic_mode = classic;
|
||||
ensure_frame(&mut app);
|
||||
app.ui.tool_options.crop_ratio = "1:1".into();
|
||||
crate::crop_size::chosen(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0]));
|
||||
crate::canvas::commit_crop(&mut app);
|
||||
assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 100));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entering_crop_with_a_saved_ratio_fits_the_selection_or_canvas() {
|
||||
let mut app = app(SampleType::U8);
|
||||
app.ui.tool_options.crop_ratio = "1:1".into();
|
||||
ensure_frame(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0]));
|
||||
cancel(&mut app);
|
||||
app.run("select.rect", json!({"x": 20, "y": 10, "width": 80, "height": 40})).unwrap();
|
||||
ensure_frame(&mut app);
|
||||
assert_eq!(app.ui.crop_rect, Some([40.0, 10.0, 80.0, 50.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_the_tool_frames_the_canvas_or_the_selection() {
|
||||
// #668: the Crop tool started with no frame.
|
||||
|
||||
@@ -35,7 +35,7 @@ pub enum PathRef {
|
||||
|
||||
impl PathRef {
|
||||
/// The engine's target params for this path.
|
||||
fn params(self) -> Value {
|
||||
pub(crate) fn params(self) -> Value {
|
||||
match self {
|
||||
PathRef::Work => json!({"name": "work"}),
|
||||
PathRef::Layer(id) => json!({"name": "layer", "layer": id}),
|
||||
@@ -104,19 +104,21 @@ impl Edit {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is Direct Selection what the pointer does now: its own tool, or the Pen with ⌘/Ctrl held.
|
||||
/// Is Direct Selection what the pointer does now: its own tool, or the Pen or an anchor point
|
||||
/// tool with ⌘/Ctrl held.
|
||||
fn direct(tool: Tool, mods: Modifiers) -> bool {
|
||||
tool == Tool::DirectSelection || (tool == Tool::Pen && mods.command)
|
||||
tool == Tool::DirectSelection || (matches!(tool, Tool::Pen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) && mods.command)
|
||||
}
|
||||
|
||||
/// Does the canvas draw Direct Selection's overlay instead of the plain path outlines?
|
||||
/// Does the canvas draw Direct Selection's overlay instead of the plain path outlines? The Add /
|
||||
/// Delete Anchor Point tools show it too: they edit the same paths.
|
||||
pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool {
|
||||
direct(app.ui.tool, mods) || app.ui.direct_selection.drag.is_some()
|
||||
direct(app.ui.tool, mods) || app.ui.direct_selection.drag.is_some() || matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint)
|
||||
}
|
||||
|
||||
/// The paths Direct Selection edits, front first: the targeted vector mask or the active shape
|
||||
/// layer's path, then the work path.
|
||||
fn candidates(app: &PhotocraftApp) -> Vec<(PathRef, Path)> {
|
||||
pub(crate) fn candidates(app: &PhotocraftApp) -> Vec<(PathRef, Path)> {
|
||||
let layer = crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app));
|
||||
let work = app.session.active().and_then(|st| st.doc.work_path.clone());
|
||||
layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect()
|
||||
|
||||
@@ -82,6 +82,8 @@ pub fn cmd_moves(t: Tool) -> bool {
|
||||
| Tool::PathSelection
|
||||
| Tool::DirectSelection
|
||||
| Tool::Pen
|
||||
| Tool::AddAnchorPoint
|
||||
| Tool::DeleteAnchorPoint
|
||||
| Tool::RectMarquee
|
||||
| Tool::EllipseMarquee
|
||||
| Tool::Lasso
|
||||
|
||||
@@ -1705,6 +1705,10 @@
|
||||
Paints from the document's opening state Maluje ze stavu dokumentu při otevření
|
||||
Path Selection Tool Nástroj výběr cesty
|
||||
Direct Selection Tool Nástroj přímý výběr
|
||||
Add Anchor Point Tool Nástroj přidat kotevní bod
|
||||
Delete Anchor Point Tool Nástroj odstranit kotevní bod
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Klepnutím na segment přidáte kotevní bod · {alt}+klik na kotevní bod jej odstraní
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Klepnutím na kotevní bod jej odstraníte · {alt}+klik na segment přidá nový bod
|
||||
Pattern Overlay Překrytí vzorkem
|
||||
Pen Pressure Přítlak pera
|
||||
Pen Tilt Náklon pera
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -1680,6 +1680,10 @@
|
||||
Paints from the document's opening state Malt aus dem Zustand beim Öffnen des Dokuments
|
||||
Path Selection Tool Pfadauswahl-Werkzeug
|
||||
Direct Selection Tool Direktauswahl-Werkzeug
|
||||
Add Anchor Point Tool Ankerpunkt-hinzufügen-Werkzeug
|
||||
Delete Anchor Point Tool Ankerpunkt-löschen-Werkzeug
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Klicke auf ein Segment, um einen Ankerpunkt hinzuzufügen · {alt}-Klick auf einen Ankerpunkt löscht ihn
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Klicke auf einen Ankerpunkt, um ihn zu löschen · {alt}-Klick auf ein Segment fügt einen hinzu
|
||||
Pattern Overlay Musterüberlagerung
|
||||
Pen Pressure Stiftdruck
|
||||
Pen Tilt Stiftneigung
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -3271,6 +3271,10 @@ cameraRaw Yellow Κίτρινο
|
||||
Paint Bucket Tool Κουβάς γεμίσματος (Paint Bucket Tool)
|
||||
Path Selection Tool Επιλογή διαδρομής (Path Selection Tool)
|
||||
Direct Selection Tool Άμεση επιλογή (Direct Selection Tool)
|
||||
Add Anchor Point Tool Εργαλείο προσθήκης σημείου αγκύρωσης
|
||||
Delete Anchor Point Tool Εργαλείο διαγραφής σημείου αγκύρωσης
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Κάντε κλικ σε ένα τμήμα για να προσθέσετε σημείο αγκύρωσης · {alt}-κλικ σε σημείο αγκύρωσης για διαγραφή
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Κάντε κλικ σε ένα σημείο αγκύρωσης για να το διαγράψετε · {alt}-κλικ σε τμήμα για προσθήκη
|
||||
Pen Tool Πένα (Pen Tool)
|
||||
Polygon Tool Πολύγωνο (Polygon Tool)
|
||||
Polygonal Lasso Tool Πολυγωνικό λάσο (Polygonal Lasso Tool)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 995 and column 18.
|
@@ -1688,6 +1688,10 @@
|
||||
Paints from the document's opening state Pinta a partir del estado en que se abrió el documento.
|
||||
Path Selection Tool Herramienta Selección de trazado
|
||||
Direct Selection Tool Herramienta Selección directa
|
||||
Add Anchor Point Tool Herramienta Añadir punto de ancla
|
||||
Delete Anchor Point Tool Herramienta Eliminar punto de ancla
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Haz clic en un segmento para añadir un punto de ancla · {alt}-clic en un punto de ancla para eliminarlo
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Haz clic en un punto de ancla para eliminarlo · {alt}-clic en un segmento para añadir uno
|
||||
Pattern Overlay Superposición de patrón
|
||||
Pen Pressure Presión del lápiz
|
||||
Pen Tilt Inclinación del lápiz
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -1666,6 +1666,10 @@
|
||||
Paints from the document's opening state Peint à partir de l'état d'ouverture du document
|
||||
Path Selection Tool Outil Sélection de tracé
|
||||
Direct Selection Tool Outil Sélection directe
|
||||
Add Anchor Point Tool Outil Ajout de point d'ancrage
|
||||
Delete Anchor Point Tool Outil Suppression de point d'ancrage
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Cliquez sur un segment pour ajouter un point d'ancrage · {alt}-clic sur un point d'ancrage pour le supprimer
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Cliquez sur un point d'ancrage pour le supprimer · {alt}-clic sur un segment pour en ajouter un
|
||||
Pattern Overlay Superposition de motif
|
||||
Pen Pressure Pression du stylet
|
||||
Pen Tilt Inclinaison du stylet
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -1660,6 +1660,10 @@
|
||||
Paints from the document's opening state Melukis dari kondisi awal dokumen saat dibuka
|
||||
Path Selection Tool Alat Path Selection
|
||||
Direct Selection Tool Alat Direct Selection
|
||||
Add Anchor Point Tool Alat Tambah Titik Jangkar
|
||||
Delete Anchor Point Tool Alat Hapus Titik Jangkar
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Klik segmen untuk menambah titik jangkar · {alt}-klik titik jangkar untuk menghapusnya
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Klik titik jangkar untuk menghapusnya · {alt}-klik segmen untuk menambah titik
|
||||
Pattern Overlay Overlay Pola
|
||||
Pen Pressure Tekanan Pena
|
||||
Pen Tilt Kemiringan Pena
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -1686,6 +1686,10 @@
|
||||
Paints from the document's opening state Dipinge dallo stato di apertura del documento
|
||||
Path Selection Tool Strumento Selezione tracciato
|
||||
Direct Selection Tool Strumento Selezione diretta
|
||||
Add Anchor Point Tool Strumento Aggiungi punto di ancoraggio
|
||||
Delete Anchor Point Tool Strumento Elimina punto di ancoraggio
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Fai clic su un segmento per aggiungere un punto di ancoraggio · {alt}-clic su un punto di ancoraggio per eliminarlo
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Fai clic su un punto di ancoraggio per eliminarlo · {alt}-clic su un segmento per aggiungerne uno
|
||||
Pattern Overlay Sovrapposizione pattern
|
||||
Pen Pressure Pressione penna
|
||||
Pen Tilt Inclinazione penna
|
||||
|
||||
|
@@ -1691,6 +1691,10 @@
|
||||
Paints from the document's opening state ドキュメントを開いた時点の状態から描画します
|
||||
Path Selection Tool パスコンポーネント選択ツール
|
||||
Direct Selection Tool パス選択ツール
|
||||
Add Anchor Point Tool アンカーポイントの追加ツール
|
||||
Delete Anchor Point Tool アンカーポイントの削除ツール
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it セグメントをクリックしてアンカーポイントを追加 · {alt}+クリック: アンカーポイントを削除
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one アンカーポイントをクリックして削除 · {alt}+クリック: セグメントにアンカーポイントを追加
|
||||
Pattern Overlay パターンオーバーレイ
|
||||
Pen Pressure ペンの筆圧
|
||||
Pen Tilt ペンの傾き
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -1659,6 +1659,10 @@
|
||||
Paints from the document's opening state 문서를 열었을 때의 상태로 칠하기
|
||||
Path Selection Tool 패스 선택 도구
|
||||
Direct Selection Tool 직접 선택 도구
|
||||
Add Anchor Point Tool 기준점 추가 도구
|
||||
Delete Anchor Point Tool 기준점 삭제 도구
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it 세그먼트를 클릭하여 기준점 추가 · {alt}-클릭: 기준점 삭제
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one 기준점을 클릭하여 삭제 · {alt}-클릭: 세그먼트에 기준점 추가
|
||||
Pattern Overlay 패턴 오버레이
|
||||
Pen Pressure 펜 압력
|
||||
Pen Tilt 펜 기울기
|
||||
|
||||
|
@@ -1668,6 +1668,10 @@
|
||||
Paints from the document's opening state Schildert vanuit de staat waarin het document werd geopend
|
||||
Path Selection Tool Padselectiegereedschap
|
||||
Direct Selection Tool Direct-selectiegereedschap
|
||||
Add Anchor Point Tool Gereedschap Ankerpunt toevoegen
|
||||
Delete Anchor Point Tool Gereedschap Ankerpunt verwijderen
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Klik op een segment om een ankerpunt toe te voegen · {alt}-klik op een ankerpunt om het te verwijderen
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Klik op een ankerpunt om het te verwijderen · {alt}-klik op een segment om er een toe te voegen
|
||||
Pattern Overlay Patroonbedekking
|
||||
Pen Pressure Pendruk
|
||||
Pen Tilt Penkanteling
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -1684,6 +1684,10 @@
|
||||
Paints from the document's opening state Maluje na podstawie stanu dokumentu z chwili otwarcia
|
||||
Path Selection Tool Narzędzie Zaznaczanie ścieżki
|
||||
Direct Selection Tool Narzędzie Zaznaczanie bezpośrednie
|
||||
Add Anchor Point Tool Narzędzie Dodaj punkt kontrolny
|
||||
Delete Anchor Point Tool Narzędzie Usuń punkt kontrolny
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Kliknij segment, aby dodać punkt kontrolny · {alt}-klik na punkcie kontrolnym usuwa go
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Kliknij punkt kontrolny, aby go usunąć · {alt}-klik na segmencie dodaje punkt
|
||||
Pattern Overlay Nakładka wzoru
|
||||
Pen Pressure Nacisk pióra
|
||||
Pen Tilt Nachylenie pióra
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -1665,6 +1665,10 @@
|
||||
Paints from the document's opening state Pinta a partir do estado de abertura do documento
|
||||
Path Selection Tool Ferramenta Seleção de demarcador
|
||||
Direct Selection Tool Ferramenta Seleção direta
|
||||
Add Anchor Point Tool Ferramenta Adicionar ponto de ancoragem
|
||||
Delete Anchor Point Tool Ferramenta Excluir ponto de ancoragem
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Clique em um segmento para adicionar um ponto de ancoragem · {alt}-clique em um ponto de ancoragem para excluí-lo
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Clique em um ponto de ancoragem para excluí-lo · {alt}-clique em um segmento para adicionar um
|
||||
Pattern Overlay Sobreposição de padrão
|
||||
Pen Pressure Pressão da caneta
|
||||
Pen Tilt Inclinação da caneta
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -1586,6 +1586,10 @@
|
||||
Pen Tool Перо
|
||||
Path Selection Tool Выделение контура
|
||||
Direct Selection Tool Выделение узла
|
||||
Add Anchor Point Tool Добавить узел
|
||||
Delete Anchor Point Tool Удалить узел
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Щёлкните сегмент, чтобы добавить узел · {alt}-щелчок по узлу удаляет его
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Щёлкните узел, чтобы удалить его · {alt}-щелчок по сегменту добавляет узел
|
||||
Rectangle Tool Прямоугольник
|
||||
Ellipse Tool Овал
|
||||
Triangle Tool Треугольник
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -1566,6 +1566,10 @@
|
||||
Pen Tool Інструмент «Перо»
|
||||
Path Selection Tool Інструмент «Виділення контуру»
|
||||
Direct Selection Tool Інструмент «Пряме виділення»
|
||||
Add Anchor Point Tool Інструмент «Додати вузол»
|
||||
Delete Anchor Point Tool Інструмент «Видалити вузол»
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it Клацніть сегмент, щоб додати вузол · {alt}+клацання по вузлу видаляє його
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one Клацніть вузол, щоб видалити його · {alt}+клацання по сегменту додає вузол
|
||||
Rectangle Tool Інструмент «Прямокутник»
|
||||
Ellipse Tool Інструмент «Еліпс»
|
||||
Triangle Tool Інструмент «Трикутник»
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1350 and column 18.
|
@@ -1703,6 +1703,10 @@
|
||||
Paints from the document's opening state 从文档打开时的状态绘制
|
||||
Path Selection Tool 路径选择工具
|
||||
Direct Selection Tool 直接选择工具
|
||||
Add Anchor Point Tool 添加锚点工具
|
||||
Delete Anchor Point Tool 删除锚点工具
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it 单击线段以添加锚点 · {alt}-单击锚点:删除锚点
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one 单击锚点将其删除 · {alt}-单击线段:添加锚点
|
||||
Pattern Overlay 图案叠加
|
||||
Pen Pressure 钢笔压力
|
||||
Pen Tilt 钢笔倾斜
|
||||
|
||||
|
@@ -1695,6 +1695,10 @@
|
||||
Paints from the document's opening state 從文件開啟時的狀態繪製
|
||||
Path Selection Tool 路徑選取工具
|
||||
Direct Selection Tool 直接選取工具
|
||||
Add Anchor Point Tool 增加錨點工具
|
||||
Delete Anchor Point Tool 刪除錨點工具
|
||||
Click a segment to add an anchor point · {alt}-click an anchor to delete it 按一下線段以增加錨點 · {alt}-按一下錨點:刪除錨點
|
||||
Click an anchor point to delete it · {alt}-click a segment to add one 按一下錨點將其刪除 · {alt}-按一下線段:增加錨點
|
||||
Pattern Overlay 圖樣覆蓋
|
||||
Pen Pressure 筆壓
|
||||
Pen Tilt 筆傾斜
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 47.
|
@@ -81,6 +81,8 @@ pub static ICONS: &[(&str, &[u8])] = &[
|
||||
("palette", include_bytes!("../../../assets/icons/palette.svg")),
|
||||
("panel-right", include_bytes!("../../../assets/icons/panel-right.svg")),
|
||||
("panels-top-left", include_bytes!("../../../assets/icons/panels-top-left.svg")),
|
||||
("pen-add-anchor", include_bytes!("../../../assets/icons/pen-add-anchor.svg")),
|
||||
("pen-delete-anchor", include_bytes!("../../../assets/icons/pen-delete-anchor.svg")),
|
||||
("pen-tool", include_bytes!("../../../assets/icons/pen-tool.svg")),
|
||||
("pencil", include_bytes!("../../../assets/icons/pencil.svg")),
|
||||
("pentagon", include_bytes!("../../../assets/icons/pentagon.svg")),
|
||||
|
||||
@@ -130,6 +130,8 @@ pub fn tool_icon(t: Tool) -> &'static str {
|
||||
Tool::QuickSelection => "circle-dashed",
|
||||
Tool::ObjectSelection => "square-dashed-mouse-pointer",
|
||||
Tool::Pen => "pen-tool",
|
||||
Tool::AddAnchorPoint => "pen-add-anchor",
|
||||
Tool::DeleteAnchorPoint => "pen-delete-anchor",
|
||||
Tool::PathSelection => "mouse-pointer-2",
|
||||
Tool::DirectSelection => "direct-select",
|
||||
Tool::Rectangle => "rectangle-horizontal",
|
||||
|
||||
@@ -21,6 +21,7 @@ pub mod adjust_preview;
|
||||
pub mod adjust_ui;
|
||||
mod alt_grab;
|
||||
pub mod analysis_ui;
|
||||
pub mod anchor_tools;
|
||||
pub mod artboard_ui;
|
||||
pub(crate) mod blend_preview;
|
||||
mod brand;
|
||||
|
||||
@@ -381,6 +381,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
|
||||
"layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => {
|
||||
crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string())
|
||||
}
|
||||
// ⇧⌘> / ⇧⌘<: the selected characters while typing, else the whole type layer.
|
||||
"type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" if params.as_object().is_none_or(|o| o.is_empty()) => {
|
||||
let p = crate::type_tool::with_target(app, json!({})).ok_or("the active layer is not a type layer")?;
|
||||
app.run(id, p)
|
||||
}
|
||||
// Formatting menus follow an inline text selection when editing. Outside an edit,
|
||||
// snapshot the selected type layers; explicit automation targets retain their scope.
|
||||
t if (t.starts_with("type.antiAlias.")
|
||||
|
||||
@@ -34,7 +34,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[
|
||||
&[Tool::Dodge, Tool::Burn, Tool::Sponge],
|
||||
],
|
||||
&[
|
||||
&[Tool::Pen],
|
||||
&[Tool::Pen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint],
|
||||
&[Tool::Type, Tool::VerticalType],
|
||||
&[Tool::PathSelection, Tool::DirectSelection],
|
||||
&[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape],
|
||||
@@ -826,6 +826,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));
|
||||
ui.style_mut().spacing.scroll = egui::style::ScrollStyle { bar_width: 4.0, ..egui::style::ScrollStyle::floating() };
|
||||
egui::ScrollArea::horizontal().id_salt("tool-options").auto_shrink([false, false]).show(ui, |ui| {
|
||||
// Font ink can extend beyond its advance width at fractional positions.
|
||||
// Include its gutter in the container layout, including right-aligned actions.
|
||||
egui::Frame::NONE.inner_margin(egui::Margin { right: 2, ..Default::default() }).show(ui, |ui| {
|
||||
ui.horizontal_centered(|ui| {
|
||||
if t.pro {
|
||||
crate::chrome_ui::home_button(app, ui);
|
||||
@@ -1148,14 +1151,17 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
crate::gradient_ui::options_changed(app, &before);
|
||||
}
|
||||
Tool::Crop if t.pro => {
|
||||
let before_ratio = crate::crop_ui::preset_ratio(app);
|
||||
let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height)));
|
||||
// Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919).
|
||||
crate::crop_presets::dropdown(app, ui);
|
||||
let o = &mut app.ui.tool_options;
|
||||
if o.crop_ratio == crate::crop_size::WHR {
|
||||
crate::crop_size::fields(o, ui);
|
||||
} else {
|
||||
// Keep partial edits in ToolOptions so the first side survives a frame.
|
||||
let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o);
|
||||
// Keep partial edits in ToolOptions so the first side survives a frame;
|
||||
// Original Ratio shows the document's numbers, as Photoshop does.
|
||||
let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size);
|
||||
let cw = widgets::value_field(ui, &mut rw, 0.0..=99_999.0, "", 54.0).changed();
|
||||
let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked();
|
||||
let ch = widgets::value_field(ui, &mut rh, 0.0..=99_999.0, "", 54.0).changed();
|
||||
@@ -1178,6 +1184,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
crate::crop_overlay::options_button(o, ui);
|
||||
let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui);
|
||||
widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels"));
|
||||
if crate::crop_ui::preset_ratio(app) != before_ratio {
|
||||
crate::crop_ui::apply_ratio(app);
|
||||
}
|
||||
if pick_shield_color {
|
||||
crate::crop_shield::pick_custom_color(app);
|
||||
}
|
||||
@@ -1362,10 +1371,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
crate::brush_panel::commit_gesture(app, ui.ctx(), &brush_before, &brush);
|
||||
});
|
||||
// Font ink can extend beyond its advance width at fractional positions.
|
||||
ui.expand_to_include_x(ui.min_rect().right() + 2.0);
|
||||
reveal_focused_control(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4904,6 +4912,62 @@ mod compact_visual_regressions {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wide_crop_options_bar_does_not_scroll() {
|
||||
for kind in crate::theme::ThemeKind::ALL {
|
||||
for scale in [1.0, 1.5, 2.0] {
|
||||
for mode in ["", crate::crop_size::WHR] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, kind);
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
if !Tokens::get(&ctx).pro {
|
||||
continue;
|
||||
}
|
||||
app.ui.tool = Tool::Crop;
|
||||
app.ui.tool_options.crop_ratio = mode.into();
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0));
|
||||
let clear_x = |output: &egui::FullOutput| {
|
||||
output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.job.text == "Clear" => Some(t.pos.x),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let mut before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui));
|
||||
before.textures_delta.clear();
|
||||
for _ in 0..3 {
|
||||
before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui));
|
||||
before.textures_delta.clear();
|
||||
}
|
||||
let mut after = before.clone();
|
||||
for _ in 0..6 {
|
||||
after = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
events: vec![
|
||||
egui::Event::PointerMoved(pos2(800.0, 20.0)),
|
||||
egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(-100.0, 0.0),
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
},
|
||||
],
|
||||
..input_at_scale(screen, scale)
|
||||
},
|
||||
|ui| options_bar(&mut app, ui),
|
||||
);
|
||||
after.textures_delta.clear();
|
||||
}
|
||||
assert_eq!(clear_x(&before), clear_x(&after), "a roomy bar must not have horizontal overflow");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_tool_options_can_scroll_to_the_last_control() {
|
||||
for kind in crate::theme::ThemeKind::ALL {
|
||||
|
||||
@@ -201,6 +201,10 @@ fn key_owner(app: &PhotocraftApp, ctx: &egui::Context) -> (bool, usize, bool, bo
|
||||
(crate::menu_nav::is_open(ctx), app.ui.dialogs.len(), app.discard.is_some(), distort, app.ui.text_edit.is_some())
|
||||
}
|
||||
|
||||
/// Keys whose shortcuts follow the key's position, as in Photoshop: ⇧⌘. is ⇧⌘> on a US layout,
|
||||
/// but types `:` on Nordic and German ones, so its character would never match.
|
||||
const POSITIONAL: [Key; 2] = [Key::Period, Key::Comma];
|
||||
|
||||
/// Dispatch this frame's shortcut presses in the order they arrived (⌘Z then ⌘S undoes, then
|
||||
/// saves the undone state; #440), consuming each. A press matching several bindings goes to the
|
||||
/// first in table order (⇧⌘Z before ⌘Z). Stops after a shortcut that hands the keyboard to
|
||||
@@ -216,8 +220,11 @@ pub fn dispatch_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, focus: Foc
|
||||
let table: Vec<(String, KeyboardShortcut)> =
|
||||
bindings(app).into_iter().filter(|(id, sc)| focus.allows(sc) && !(editing && TEXT_OWNED.contains(&id.as_str()))).collect();
|
||||
let command = |e: &egui::Event| match e {
|
||||
egui::Event::Key { key, pressed: true, modifiers, .. } => {
|
||||
table.iter().find(|(_, sc)| key_matches(sc, *key, *modifiers)).map(|(id, _)| (id.clone(), *key == Key::Tab))
|
||||
egui::Event::Key { key, physical_key, pressed: true, modifiers, .. } => {
|
||||
let by_position = physical_key
|
||||
.filter(|p| POSITIONAL.contains(p))
|
||||
.and_then(|p| table.iter().find(|(_, sc)| sc.logical_key == p && key_matches(sc, p, *modifiers)));
|
||||
by_position.or_else(|| table.iter().find(|(_, sc)| key_matches(sc, *key, *modifiers))).map(|(id, _)| (id.clone(), *key == Key::Tab))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -617,3 +617,37 @@ fn f6_while_recording_records_a_named_call_not_the_child_steps() {
|
||||
h.state_mut().run("actions.stop", json!({})).unwrap();
|
||||
assert_eq!(h.state().session.actions.list[1].steps, [("actions.play".into(), json!({"action":"LivePrint 2R"}))]);
|
||||
}
|
||||
|
||||
/// ⇧⌘> / ⇧⌘< follow the keys' position: a Nordic or German layout reports ⇧⌘. as `:`, which is
|
||||
/// also ⇧⌘; (View › Snap) on a US layout. While typing they size only the selected characters.
|
||||
#[test]
|
||||
fn type_size_keys_follow_key_position_and_the_typed_selection() {
|
||||
let mut h = harness();
|
||||
let st = h.state().session.active().unwrap();
|
||||
let id = st.doc.walk().into_iter().find(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).unwrap().2.id.0;
|
||||
h.state_mut().session.execute("layer.select", json!({"layer": id})).unwrap();
|
||||
let sizes = |h: &Harness<'_, PhotocraftApp>| match &h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content {
|
||||
LayerContent::Text(t) => t.char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::<Vec<_>>(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let positional = |h: &mut Harness<'_, PhotocraftApp>, key, physical| {
|
||||
let m = platform(Modifiers::COMMAND | Modifiers::SHIFT);
|
||||
h.event(egui::Event::ModifiersChanged(m));
|
||||
h.event(egui::Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: m });
|
||||
h.event(egui::Event::Key { key, physical_key: Some(physical), pressed: false, repeat: false, modifiers: m });
|
||||
h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.run_steps(2);
|
||||
};
|
||||
let base = sizes(&h)[0].1;
|
||||
positional(&mut h, egui::Key::Colon, egui::Key::Period);
|
||||
assert_eq!(logged(&h), ["type.increaseSize"]);
|
||||
assert_eq!(sizes(&h), [(5, base + 2.0)], "the whole layer grows from the canvas");
|
||||
|
||||
crate::type_tool::edit_active(h.state_mut()).unwrap();
|
||||
if let Some(ed) = h.state_mut().ui.text_edit.as_mut() {
|
||||
(ed.anchor, ed.caret) = (0, 2);
|
||||
}
|
||||
positional(&mut h, egui::Key::Semicolon, egui::Key::Comma);
|
||||
assert_eq!(logged(&h), ["type.decreaseSize"]);
|
||||
assert_eq!(sizes(&h), [(2, base), (3, base + 2.0)], "only the selected \"He\" shrinks");
|
||||
}
|
||||
@@ -169,7 +169,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) {
|
||||
// outside the selection moves the layer as the Move tool does (#2681).
|
||||
let tool = crate::canvas::event_tool(app, mods);
|
||||
let moves_layer = crate::canvas::command_moves_layer(app, tool, p, mods);
|
||||
let tol = tolerance(app);
|
||||
let crop_tol = crate::crop_ui::tolerance(app);
|
||||
let gesture = if let Some(t) = &app.ui.transform {
|
||||
if t.mode == crate::state::TransformMode::Distort {
|
||||
// Distort is freehand corner placement (fitting an image onto a screen, say): guides
|
||||
@@ -189,7 +189,8 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) {
|
||||
moving_rect(app, tool).map(|rect| (Gesture::Move { rect }, exclude))
|
||||
} else if tool == Tool::Crop
|
||||
&& (crate::crop_mode::classic(app) || app.crop.default_frame)
|
||||
&& let Some(rect) = app.ui.crop_rect.filter(|r| crate::crop_ui::angle(app) == 0.0 && crate::crop_ui::hit(*r, p, tol) == crate::crop_ui::Hit::Inside)
|
||||
&& let Some(rect) =
|
||||
app.ui.crop_rect.filter(|r| crate::crop_ui::angle(app) == 0.0 && crate::crop_ui::hit(*r, p, crop_tol) == crate::crop_ui::Hit::Inside)
|
||||
{
|
||||
// Inside the untouched default frame draws a new crop (in both modes): snap its corner, not
|
||||
// the old canvas-sized frame's bounds. An edited Classic Mode frame still moves and snaps
|
||||
@@ -198,7 +199,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) {
|
||||
Some((gesture, Vec::new()))
|
||||
} else if tool == Tool::Crop
|
||||
&& (crate::crop_ui::turns_at(app, p)
|
||||
|| app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), p, tol) == crate::crop_ui::Hit::Inside))
|
||||
|| app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), p, crop_tol) == crate::crop_ui::Hit::Inside))
|
||||
{
|
||||
// Turning the frame, moving a turned one (its edges don't line up with anything), or in
|
||||
// the default mode moving or turning the image under the box: no snapping.
|
||||
@@ -249,7 +250,7 @@ fn pixel_round(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
|
||||
}
|
||||
|
||||
/// Snap one pointer position for the active gesture; records the alignment lines.
|
||||
fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
|
||||
fn apply(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> [f64; 2] {
|
||||
let tol = tolerance(app);
|
||||
let Some(snap) = app.prefs_rt.snap.as_ref() else { return p };
|
||||
if snap.disabled {
|
||||
@@ -257,7 +258,8 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
|
||||
return p;
|
||||
}
|
||||
let (out, lines) = match &snap.gesture {
|
||||
Gesture::Point | Gesture::Guide => snap.targets.snap_point(p, tol),
|
||||
Gesture::Point => live_crop_handle(app, p, mods, &snap.targets, tol).unwrap_or_else(|| snap.targets.snap_point(p, tol)),
|
||||
Gesture::Guide => snap.targets.snap_point(p, tol),
|
||||
Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } => {
|
||||
let d = [p[0] - snap.start[0], p[1] - snap.start[1]];
|
||||
let moved = [rect[0] + d[0], rect[1] + d[1], rect[2] + d[0], rect[3] + d[1]];
|
||||
@@ -270,6 +272,66 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] {
|
||||
out
|
||||
}
|
||||
|
||||
/// Snap the proposed handle on the image, calculated from the original camera. Snapping the
|
||||
/// pointer in the moving camera feeds the previous frame's pan back into the resize and makes
|
||||
/// a stationary pointer oscillate near the canvas edges.
|
||||
fn live_crop_handle(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers, targets: &SnapTargets, tol: f64) -> Option<([f64; 2], Vec<SnapLine>)> {
|
||||
if app.ui.tool != Tool::Crop {
|
||||
return None;
|
||||
}
|
||||
let crate::crop_ui::CropDrag::Resize { hx, hy, start, rect, view: Some(view) } = app.crop.drag? else { return None };
|
||||
let deg = crate::crop_ui::angle(app);
|
||||
let q = crate::crop_mode::to_press(app, Some(view), p);
|
||||
let g = crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio: crate::crop_ui::resize_ratio(app, rect, mods), alt: mods.alt };
|
||||
let (frame, _) = crate::crop_mode::resized_frame(g)?;
|
||||
let at = |r: [f64; 4]| {
|
||||
let c = crate::crop_ui::center(r);
|
||||
crate::crop_ui::turn([c[0] + f64::from(hx) * (r[2] - r[0]) / 2.0, c[1] + f64::from(hy) * (r[3] - r[1]) / 2.0], c, deg)
|
||||
};
|
||||
let handle = at(frame);
|
||||
let (snapped, mut lines) = targets.snap_point(handle, tol);
|
||||
let mut d = crate::crop_ui::turn([snapped[0] - handle[0], snapped[1] - handle[1]], [0.0, 0.0], -deg);
|
||||
// An edge handle controls only its own axis, not the midpoint along the other one.
|
||||
if hx == 0 {
|
||||
d[0] = 0.0;
|
||||
}
|
||||
if hy == 0 {
|
||||
d[1] = 0.0;
|
||||
}
|
||||
if deg == 0.0 {
|
||||
lines.retain(|line| if line.vertical { hx != 0 } else { hy != 0 });
|
||||
}
|
||||
// Auto Center Preview moves both screen edges. On the image the opposite edge stays put,
|
||||
// so the grabbed edge travels twice as far as the pointer (once with Alt).
|
||||
let scale = if mods.alt { 1.0 } else { 2.0 };
|
||||
if lines.is_empty() {
|
||||
return Some((p, lines));
|
||||
}
|
||||
let original = at(rect);
|
||||
let travel = crate::crop_ui::turn([handle[0] - original[0], handle[1] - original[1]], [0.0, 0.0], -deg);
|
||||
let mut local = [(travel[0] + d[0]) / scale, (travel[1] + d[1]) / scale];
|
||||
if deg == 0.0
|
||||
&& hx != 0
|
||||
&& hy != 0
|
||||
&& let Some(k) = g.ratio
|
||||
{
|
||||
// A corner with a ratio has one degree of freedom. Put the other axis on the same
|
||||
// ratio, rather than letting the raw pointer's unused axis override the snapped edge.
|
||||
if lines.iter().any(|line| line.vertical) {
|
||||
local[1] = f64::from(hy) * ((rect[2] - rect[0] + 2.0 * f64::from(hx) * local[0]) / k - (rect[3] - rect[1])) / 2.0;
|
||||
} else {
|
||||
local[0] = f64::from(hx) * ((rect[3] - rect[1] + 2.0 * f64::from(hy) * local[1]) * k - (rect[2] - rect[0])) / 2.0;
|
||||
}
|
||||
}
|
||||
let d = crate::crop_ui::turn(local, [0.0, 0.0], deg);
|
||||
let q = [start[0] + d[0], start[1] + d[1]];
|
||||
if let Some((snapped_frame, _)) = crate::crop_mode::resized_frame(crate::crop_mode::LiveResize { q, ..g }) {
|
||||
let h = at(snapped_frame);
|
||||
lines.retain(|line| (if line.vertical { h[0] } else { h[1] } - line.pos).abs() < 1e-3);
|
||||
}
|
||||
Some((crate::crop_mode::from_press(app, view, q), lines))
|
||||
}
|
||||
|
||||
/// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it).
|
||||
pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent {
|
||||
match ev {
|
||||
@@ -277,8 +339,16 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier
|
||||
begin(app, [x, y], mods);
|
||||
// Moves snap their delta, which is zero at the start: keep the press point.
|
||||
let p = match app.prefs_rt.snap.as_ref().map(|s| &s.gesture) {
|
||||
Some(Gesture::Point) => {
|
||||
let q = apply(app, [x, y]);
|
||||
Some(Gesture::Point)
|
||||
if !(app.ui.tool == Tool::Crop
|
||||
&& app.ui.crop_rect.is_some_and(|r| {
|
||||
matches!(
|
||||
crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), [x, y], crate::crop_ui::tolerance(app)),
|
||||
crate::crop_ui::Hit::Handle(..)
|
||||
)
|
||||
})) =>
|
||||
{
|
||||
let q = apply(app, [x, y], mods);
|
||||
pixel_round(app, q)
|
||||
}
|
||||
_ => [x, y],
|
||||
@@ -292,7 +362,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier
|
||||
if let Some(s) = app.prefs_rt.snap.as_mut() {
|
||||
s.disabled = override_held(mods);
|
||||
}
|
||||
let q = apply(app, [x, y]);
|
||||
let q = apply(app, [x, y], mods);
|
||||
let p = pixel_round(app, q);
|
||||
ToolEvent::Move { x: p[0], y: p[1], pressure }
|
||||
}
|
||||
@@ -303,7 +373,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier
|
||||
if let Some(s) = app.prefs_rt.snap.as_mut() {
|
||||
s.disabled = override_held(mods);
|
||||
}
|
||||
let q = apply(app, [x, y]);
|
||||
let q = apply(app, [x, y], mods);
|
||||
let p = pixel_round(app, q);
|
||||
app.prefs_rt.snap = None;
|
||||
app.prefs_rt.snap_lines.clear();
|
||||
|
||||
@@ -111,6 +111,8 @@ pub enum Tool {
|
||||
QuickSelection,
|
||||
ObjectSelection,
|
||||
Pen,
|
||||
AddAnchorPoint,
|
||||
DeleteAnchorPoint,
|
||||
PathSelection,
|
||||
DirectSelection,
|
||||
Rectangle,
|
||||
@@ -124,7 +126,7 @@ pub enum Tool {
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
pub const ALL: [Tool; 56] = [
|
||||
pub const ALL: [Tool; 58] = [
|
||||
Tool::Move,
|
||||
Tool::RectMarquee,
|
||||
Tool::EllipseMarquee,
|
||||
@@ -171,6 +173,8 @@ impl Tool {
|
||||
Tool::QuickSelection,
|
||||
Tool::ObjectSelection,
|
||||
Tool::Pen,
|
||||
Tool::AddAnchorPoint,
|
||||
Tool::DeleteAnchorPoint,
|
||||
Tool::PathSelection,
|
||||
Tool::DirectSelection,
|
||||
Tool::Rectangle,
|
||||
@@ -233,6 +237,8 @@ impl Tool {
|
||||
Tool::QuickSelection => "Quick Selection Tool",
|
||||
Tool::ObjectSelection => "Object Selection Tool",
|
||||
Tool::Pen => "Pen Tool",
|
||||
Tool::AddAnchorPoint => "Add Anchor Point Tool",
|
||||
Tool::DeleteAnchorPoint => "Delete Anchor Point Tool",
|
||||
Tool::PathSelection => "Path Selection Tool",
|
||||
Tool::DirectSelection => "Direct Selection Tool",
|
||||
Tool::Rectangle => "Rectangle Tool",
|
||||
@@ -295,7 +301,7 @@ impl Tool {
|
||||
Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0',
|
||||
Tool::Dodge | Tool::Burn | Tool::Sponge => 'O',
|
||||
Tool::QuickSelection | Tool::ObjectSelection => 'W',
|
||||
Tool::Pen => 'P',
|
||||
Tool::Pen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint => 'P',
|
||||
Tool::PathSelection | Tool::DirectSelection => 'A',
|
||||
Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => 'U',
|
||||
}
|
||||
@@ -1237,7 +1243,10 @@ mod tests {
|
||||
assert!(!Tool::RedEye.is_brushlike());
|
||||
assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp));
|
||||
assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp));
|
||||
assert_eq!(Tool::ALL.len(), 56);
|
||||
assert_eq!(Tool::ALL.len(), 58);
|
||||
assert_eq!(Tool::from_name("addAnchorPoint"), Some(Tool::AddAnchorPoint));
|
||||
assert_eq!(Tool::from_name("Delete Anchor Point Tool"), Some(Tool::DeleteAnchorPoint));
|
||||
assert_eq!(Tool::DeleteAnchorPoint.key(), 'P');
|
||||
assert_eq!(Tool::from_name("Remove Tool"), Some(Tool::Remove));
|
||||
assert_eq!(Tool::Remove.key(), 'J');
|
||||
assert!(Tool::Remove.is_brushlike());
|
||||
|
||||
@@ -646,7 +646,7 @@ pub fn install_fonts(ctx: &egui::Context) {
|
||||
install_fonts_with(ctx, crate::cjk_fonts::Sources::system());
|
||||
}
|
||||
|
||||
/// [`install_fonts`] with the CJK/Thai fallback fonts taken from `cjk` (tests swap the sources).
|
||||
/// [`install_fonts`] with the CJK and other-script fallback fonts taken from `cjk` (tests swap the sources).
|
||||
pub fn install_fonts_with(ctx: &egui::Context, cjk: crate::cjk_fonts::Sources) {
|
||||
let mut fonts = FontDefinitions::default();
|
||||
// The bundled fonts are inflated on first use (photocraft_text::fonts). Should one ever fail
|
||||
@@ -692,7 +692,7 @@ pub fn install_fonts_with(ctx: &egui::Context, cjk: crate::cjk_fonts::Sources) {
|
||||
{
|
||||
ctx.add_plugin(UiFontSizePlugin { applied: size, defer_after_install: true });
|
||||
}
|
||||
// Japanese / Chinese / Korean / Thai fallback fonts (craft-fonts' Japanese ones if built in, then
|
||||
// CJK, Thai, Arabic, Indic and other script fallback fonts (craft-fonts' Japanese ones if built in, then
|
||||
// the system's) are registered on demand (cjk_fonts.rs).
|
||||
crate::cjk_fonts::install_with(ctx, cjk);
|
||||
}
|
||||
|
||||
@@ -97,8 +97,14 @@ pub fn document_selection_mode(app: &PhotocraftApp, tool: Tool, m: egui::Modifie
|
||||
}
|
||||
}
|
||||
|
||||
/// The badge the cursor of `tool` shows with modifiers `m` (None for non-selection tools or New).
|
||||
/// The badge the cursor of `tool` shows with modifiers `m` (None for non-selection tools or New;
|
||||
/// the anchor point tools show theirs).
|
||||
pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option<Badge> {
|
||||
// Add / Delete Anchor Point: + or − beside the crosshair, as on Photoshop's pen cursors (⌥
|
||||
// swaps them; ⌘ is Direct Selection, which shows none).
|
||||
if let Some(t) = crate::anchor_tools::effective(tool, m) {
|
||||
return (!m.command).then_some(if t == Tool::AddAnchorPoint { Badge::Add } else { Badge::Subtract });
|
||||
}
|
||||
if !is_selection_tool(tool) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1060,6 +1060,20 @@ fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_json::Value)
|
||||
let _ = app.run("type.setStyle", p);
|
||||
}
|
||||
|
||||
/// `props` aimed at the type target: its layer, the selected characters while typing, and the
|
||||
/// typing session's undo step. `None` without a type target.
|
||||
pub(crate) fn with_target(app: &PhotocraftApp, mut props: serde_json::Value) -> Option<serde_json::Value> {
|
||||
let (layer, range) = target(app)?;
|
||||
props["layer"] = json!(layer);
|
||||
if let Some(r) = range {
|
||||
props["range"] = json!(r);
|
||||
}
|
||||
if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) {
|
||||
props["coalesce"] = json!(key);
|
||||
}
|
||||
Some(props)
|
||||
}
|
||||
|
||||
/// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling
|
||||
/// the dialog never changes the text selection, tool colours, or document history.
|
||||
pub fn open_color_picker(app: &mut PhotocraftApp, rgb: [f32; 3]) -> u64 {
|
||||
|
||||
@@ -486,6 +486,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
|
||||
if crate::direct_select::shows(app, painter.ctx().input(|i| i.modifiers)) {
|
||||
// Direct Selection (or the Pen with ⌘/Ctrl held) draws the paths it edits (#790).
|
||||
crate::direct_select::draw_overlay(app, painter, &to_scr, accent, paths);
|
||||
if paths {
|
||||
crate::anchor_tools::draw_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers));
|
||||
}
|
||||
} else if paths {
|
||||
if vector_tool {
|
||||
if let Some(wp) = &doc.work_path {
|
||||
@@ -535,7 +538,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
|
||||
|
||||
/// Options bar for vector tools; false for other tools.
|
||||
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
|
||||
if !(is_shape_tool(tool) || matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection)) {
|
||||
if !(is_shape_tool(tool) || matches!(tool, Tool::Pen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::PathSelection | Tool::DirectSelection)) {
|
||||
return false;
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -558,6 +561,15 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if matches!(tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) {
|
||||
let hint = if tool == Tool::AddAnchorPoint {
|
||||
tl!("Click a segment to add an anchor point · {alt}-click an anchor to delete it")
|
||||
} else {
|
||||
tl!("Click an anchor point to delete it · {alt}-click a segment to add one")
|
||||
};
|
||||
lbl(ui, &crate::i18n::fmt(hint, &[("alt", &crate::shortcuts::pretty("Alt"))]));
|
||||
return true;
|
||||
}
|
||||
if tool == Tool::Pen {
|
||||
let opts = [("path".to_string(), tl!("Path")), ("shape".to_string(), tl!("Shape"))];
|
||||
crate::widgets::dropdown(ui, "pen-mode", &mut o.vector_mode, &opts, 80.0);
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//! adapter exists (like `crop_beyond_canvas.rs`).
|
||||
|
||||
use egui::{Key, Modifiers, PointerButton, Pos2, pos2, vec2};
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use photocraft_ui_egui::PhotocraftApp;
|
||||
use photocraft_ui_egui::canvas::ViewXform;
|
||||
use photocraft_ui_egui::control::{ControlRequest, handle};
|
||||
@@ -101,6 +102,71 @@ fn setup() -> Option<Harness> {
|
||||
Some(h)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ratio_dropdown_updates_the_preview_and_enter_without_touching_a_handle() {
|
||||
let Some(mut h) = setup() else { return };
|
||||
h.get_by_value("Ratio").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("1 : 1 (Square)").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().ui.crop_rect, Some([50.0, 0.0, 250.0, 200.0]));
|
||||
if let Some(dir) = std::env::var_os("CRAFT_UI_VISUAL_FIXTURES") {
|
||||
let dir = std::path::PathBuf::from(dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
h.render().unwrap().save(dir.join("photocraft-crop-square.png")).unwrap();
|
||||
}
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_doc::Size::new(200, 200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_swap_button_and_x_apply_the_same_inscribed_ratio() {
|
||||
let Some(mut h) = setup() else { return };
|
||||
let original = [30.0, 20.0, 270.0, 180.0];
|
||||
h.state_mut().ui.crop_rect = Some(original);
|
||||
h.state_mut().ui.tool_options.crop_ratio = "3:2".into();
|
||||
h.run_steps(3);
|
||||
let before = mid(screen_box(&h));
|
||||
h.get_by_label("Swaps height and width").click();
|
||||
h.run_steps(3);
|
||||
let button = h.state().ui.crop_rect.unwrap();
|
||||
assert_eq!(h.state().ui.tool_options.crop_ratio, "2:3");
|
||||
assert!(((button[2] - button[0]) / (button[3] - button[1]) - 2.0 / 3.0).abs() < 1e-10);
|
||||
assert!(button[0] >= original[0] && button[2] <= original[2] && button[1] >= original[1] && button[3] <= original[3]);
|
||||
assert!(mid(screen_box(&h)).distance(before) < 0.01);
|
||||
h.state_mut().ui.crop_rect = Some(original);
|
||||
h.state_mut().ui.tool_options.crop_ratio = "3:2".into();
|
||||
h.run_steps(3);
|
||||
h.key_press(Key::X);
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().ui.crop_rect, Some(button));
|
||||
assert!(mid(screen_box(&h)).distance(before) < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resize_renders_the_frame_and_image_with_the_same_camera() {
|
||||
let Some(mut h) = setup() else { return };
|
||||
let box0 = screen_box(&h);
|
||||
let c = mid(box0);
|
||||
let right = pos2(box0[1].x, c.y);
|
||||
drag(&mut h, right, right - vec2(48.0, 0.0), 6, |h, i| {
|
||||
let img = h.render().expect("render");
|
||||
let b = screen_box(h);
|
||||
// The left edge also moves inward with Auto Center Preview. Sample either side
|
||||
// away from the handles and the red patch: white inside, dimmed white outside.
|
||||
let y = c.y + 70.0;
|
||||
for x in [b[0].x - 5.0, b[1].x + 5.0] {
|
||||
let px = img.get_pixel(x.round() as u32, y.round() as u32);
|
||||
assert!(px[0] < 230 && px[1] < 230 && px[2] < 230, "frame {i}, outside at {x}: {px:?}");
|
||||
}
|
||||
for x in [b[0].x + 5.0, b[1].x - 5.0] {
|
||||
let px = img.get_pixel(x.round() as u32, y.round() as u32);
|
||||
assert!(px[0] > 245 && px[1] > 245 && px[2] > 245, "frame {i}, inside at {x}: {px:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_inside_moves_the_image_and_the_box_stays_centred() {
|
||||
let Some(mut h) = setup() else { return };
|
||||
|
||||
+129
-4
@@ -1,6 +1,6 @@
|
||||
//! Point-level path editing, Photoshop's Direct Selection and Convert Point tools: move anchors,
|
||||
//! drag direction handles, reshape a segment by dragging it, convert between smooth and corner
|
||||
//! points, and hit-test a path's parts. Pure geometry on [`Path`]; the engine's `path.*` edit
|
||||
//! Point-level path editing, Photoshop's Direct Selection, Convert Point and Add / Delete Anchor
|
||||
//! Point tools: move anchors, drag direction handles, reshape a segment by dragging it, convert
|
||||
//! between smooth and corner points, insert and remove anchors, and hit-test a path's parts. Pure geometry on [`Path`]; the engine's `path.*` edit
|
||||
//! commands and the canvas previews share it, so a preview is exactly what the command commits.
|
||||
//!
|
||||
//! Knots are addressed as `[subpath, knot]`. Every edit validates its indices and returns an
|
||||
@@ -167,6 +167,59 @@ pub fn bend_segment(path: &mut Path, knot: [usize; 2], t: f64, d: [f64; 2]) -> R
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lerp(a: Point, b: Point, t: f64) -> Point {
|
||||
Point::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
|
||||
}
|
||||
|
||||
/// Add Anchor Point: inserts an anchor into the segment leaving `knot` at curve parameter `t`
|
||||
/// (strictly between 0 and 1) and returns the new knot's `[subpath, knot]`. A curve is split at
|
||||
/// `t` (de Casteljau), so its shape does not change and the new anchor is smooth; on a straight
|
||||
/// segment (both handles retracted) the new anchor is a corner on the line.
|
||||
pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2], String> {
|
||||
if !(t.is_finite() && t > 0.0 && t < 1.0) {
|
||||
return Err("`t` must be strictly between 0 and 1".into());
|
||||
}
|
||||
let end = segment_end(path, knot)?;
|
||||
let retracted = |k: &Knot, h: Handle| dist(handle(k, h), k.anchor) < 1e-9;
|
||||
let a = *knot_mut(path, knot)?;
|
||||
let b = *knot_mut(path, end)?;
|
||||
let new = if retracted(&a, Handle::Out) && retracted(&b, Handle::In) {
|
||||
let p = lerp(a.anchor, b.anchor, t);
|
||||
Knot::corner(p.x, p.y)
|
||||
} else {
|
||||
let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t));
|
||||
let (p012, p123) = (lerp(p01, p12, t), lerp(p12, p23, t));
|
||||
knot_mut(path, knot)?.out_ctrl = p01;
|
||||
knot_mut(path, end)?.in_ctrl = p23;
|
||||
Knot::smooth(lerp(p012, p123, t), p012, p123)
|
||||
};
|
||||
let [s, k] = knot;
|
||||
let at = k.checked_add(1).ok_or_else(|| format!("no segment leaves knot {k} of subpath {s}"))?;
|
||||
let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?;
|
||||
// `at` ≤ len: the segment leaving `k` exists, so `k` < len.
|
||||
sp.knots.insert(at.min(sp.knots.len()), new);
|
||||
Ok([s, at])
|
||||
}
|
||||
|
||||
/// Delete Anchor Point: removes a knot. Its neighbours are joined by one segment that keeps the
|
||||
/// previous anchor's out handle and the next anchor's in handle; a closed subpath stays closed.
|
||||
/// Removing a subpath's last anchor removes the subpath. Refused (unchanged) when it would leave
|
||||
/// the path with no anchors at all. Returns whether the subpath was removed.
|
||||
pub fn delete_anchor(path: &mut Path, [s, k]: [usize; 2]) -> Result<bool, String> {
|
||||
knot_mut(path, [s, k])?;
|
||||
let total: usize = path.subpaths.iter().map(|sp| sp.knots.len()).fold(0, usize::saturating_add);
|
||||
if total <= 1 {
|
||||
return Err("can't delete the path's only anchor point; delete the path instead".into());
|
||||
}
|
||||
let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?;
|
||||
if sp.knots.len() <= 1 {
|
||||
path.subpaths.remove(s);
|
||||
return Ok(true);
|
||||
}
|
||||
sp.knots.remove(k);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Every anchor of subpath `s` (⌥-click with Direct Selection selects the whole subpath).
|
||||
pub fn subpath_anchors(path: &Path, s: usize) -> Vec<[usize; 2]> {
|
||||
path.subpaths.get(s).map_or_else(Vec::new, |sp| (0..sp.knots.len()).map(|k| [s, k]).collect())
|
||||
@@ -186,7 +239,8 @@ pub fn anchors_in(path: &Path, [x0, y0, x1, y1]: [f64; 4]) -> Vec<[usize; 2]> {
|
||||
out
|
||||
}
|
||||
|
||||
fn eval(seg: &[Point; 4], t: f64) -> Point {
|
||||
/// The point at parameter `t` of the cubic segment `[anchor, out, in, anchor]`.
|
||||
pub fn eval(seg: &[Point; 4], t: f64) -> Point {
|
||||
let u = 1.0 - t;
|
||||
let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
Point::new(a * seg[0].x + b * seg[1].x + c * seg[2].x + d * seg[3].x, a * seg[0].y + b * seg[1].y + c * seg[2].y + d * seg[3].y)
|
||||
@@ -331,6 +385,77 @@ mod tests {
|
||||
assert_eq!(hit(&tri(), Point::new(50.0, 40.0), 3.0, &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_to_a_curve_splits_it_without_changing_its_shape() {
|
||||
for t in [0.5, 0.13, 0.9] {
|
||||
let mut p = curve();
|
||||
let seg = curve().subpaths[0].segments()[0];
|
||||
let r = add_anchor(&mut p, [0, 0], t).unwrap();
|
||||
assert_eq!((r, p.subpaths[0].knots.len()), ([0, 1], 4));
|
||||
let k = at(&p, 0, 1);
|
||||
assert!(k.smooth, "a split curve gets a smooth anchor");
|
||||
assert!(dist(k.anchor, eval(&seg, t)) < 1e-9, "the new anchor is where it was clicked");
|
||||
// 100 evenly spaced parameters of the old segment land on the two halves.
|
||||
let halves = p.subpaths[0].segments();
|
||||
for i in 0..=100 {
|
||||
let u = i as f64 / 100.0;
|
||||
let q = if u <= t { eval(&halves[0], u / t) } else { eval(&halves[1], (u - t) / (1.0 - t)) };
|
||||
assert!(dist(q, eval(&seg, u)) < 0.01, "t={t} u={u}");
|
||||
}
|
||||
assert_eq!(halves[2], curve().subpaths[0].segments()[1], "the next segment is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_to_a_straight_segment_makes_a_corner_on_the_line() {
|
||||
let mut p = tri();
|
||||
// The closing segment (2 → 0) wraps: the new anchor goes last.
|
||||
assert_eq!(add_anchor(&mut p, [0, 2], 0.5).unwrap(), [0, 3]);
|
||||
assert_eq!(at(&p, 0, 3), Knot::corner(25.0, 40.0));
|
||||
assert_eq!(add_anchor(&mut p, [0, 0], 0.25).unwrap(), [0, 1]);
|
||||
assert_eq!(at(&p, 0, 1), Knot::corner(25.0, 0.0));
|
||||
assert_eq!(p.subpaths[0].knots.len(), 5);
|
||||
assert!(p.subpaths[0].closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_joins_the_neighbours_with_their_handles() {
|
||||
let mut sq = Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])]);
|
||||
assert!(!delete_anchor(&mut sq, [0, 2]).unwrap());
|
||||
assert_eq!((sq.subpaths[0].knots.len(), sq.subpaths[0].closed), (3, true));
|
||||
let mut c = Path::new(vec![Subpath::polyline(&[(0.0, 50.0), (50.0, 0.0), (100.0, 50.0)])]);
|
||||
c.subpaths[0].knots[0].out_ctrl = Point::new(10.0, 20.0);
|
||||
c.subpaths[0].knots[2].in_ctrl = Point::new(90.0, 20.0);
|
||||
delete_anchor(&mut c, [0, 1]).unwrap();
|
||||
assert_eq!(c.subpaths[0].segments(), vec![[Point::new(0.0, 50.0), Point::new(10.0, 20.0), Point::new(90.0, 20.0), Point::new(100.0, 50.0)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_subpaths_last_anchor_removes_it_but_never_the_last_anchor() {
|
||||
let mut p = tri();
|
||||
p.subpaths.push(Subpath::polyline(&[(5.0, 5.0)]));
|
||||
assert!(delete_anchor(&mut p, [1, 0]).unwrap());
|
||||
assert_eq!(p, tri());
|
||||
let mut one = Path::new(vec![Subpath::polyline(&[(5.0, 5.0)])]);
|
||||
let before = one.clone();
|
||||
assert!(delete_anchor(&mut one, [0, 0]).is_err());
|
||||
assert_eq!(one, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_anchor_edits_are_errors_and_change_nothing() {
|
||||
let mut p = curve();
|
||||
for t in [0.0, 1.0, -0.5, 2.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(add_anchor(&mut p, [0, 0], t).is_err(), "t={t}");
|
||||
}
|
||||
assert!(add_anchor(&mut p, [0, 2], 0.5).is_err(), "an open subpath's last knot starts no segment");
|
||||
assert!(add_anchor(&mut p, [0, usize::MAX], 0.5).is_err());
|
||||
assert!(add_anchor(&mut p, [usize::MAX, 0], 0.5).is_err());
|
||||
assert!(delete_anchor(&mut p, [0, 3]).is_err());
|
||||
assert!(delete_anchor(&mut p, [1, 0]).is_err());
|
||||
assert_eq!(p, curve());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marquee_and_subpath_selections() {
|
||||
let p = tri();
|
||||
|
||||
+1
-1
@@ -171,7 +171,7 @@ cargo run -p photocraft-cli -- batch --actions actions.json --in photos/ --out d
|
||||
cargo run -p photocraft-cli -- commands --filter blur # the command registry
|
||||
```
|
||||
|
||||
`actions.json` holds the steps of a recorded action: `[["<id>", {…}], …]`, `[{"command": "<id>", "params": {…}}, …]` or bare ids, as a list or wrapped in `{"actions": …}` or `{"steps": …}`; a droplet file works too. `batch` refuses an `--out` folder that is the `--in` folder, since the results would replace the originals, unless `--in-place` is given. `run` prints one JSON line per command result.
|
||||
`actions.json` holds the steps of a recorded action: `[["<id>", {…}], …]`, `[{"command": "<id>", "params": {…}}, …]` or bare ids, as a list or wrapped in `{"actions": …}` or `{"steps": …}`; a droplet file works too. It can also be an Actions set (the Actions panel's `actions.json`, `{"actions": [{"name": …, "steps": […]}, …]}`): `--action <name>` picks the action to play (optional when the set holds one), and the whole set is loaded for each file, so a step that plays another action of the set works. `batch` refuses an `--out` folder that is the `--in` folder, since the results would replace the originals, unless `--in-place` is given. `run` prints one JSON line per command result.
|
||||
|
||||
## Native format (.pcraft)
|
||||
|
||||
|
||||
@@ -431,7 +431,7 @@ filled bar. This extends UI reachability and does not claim Photoshop-authored s
|
||||
| Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. |
|
||||
| Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. |
|
||||
| UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418). 2026-10-09: canvas zoom is physical at any display scale — 100% is one document pixel per physical display pixel, and every screen-space overlay, cursor, scrollbar, navigator and fit follows it (#1943) | low–medium | Needs recurring visual QA with realistic documents. |
|
||||
| Tools | 2026-10-10: Pencil, Mixer Brush, Color Replacement, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. Crop rotation (2026-10-09, #1792): dragging outside the crop frame turns it (⇧ 15° steps, angle readout), and ↵ rotates the document and crops in one undo step (`image.crop` `angle`); the frame turns over the image as in Photoshop's Classic Mode, and the options-bar Straighten is still missing. |
|
||||
| Tools | 2026-10-10: Pencil, Mixer Brush, Color Replacement, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. Crop rotation (2026-10-09, #1792): dragging outside the crop frame turns it (⇧ 15° steps, angle readout), and ↵ rotates the document and crops in one undo step (`image.crop` `angle`); the frame turns over the image as in Photoshop's Classic Mode, and the options-bar Straighten is still missing. |
|
||||
| Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Native Wayland pen input open (#79; a pen opens the window through Xwayland meanwhile); X11 pressure confirmed by a user, macOS not yet verified on tablet hardware. |
|
||||
| Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. |
|
||||
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |
|
||||
@@ -524,7 +524,7 @@ See [method and results](octagonal-mask-performance.md).
|
||||
effects, composite with masks and adjustment layers, CMYK print prep…) scripted end to end and
|
||||
checked against Photoshop's output on every build. Their pass rate becomes the headline parity
|
||||
number.
|
||||
4. **Tool coverage and workflow depth:** Pen variants (Direct Selection landed, #790) and
|
||||
4. **Tool coverage and workflow depth:** Pen variants (Direct Selection landed, #790; Add/Delete Anchor Point, #1044) and
|
||||
Perspective Crop; finish Content-Aware Move's Transform On Drop and live result preview.
|
||||
Pencil, Mixer Brush, Patch, Vertical Type, Pattern Stamp and Rotate View are already available on the toolbar.
|
||||
5. **Complex-document performance** (#125/#128) and GPU tiling beyond the texture limit (#49).
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
# UI parity: tools, handles, modifiers and feel
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (first version: tools, transform, nudging, snapping, modifiers, navigation, shortcuts, panels audited from source and open issues) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Crop resize stability, immediate ratio previews, and options-bar overflow regression coverage) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
|
||||
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
|
||||
@@ -129,6 +129,9 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
|
||||
|---|---|---|
|
||||
| Drag outside rotates (⇧ 15°), angle readout; ↵ rotates and crops in one undo step | done | TOOL-214-18 |
|
||||
| Straighten button and ⌘-drag line | done | TOOL-214-21 |
|
||||
| Default-mode resize snaps handles without camera feedback; image and frame use the same camera in each rendered frame | done | `crop_mode.rs::a_live_resize_snaps_the_handle_without_feedback_from_the_camera`, `tests/crop_default_mode.rs::a_resize_renders_the_frame_and_image_with_the_same_camera` (2026-10-10) |
|
||||
| Ratio presets and W × H changes immediately fit the current frame around its centre; Swap button and X share the fitted ratio, Enter needs no resize | done | `crop_ui.rs::choosing_a_ratio_fits_and_commits_without_a_resize`, `crop_size.rs::choosing_a_size_with_the_canvas_ratio_commits_without_a_resize`, `tests/crop_default_mode.rs` (2026-10-10) |
|
||||
| Roomy Crop options bar does not scroll; narrow tool bars retain horizontal scrolling | done | `panels.rs::a_wide_crop_options_bar_does_not_scroll`, `panels.rs::narrow_tool_options_can_scroll_to_the_last_control` (2026-10-10) |
|
||||
| Overlays (thirds, grid, diagonal, triangle, golden ratio/spiral), O / ⇧O | done | TOOL-214-20 |
|
||||
| Crop shield, Show Cropped Area (H) | done | TOOL-214-22 |
|
||||
| Default mode: the image turns and moves behind an upright box; Auto Center Preview; Use Classic Mode | done | TOOL-214-23 |
|
||||
@@ -204,3 +207,4 @@ Paragraph; the rest open as in-app floating windows.
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues |
|
||||
| 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions |
|
||||
Reference in new issue
Block a user