Split oversized functions and fix imports in photocraft crates

Moves code into named helpers (PSD export blocks, key-shortcut stages, options-bar
tool controls, liquify wheel handling, CAF options bar) without changing behaviour,
and restores imports left unfinished in the engine and UI crates. Clippy still
reports cognitive-complexity errors in ui-egui; those are being split next.
This commit is contained in:
Dylan M. Taylor committed 2026-10-27 21:43:48 +00:00
1 parent 4d95958a4c
commit 051ee2aff7
233 files changed
+3117 -2397

No files matched your search

+1 -1
View File
@@ -58,7 +58,7 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file,
- **Don't cascade.** Handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)`) and treat thread joins as `Result`s.
- **Last-resort guard.** The app shell must catch an escaped panic around command dispatch and file import/export, reports it as an error and keeps the document. It's a safety net, not a licence to panic. Keep `panic = "unwind"`.
- **Prove it.** Every crash fix comes with a small synthetic regression test that panicked before the fix.
- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic`/indexing in tests only. Clean production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`.
- **Enforced by clippy.** `clippy.toml` allows `unwrap`/`expect`/`panic` in tests only. Clean production crate roots carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; every new workspace crate must also include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`.
1. **Everything is a command.** New user-visible behaviour = a command in the engine (`crates/engine/src/*_cmds.rs`, registered in `commands.rs`) with id, label, menu path, shortcut, params doc, `enabled` and `run`, plus tests. The UI, CLI, control channel and MCP all dispatch commands by id. Use the **exact id from `crates/ui-egui/src/menu_catalog.rs`** and the menu item goes live automatically. Only pure view/window state (zoom, panels, screen mode) belongs to the shell (`menus.rs` `UI_COMMANDS`).
2. **No format or colour assumptions.** Bit depth (8/16/32f) and colour model (RGB/Gray/CMYK/Lab…) are runtime data. Never introduce a `u8`-only pixel path in public APIs. Never assume sRGB: colour conversions go through `photocraft-cms` (`Transform`, `transform::cached`). Test at several depths.
+5 -2
View File
@@ -1,7 +1,10 @@
//! Catalog metadata, strict tool envelopes and live resources.
use super::*;
use super::{Arc, Backend, BatchParams, DocIndex, ListParams, McpError, Parameters, PhotocraftMcp, RunParams, ServerHandler, Value, json};
use rmcp::RoleServer;
use rmcp::model::*;
use rmcp::model::{
CallToolRequestParams, CallToolResponse, Implementation, ListResourcesResult, ListToolsResult, PaginatedRequestParams, ReadResourceRequestParams,
ReadResourceResponse, ReadResourceResult, ServerCapabilities, ServerConfig, Tool, ToolAnnotations,
};
use rmcp::service::RequestContext;
const DOCUMENT: &str = "photocraft://document";
+1 -1
View File
@@ -1,5 +1,5 @@
//! Render Video runs on the existing blocking worker; rmcp remains available for ping/cancel.
use super::*;
use super::{CallToolResult, PhotocraftMcp, Value, fail, no_backend, ok_json};
use rmcp::RoleServer;
use rmcp::model::ProgressNotificationParam;
use rmcp::service::RequestContext;
+1 -1
View File
@@ -1,5 +1,5 @@
//! Recover malformed JSON lines before passing valid messages to rmcp.
use super::*;
use super::{AutomationError, PhotocraftMcp, ServiceExt, Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use crate::security::MAX_REQUEST_BYTES;
+4
View File
@@ -338,6 +338,10 @@ fn filesystem_commands_fail_closed() {
for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] {
assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}");
}
}
#[test]
fn filesystem_command_paths_and_profiles_fail_closed() {
// The UI-level examples in docs/control-protocol.md.
for id in ["view.zoomIn", "window.theme.pro", "edit.search"] {
assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}");
+1 -1
View File
@@ -2,7 +2,7 @@ use super::composite::{adjustment_quantum, blend_into, composite_stack};
use super::ctx::Ctx;
use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside};
use super::fx_cache::effect_maps;
use super::{Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern};
use super::{BlendMode, Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split};
/// Tile size for parallel rendering (tile results are independent).
pub const RENDER_TILE: i32 = 256;
+1 -1
View File
@@ -1,6 +1,6 @@
use super::content::{render_content, surface_to_buffer};
use super::ctx::Ctx;
use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, effects, masks};
use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, effects, masks, shape_split};
/// Bounds of a layer's own pixels (union over group children; the canvas
/// for fill layers; an artboard's board).
+8
View File
@@ -63,6 +63,11 @@ fn every_kind_round_trips_through_params() {
#[test]
fn params_reach_the_model() {
basic_params_reach_the_model();
color_space_params_reach_the_model();
}
fn basic_params_reach_the_model() {
let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap();
assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true });
let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap();
@@ -82,6 +87,9 @@ fn params_reach_the_model() {
assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, hue: 120.0, .. }), "{a:?}");
let a = from_params("gradientMap", &json!({"stops": [[1, "#ffffff"], [0, "#000000"]], "dither": true}), None, ColorMode::Rgb).unwrap();
assert!(matches!(&a, Adjustment::GradientMap { stops, dither: true, .. } if stops[0].0 == 0.0));
}
fn color_space_params_reach_the_model() {
// CMYK curves: ink channels; Lab: lightness without a composite.
let a = from_params("curves", &json!({"black": [[0, 0], [255, 200]]}), None, ColorMode::Rgb).unwrap();
assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Cmyk, black, .. } if black.len() == 2));
+1 -1
View File
@@ -1,6 +1,6 @@
use super::enabled::{check_all_unlocked, is_mask_target, paint_surface};
use super::layer_params::{layer_param, mask_new_layer};
use super::*;
use super::{Adjustment, ColorMode, EngineError, Layer, LayerContent, Map, Result, Session, Value, json, pixels};
/// Add an adjustment layer above the active one; it takes the mask `mask_new_layer` builds from `p` (a path, the selection, or the default white mask).
pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result<Value> {
@@ -1,7 +1,7 @@
use super::descriptors::{color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, jbool, jnum, jstr, long, num, pct, text};
use super::fields::{F, Kind, Mapped, fields_from, fields_to, step};
use super::tables::{CHANNELS, channel_key, channel_ref, lookup, lookup_back};
use super::*;
use super::{D, Descriptor, Map, Value, json};
// ------------------------------------------------------------------ adjustments
+1 -1
View File
@@ -1,7 +1,7 @@
use super::descriptors::{desc, get_obj, jstr};
use super::events::{event_and_descriptor, event_for};
use super::fields::Mapped;
use super::*;
use super::{Action, AtnAction, AtnEvent, AtnFile, AtnItem, D, DEFAULT_SET, Descriptor, PHOTOSHOP_STEP, UnicodeString, Value, atn, json};
// ------------------------------------------------------------------ import
@@ -1,4 +1,4 @@
use super::*;
use super::{Class, D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json};
// ------------------------------------------------------------------ descriptor access
+1 -1
View File
@@ -16,7 +16,7 @@ use super::steps_layer::{
};
use super::steps_make::{make_from, make_to, set_from, set_to};
use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM};
use super::*;
use super::{AtnEvent, D, Descriptor, STOP_MESSAGE, Value, json};
/// An event: code (empty when Photoshop only has a string name), string name, the panel
/// label, the command ids it exports (the first is the one simple events import to), and the
+1 -1
View File
@@ -1,6 +1,6 @@
use super::descriptors::{ang, color_desc, color_hex, enm, get_bool, get_enum, get_num, get_obj, long, pct, px};
use super::tables::{blend_label, blend_ps, lookup, lookup_back};
use super::*;
use super::{D, Descriptor, Map, Value, json};
// ------------------------------------------------------------------ field tables
+1 -1
View File
@@ -1,5 +1,5 @@
use super::convert::{UniqueNames, export, import};
use super::*;
use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json};
pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "actions.load";
+1 -1
View File
@@ -5,7 +5,7 @@ use super::descriptors::{
};
use super::fields::{Mapped, none, step, steps};
use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back};
use super::*;
use super::{D, Descriptor, Id, Map, ReferenceItem, STOP_MESSAGE, UnicodeString, Value, json};
/// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale.
pub(super) fn place_from(d: &Descriptor) -> Mapped {
@@ -5,7 +5,7 @@ use super::descriptors::{
use super::events::pixel_target;
use super::fields::{F, Kind, Mapped, fields_from, fields_to, step};
use super::tables::{CHANNELS, INTERPOLATION, RADIAL_METHOD, RADIAL_QUALITY, channel_of, lookup, lookup_back};
use super::*;
use super::{D, Descriptor, Map, ReferenceItem, UnicodeString, Value, json};
/// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre,
/// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything
@@ -7,7 +7,7 @@ use super::events::pixel_target;
use super::fields::{F, Kind, Mapped, fields_to, none, step, steps};
use super::steps_make::is_tool_class;
use super::tables::{FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, lookup, lookup_back};
use super::*;
use super::{D, Descriptor, Id, Map, ReferenceItem, UnicodeString, Value, json};
pub(super) fn select_from(d: &Descriptor) -> Mapped {
let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } };
+161 -144
View File
@@ -6,7 +6,7 @@ use super::descriptors::{
use super::fields::{Mapped, none, step, steps};
use super::steps_layer::quick_mask_ref;
use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_back};
use super::*;
use super::{D, Descriptor, Id, Map, ReferenceItem, Value, json};
/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of
/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ
@@ -59,82 +59,92 @@ const MASK_USING: &[(&str, &str)] = &[
("HdSl", "layer.layerMask.hideSelection"),
];
fn duplicate_layer_from_descriptor(d: &Descriptor) -> Option<Mapped> {
let r = get_ref(d, "null")?;
if ref_class(r).as_deref() != Some("Dcmn") || !matches!(target(r), Target::Class) {
return None;
}
let u = get_ref(d, "Usng")?;
if !matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) {
return None;
}
let mut params = layer_target(u)?;
params.insert("document".into(), "new".into());
if let Some(n) = get_text(d, "Nm ") {
params.insert("documentName".into(), n.into());
}
if let Some(n) = get_text(d, "LyrN") {
params.insert("name".into(), n.into());
}
Some(step("layer.duplicate", Value::Object(params)))
}
fn mask_from_descriptor(d: &Descriptor) -> Option<Mapped> {
let Some(D::Class(c)) = d.get("Nw ") else { return None };
if trimmed(&c.class_id) != "Chnl" {
return None;
}
let at_mask =
get_ref(d, "At ").is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk"));
Some(match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) {
Some(id) if at_mask => none(id),
_ => Mapped::Unsupported { harmless: false },
})
}
fn new_document_from_descriptor(d: &Descriptor) -> Option<Mapped> {
let nw = get_obj(d, "Nw ")?;
if get_enum(d, "Usng").as_deref() == Some("Slct") {
let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" };
let mut mapped_steps = vec![(id, json!({}))];
if let Some(n) = get_text(nw, "Nm ") {
mapped_steps.push(("layer.setProps", json!({"name": n})));
}
return Some(steps(mapped_steps));
}
if get_text(nw, "preset").is_some() {
return Some(none("file.newFromClipboard"));
}
let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) else {
return Some(Mapped::Unsupported { harmless: false });
};
let res = get_num(nw, "Rslt").unwrap_or(72.0);
let to_px = |key: &str, value: f64| match nw.get(key) {
Some(D::UnitFloat { unit: PX, .. }) => value,
_ => value * res / 72.0,
};
let mut params = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res});
if let Some(n) = get_text(nw, "Nm ") {
params["name"] = json!(n);
}
if let Some(D::Class(c)) = nw.get("Md ")
&& let Some(m) = lookup(MODES, &trimmed(&c.class_id))
{
params["mode"] = json!(m);
}
if let Some(depth) = get_num(nw, "Dpth") {
params["depth"] = json!(depth);
}
if let Some(fill) = get_enum(nw, "Fl ") {
params["background"] = json!(match fill.as_str() {
"Wht" => "white",
"BckC" => "backgroundColor",
"Trns" => "transparent",
_ => "white",
});
}
Some(step("file.new", params))
}
pub(super) fn make_from(d: &Descriptor) -> Mapped {
// Duplicate layer/group into a new document: `Mk` with a document class, a layer
// `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN`
// (the copy's name). A `Dplc` with a `T` document reference (duplicate into another
// open document) stays a kept Photoshop step: document indices mean nothing at replay.
if let Some(r) = get_ref(d, "null")
&& ref_class(r).as_deref() == Some("Dcmn")
&& matches!(target(r), Target::Class)
&& let Some(u) = get_ref(d, "Usng")
&& matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection"))
&& let Some(mut p) = layer_target(u)
{
p.insert("document".into(), "new".into());
if let Some(n) = get_text(d, "Nm ") {
p.insert("documentName".into(), n.into());
}
if let Some(n) = get_text(d, "LyrN") {
p.insert("name".into(), n.into());
}
return step("layer.duplicate", Value::Object(p));
if let Some(mapped) = duplicate_layer_from_descriptor(d) {
return mapped;
}
// Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals.
if let Some(D::Class(c)) = d.get("Nw ")
&& trimmed(&c.class_id) == "Chnl"
{
// The target layer's mask only: a further item (a `Lyr` by name…) puts it on another layer.
let at_mask = get_ref(d, "At ")
.is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk"));
return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) {
Some(id) if at_mask => none(id),
_ => Mapped::Unsupported { harmless: false },
};
if let Some(mapped) = mask_from_descriptor(d) {
return mapped;
}
if let Some(nw) = get_obj(d, "Nw ") {
// Layer via Copy / Cut (`Usng` = the selection), or a new document.
if get_enum(d, "Usng").as_deref() == Some("Slct") {
let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" };
let mut v = vec![(id, json!({}))];
if let Some(n) = get_text(nw, "Nm ") {
v.push(("layer.setProps", json!({"name": n})));
}
return steps(v);
}
if get_text(nw, "preset").is_some() {
return none("file.newFromClipboard");
}
if let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) {
let res = get_num(nw, "Rslt").unwrap_or(72.0);
// Dimensions are in points (`#Rlt`) unless given in pixels.
let to_px = |k: &str, v: f64| match nw.get(k) {
Some(D::UnitFloat { unit: PX, .. }) => v,
_ => v * res / 72.0,
};
let mut p = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res});
if let Some(n) = get_text(nw, "Nm ") {
p["name"] = json!(n);
}
if let Some(D::Class(c)) = nw.get("Md ")
&& let Some(m) = lookup(MODES, &trimmed(&c.class_id))
{
p["mode"] = json!(m);
}
if let Some(depth) = get_num(nw, "Dpth") {
p["depth"] = json!(depth);
}
if let Some(f) = get_enum(nw, "Fl ") {
p["background"] = json!(match f.as_str() {
"Wht" => "white",
"BckC" => "backgroundColor",
"Trns" => "transparent",
_ => "white",
});
}
return step("file.new", p);
}
return Mapped::Unsupported { harmless: false };
if let Some(mapped) = new_document_from_descriptor(d) {
return mapped;
}
let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } };
let using = get_obj(d, "Usng");
@@ -316,84 +326,91 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
})
}
fn selection_from(d: &Descriptor) -> Mapped {
let unsupported = Mapped::Unsupported { harmless: false };
match d.get("T ") {
Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() {
"Al" => none("select.all"),
"None" => none("select.deselect"),
"Prvs" => none("select.reselect"),
_ => unsupported,
},
Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) {
(Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})),
// ⌘-click on the targeted channel (a layer mask after `select` of `Msk`).
(Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})),
(Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})),
_ => unsupported,
},
Some(D::Descriptor(t)) if t.class_id.is("Plgn") => {
let pts: Option<Vec<Value>> = get_list(t, "Pts ")
.unwrap_or(&[])
.iter()
.map(|v| match v {
D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])),
_ => None,
})
.collect();
match pts {
Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})),
_ => unsupported,
}
}
Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => {
let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) else {
return unsupported;
};
let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)});
if t.class_id.is("Elps") {
p["ellipse"] = json!(true);
}
step("select.rect", p)
}
_ => unsupported,
}
}
fn background_from(d: &Descriptor) -> Mapped {
let unsupported = Mapped::Unsupported { harmless: false };
// On an image that opened as a normal layer there is no Background to convert;
// Photoshop stops there, but the step's purpose (an editable layer) is met.
// Photoshop's `set` of another layer doesn't target it: the selected layer stays.
let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))];
let mut props = Map::new();
props.insert("layer".into(), "Layer 0".into());
if let Some(t) = get_obj(d, "T ") {
if let Some(n) = get_text(t, "Nm ") {
props.insert("name".into(), n.into());
}
if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) {
props.insert("opacity".into(), (o / 100.0).into());
}
match get_enum(t, "Md ").as_deref() {
None | Some("Nrml") => {}
Some(m) => match blend_label(m) {
Some(label) => {
props.insert("blend".into(), label.into());
}
None => return unsupported,
},
}
}
if props.len() > 1 {
v.push(("layer.setProps", Value::Object(props)));
}
steps(v)
}
pub(super) fn set_from(d: &Descriptor) -> Mapped {
let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } };
let unsupported = Mapped::Unsupported { harmless: false };
match (ref_class(r).as_deref(), target(r)) {
(Some("Chnl"), Target::Property(p)) if p == "fsel" => match d.get("T ") {
Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() {
"Al" => none("select.all"),
"None" => none("select.deselect"),
"Prvs" => none("select.reselect"),
_ => unsupported,
},
Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) {
(Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})),
// ⌘-click on the targeted channel (a layer mask after `select` of `Msk`).
(Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})),
(Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})),
_ => unsupported,
},
Some(D::Descriptor(t)) if t.class_id.is("Plgn") => {
let pts: Option<Vec<Value>> = get_list(t, "Pts ")
.unwrap_or(&[])
.iter()
.map(|v| match v {
D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])),
_ => None,
})
.collect();
match pts {
Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})),
_ => unsupported,
}
}
Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => {
let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght"))
else {
return unsupported;
};
let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)});
if t.class_id.is("Elps") {
p["ellipse"] = json!(true);
}
step("select.rect", p)
}
_ => unsupported,
},
(Some("Chnl"), Target::Property(p)) if p == "fsel" => selection_from(d),
// Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off.
(Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})),
// Layer › New › Layer From Background (Photoshop records the New Layer dialog's values
// as a `set` of the Background); values other than the defaults then apply to the layer.
(Some("Lyr"), Target::Property(p)) if p == "Bckg" => {
// On an image that opened as a normal layer there is no Background to convert;
// Photoshop stops there, but the step's purpose (an editable layer) is met.
// Photoshop's `set` of another layer doesn't target it: the selected layer stays.
let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))];
let mut props = Map::new();
props.insert("layer".into(), "Layer 0".into());
if let Some(t) = get_obj(d, "T ") {
if let Some(n) = get_text(t, "Nm ") {
props.insert("name".into(), n.into());
}
if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) {
props.insert("opacity".into(), (o / 100.0).into());
}
match get_enum(t, "Md ").as_deref() {
None | Some("Nrml") => {}
Some(m) => match blend_label(m) {
Some(label) => {
props.insert("blend".into(), label.into());
}
None => return unsupported,
},
}
}
if props.len() > 1 {
v.push(("layer.setProps", Value::Object(props)));
}
steps(v)
}
(Some("Lyr"), Target::Property(p)) if p == "Bckg" => background_from(d),
// The toolbox colours.
(Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) {
Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})),
+1 -1
View File
@@ -1,5 +1,5 @@
use super::descriptors::{Target, class, code, get_ref, target};
use super::*;
use super::{D, Descriptor, ReferenceItem};
/// Photoshop's `BlnM` enumeration ↔ PhotoCraft's blend mode labels.
const BLEND_MODES: &[(&str, &str)] = &[
@@ -1,6 +1,9 @@
//! Incremental Mixer Brush transaction. Source pixels are composed before each dab;
//! only the selected target changes. Dropping the transaction cancels it.
use super::*;
use super::{
EngineError, LiveCommit, MixerSettings, Rect, Result, Session, Stroke, StrokePoint, Surface, Value, bad, check_coords, color, damage_json, doc_cmyk_space,
flag, has_paintable, json, layer_id, num, parse_points, pct, resolve_brush,
};
use photocraft_color::{PixelFormat, SampleType};
use photocraft_doc::{Document, LayerId};
use photocraft_paint::dynamics::DabGenerator;
+1 -1
View File
@@ -2,7 +2,7 @@ use super::manage::gray_document;
use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, read_plane, tone};
use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec};
use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface};
use super::*;
use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel};
// ---------------------------------------------------------------------------------------------
// Apply Image / Calculations
+3 -1
View File
@@ -3,7 +3,9 @@ use super::refs::{ChanRef, alpha_index, bad, doc_index, gray_plane, parse_ref};
use super::selection::{uniform, unselected_surface};
use super::targeting::target;
use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, touch};
use super::*;
use super::{
AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, EngineError, Layer, PixelFormat, Result, Session, Surface, Value, json, list, sel,
};
// ---------------------------------------------------------------------------------------------
// Channel management
+1 -1
View File
@@ -1,5 +1,5 @@
use super::view::{ChannelTarget, color_names};
use super::*;
use super::{ColorMode, DocState, Document, PixelFormat, Rect, Surface};
/// The Curves dialog's Channel popup lists only this channel when the Channels panel has a
/// single non-composite target (a colour component, layer mask, saved channel or Quick Mask).
+1 -1
View File
@@ -1,6 +1,6 @@
use super::planes::{color_count, edit_mode, luminosity, read_plane, tone};
use super::view::{color_names, composite_name};
use super::*;
use super::{BlendMode, Document, EngineError, LayerContent, LayerId, Result, Session, Value, blend_channel, from_rgba, sel, to_rgba};
// ---------------------------------------------------------------------------------------------
// Channel references
@@ -1,7 +1,7 @@
use super::planes::{channel_format, next_alpha_name, plane_surface, read_plane};
use super::refs::{ChanRef, bad, doc_index, parse_ref, source};
use super::view::{ChannelTarget, QuickMaskOptions};
use super::*;
use super::{AlphaChannel, ColorIndicates, Document, EngineError, PixelFormat, Rect, Result, SelectionMode, Session, Surface, Value, json, operation, sel};
pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "select.saveSelection";
+1 -1
View File
@@ -2,7 +2,7 @@ use super::manage::{fix_view_now, gray_document};
use super::planes::{channel_format, edit_mode, plane_surface, read_plane, tone};
use super::refs::{ChanRef, alpha_index, bad, gray_plane, native_pixels};
use super::view::{ChannelTarget, ChannelView, color_names};
use super::*;
use super::{AlphaChannel, ColorMode, DocState, Document, EngineError, Layer, Result, Session, Value, from_rgba, json};
/// Merge Spot Channel: flattens the image and prints the spot ink into the colour channels.
pub(super) fn merge_spot(s: &mut Session, p: &Value) -> Result<Value> {
@@ -2,7 +2,7 @@ use super::manage::fix_view_now;
use super::planes::{color_count, materialize};
use super::refs::{ChanRef, bad, parse_ref};
use super::view::ChannelTarget;
use super::*;
use super::{ColorMode, Document, EngineError, Layer, LayerId, Rect, Result, Session, Surface, TileCoord, Value, from_rgba, json, list};
// ---------------------------------------------------------------------------------------------
// Targets for pixel commands
+1 -1
View File
@@ -1,5 +1,5 @@
use super::planes::color_count;
use super::*;
use super::{AlphaChannel, Color, ColorIndicates, ColorMode, DocState, Document, Serialize};
// ---------------------------------------------------------------------------------------------
// View state
@@ -1,4 +1,7 @@
use super::*;
use super::{
Document, EngineError, Layer, LayerId, PixelFormat, Rect, Result, Session, Surface, Value, bad, bool_or, from_rgba_into, int, json, pixel_layer,
pixel_layer_id, str_or, to_rgba, writable_surface,
};
// ------------------------------------------------------------------ Content-Aware Fill
@@ -1,5 +1,7 @@
use super::content_aware::channel_mask;
use super::*;
use super::{
Document, EngineError, LayerId, PixelFormat, Rect, Result, Session, Surface, Value, bad, bool_or, f32_or, json, pixel_layer, to_rgba, writable_surface,
};
// ------------------------------------------------------------------ Content-Aware Scale
+4 -1
View File
@@ -1,4 +1,7 @@
use super::*;
use super::{
BlendMode, EngineError, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, surface_of,
surface_of_mut, to_rgba,
};
// ------------------------------------------------------------------ Fade
@@ -1,4 +1,4 @@
use super::*;
use super::{Document, EngineError, LayerContent, LayerId, Result, Session, Value, bad, bool_or, json, layer_param, str_or};
// ------------------------------------------------------------------ Find and Replace Text
@@ -1,4 +1,4 @@
use super::*;
use super::{CustomShape, Deserialize, Document, EngineError, LayerContent, LayerId, Path, Result, Serialize, Session, Value, bad, json, str_or};
// ------------------------------------------------------------------ Define Brush / Custom Shape
@@ -1,4 +1,4 @@
use super::*;
use super::{Result, Session, Value, json};
// ------------------------------------------------------------------ Purge
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{Document, EngineError, LayerContent, LayerId, Result, Session, Value};
pub(crate) fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
+1 -1
View File
@@ -2,7 +2,7 @@ use super::open::import_at_raw_ppi;
use super::paths::{extension, file_name, join, list_images, read_file, stem};
use super::processing::parse_steps;
use super::save::{SaveOpts, save_doc};
use super::*;
use super::{Arc, Document, EngineError, Result, Session, Value, batch_naming, json, str_param};
/// Inputs of a batch command: `"input"` is a folder or an array of files.
pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
+1 -1
View File
@@ -1,6 +1,6 @@
use super::paths::{join, sanitize, stem, write_file};
use super::save::{SaveOpts, encode};
use super::*;
use super::{ColorMode, Document, EngineError, Layer, LayerContent, LayerId, Rect, Result, Session, Surface, Value, from_rgba_into, json, str_param};
// ---------- Export ----------
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{EngineError, Result, Session, Value, json};
// ---------- File Info (XMP) ----------
+4 -1
View File
@@ -1,5 +1,8 @@
use super::paths::{file_name, read_file, stem, template_name};
use super::*;
use super::{
Affine, Arc, Document, EngineError, Layer, LayerContent, Resample, Result, Session, SmartObject, SmartSource, Value, f64_param, flattened_checked, json,
resize_surface, str_param, translate_surface,
};
pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
import_result(name, bytes).map(|r| r.document)
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{EngineError, Result, Session};
// ---------- file system (native only) ----------
@@ -2,7 +2,10 @@ use super::batch_run::{batch_inputs_tree, process_tree};
use super::open::import_opened;
use super::paths::{file_name, list_images, read_file, stem};
use super::save::SaveOpts;
use super::*;
use super::{
ColorMode, Document, EngineError, Layer, LayerContent, LayerId, Result, Session, Surface, Value, buffer_surface, flattened_checked, json, size_param,
str_param,
};
// ---------- Automate ----------
+1 -1
View File
@@ -1,5 +1,5 @@
use super::paths::{same_file, write_file};
use super::*;
use super::{Document, EngineError, Layer, LayerContent, Result, Session, Value, f64_param, flattened_checked, json, str_param};
/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone
/// Background layer). The UI asks before such a save when the "ask before saving layered TIFF"
@@ -1,7 +1,7 @@
use super::damage::layer_bounds;
use super::moves::{move_layers, with_links};
use super::selection::{selected, top_level};
use super::*;
use super::{Document, EngineError, LayerId, Rect, Result, Session, Value, bad, json};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Edge {
@@ -1,4 +1,4 @@
use super::*;
use super::{Document, Layer, LayerContent, LayerId, Rect, Session, VideoData};
/// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents
/// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere.
@@ -1,7 +1,7 @@
use super::damage::note_damage;
use super::selection::{reselect, same_named_targets, selected, top_level};
use super::structure::check_group_depth;
use super::*;
use super::{Document, EngineError, Layer, LayerContent, LayerId, Result, Session, Value, bad, int_i32, json};
/// A Layers-panel drag of the selected layer records its drop target by name (and which of
/// several same-named layers it is), as [`recorded_selection`] does: the id means nothing in the
@@ -1,5 +1,5 @@
use super::moves::{link_groups, recorded_move};
use super::*;
use super::{DocState, Document, EngineError, Layer, LayerContent, LayerId, Rect, Result, Session, Value, bad, json};
// ---------- selection state ----------
@@ -1,5 +1,5 @@
use super::selection::{reselect, selected, top_level};
use super::*;
use super::{Document, EngineError, Layer, LayerContent, LayerId, PixelFormat, Result, Session, Value, bad, json};
// ---------- structural commands ----------
+1 -1
View File
@@ -1,5 +1,5 @@
use super::params::bad;
use super::*;
use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value};
/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that
/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays
+1 -1
View File
@@ -1,6 +1,6 @@
use super::enabled::check_all_unlocked;
use super::layer_params::{layer_param, mask_at_depth};
use super::*;
use super::{Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, json, pixels};
pub(super) fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result<Value> {
let id = layer_param(s, p)?;
+1 -1
View File
@@ -1,5 +1,5 @@
use super::layer_params::layer_param;
use super::*;
use super::{EngineError, LayerId, Result, Session, Value, json};
// ---------- param helpers ----------
@@ -7,7 +7,7 @@ use photocraft_paint::MAX_BRUSH_SIZE;
use photocraft_paint::retouch::{Region, alpha_index};
use serde_json::{Value, json};
use super::*;
use super::{EngineError, Result, Session, bad, blend_param, damage_json, parse_brush, run_stroke};
const CMD: &str = "paint.artHistoryBrush";
const MAX_POINTS: usize = 4096;
+5 -1
View File
@@ -1,6 +1,10 @@
use super::heal::history_source;
use super::sampling::{SampleLayers, sample, sample_layers};
use super::*;
use super::{
BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value,
alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point,
reject_huge_stroke, run_stroke, to_rgba,
};
/// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot,
/// with the slot's (or the call's) scale, rotation and flips (see `presets::clone_source`).
@@ -34,7 +34,10 @@ use photocraft_algo::content_aware::{FillOptions, color_amount, color_level, fil
use photocraft_algo::transform::{Homography, Interp};
use super::patch::{coverage, offset, selection_area, target_layer};
use super::*;
use super::{
Document, EngineError, LayerContent, LayerId, Rect, Region, Result, SampleLayers, Session, Surface, Value, alpha_index, bad, clamp_samples,
composite_region, damage_json, flag, has_pixel_layer, json, string, targets_pixels,
};
const CMD: &str = "paint.contentAwareMove";
+5 -1
View File
@@ -1,5 +1,9 @@
use super::sampling::{AllLayers, sample_all_layers};
use super::*;
use super::{
BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect, Region, Result,
Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, from_rgba_into,
has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba,
};
// ---------------------------------------------------------------------------------------------
// Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge
+4 -1
View File
@@ -1,6 +1,9 @@
use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample};
use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers};
use super::*;
use super::{
BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad,
coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string,
};
/// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve).
fn pad_coverage(bounds: Rect, cov: &[f32], m: i32) -> (Rect, Vec<f32>) {
+4 -1
View File
@@ -17,7 +17,10 @@
//! (3: 32 of 42 levels, 31 of 102; 10: 35 of 42, 95 of 102). It runs as a background job, like
//! the move.
use super::*;
use super::{
BlendMode, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Surface, Value, apply_coverage, bad, clamp_samples, damage_json,
flag, has_pixel_layer, heal_region, json, point, poisson, run_stroke, string, targets_pixels,
};
const CMD: &str = "paint.patch";
@@ -1,6 +1,6 @@
//! Bounded reads from the repeating document tile used by Pattern Preview.
use super::*;
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, StrokePoint, Surface, alpha_index, apply_coverage, bad};
/// At most four disjoint rectangles in the document tile. Projecting the dirty area separately
/// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam.
+4 -1
View File
@@ -16,7 +16,10 @@
use super::content_aware_move::{Target, replace};
use super::patch::coverage;
use super::*;
use super::{
Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleLayers, Session, Stroke, Surface, Value, alpha_index, bad, clamp_samples,
composite_region, damage_json, flag, json, parse_brush, reject_huge_stroke, targets_pixels,
};
use photocraft_doc::Layer;
const CMD: &str = "paint.remove";
@@ -1,4 +1,4 @@
use super::*;
use super::{Document, Footprint, LayerId, PixelFormat, Rect, Region, Result, Surface, Value, bad, flag, from_rgba_into, string, targets_pixels};
// ---------------------------------------------------------------------------------------------
// Sampling sources
+4 -1
View File
@@ -2,7 +2,10 @@ use super::filters::{smart, smart_mut};
use super::placing::detach_psd;
use super::rendering::{refresh, refresh_or_fail, unapplied_filters};
use super::source::{authorized_source_bytes, source_bytes};
use super::*;
use super::{
Arc, DocId, Document, EngineError, LayerContent, LayerId, Metadata, Result, Session, SmartContentsId, SmartLink, SmartSource, Value, bad, base_name,
decode_source, encode_source, json, layer_param, other,
};
pub(super) fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> {
p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "pass `path`"))
+4 -1
View File
@@ -1,6 +1,9 @@
use super::rendering::{refresh_or_fail, refresh_or_fail_in};
use super::source::source_bytes;
use super::*;
use super::{
BlendMode, Document, EngineError, Layer, LayerContent, LayerId, LayerMask, Result, Session, SmartObject, Surface, Value, bad, blend_from_str, json,
layer_param, other,
};
pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> {
match &doc.layer(id).ok_or(EngineError::NoLayer(id))?.content {
+4 -1
View File
@@ -1,5 +1,8 @@
use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes};
use super::*;
use super::{
Affine, Arc, BlendMode, Document, EngineError, Homography, Layer, LayerContent, LayerId, PLACED_KEYS, Rect, Result, Session, Size, SmartContentsId,
SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, translate_surface,
};
/// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so
/// repeated transforms land back on exact, lossless placements.
@@ -1,6 +1,9 @@
use super::filters::smart;
use super::source::{SourceImage, cache_get, cache_key, cache_put, source_bytes, source_image, source_surface, svg_source_image, vector_scale};
use super::*;
use super::{
Affine, Arc, BlendMode, Document, EngineError, Homography, JobCtx, Layer, LayerContent, LayerId, PixelFormat, Rect, Result, SmartFilter, SmartObject,
SmartSource, Stage, StageKey, Surface, Value, decode_source, other, stack_cache,
};
/// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the
/// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode.
+4 -1
View File
@@ -1,4 +1,7 @@
use super::*;
use super::{
Arc, ColorMode, Document, Layer, LayerContent, LayerId, Metadata, Mutex, PixelFormat, Rect, Result, SampleType, Session, SmartObject, SmartSource, Surface,
base_name, decode_source, json, other,
};
/// A linked file's bytes; `None` when it is missing or its path is not followed
/// ([`crate::doc_path::resolve`]).
+19
View File
@@ -320,6 +320,13 @@ mod tests {
#[test]
fn navigate_words_lines_edges_and_keeps_a_column() {
check_word_moves();
check_newline_moves();
check_vertical_column_moves();
check_navigation_queries_are_read_only();
}
fn check_word_moves() {
let mut s = session();
let id = create(&mut s, json!({"x": 20, "y": 60, "text": "hello big world", "size": 18}));
assert_eq!(go(&mut s, id, 0, "wordNext", None), 5);
@@ -334,7 +341,10 @@ mod tests {
assert_eq!(go(&mut s, id, 4, "end", None), 15);
assert_eq!(go(&mut s, id, 4, "lineStart", None), 0);
assert_eq!(go(&mut s, id, 4, "lineEnd", None), 15);
}
fn check_newline_moves() {
let mut s = session();
// A newline is not part of either word; line edges agree with type.info.
let id = create(&mut s, json!({"x": 20, "y": 120, "text": "hello\nworld", "size": 18}));
assert_eq!(go(&mut s, id, 0, "wordNext", None), 5);
@@ -353,7 +363,10 @@ mod tests {
assert!((l1s..=l1e).contains(&next), "lineNext {next} not on {l1s}..={l1e}");
assert_eq!(go(&mut s, id, 0, "linePrev", None), 0);
assert_eq!(go(&mut s, id, l1e as usize, "lineNext", None), "hello\nworld".chars().count() as u64);
}
fn check_vertical_column_moves() {
let mut s = session();
// Repeated line moves keep the document x of the original column.
let id = create(&mut s, json!({"x": 24, "y": 200, "text": "WWWWWW\nI", "size": 28}));
let info = s.execute("type.info", json!({"layer": id})).unwrap();
@@ -366,7 +379,13 @@ mod tests {
assert_eq!(go(&mut s, id, end0 as usize, "lineNext", Some(x)), start1);
assert_eq!(go(&mut s, id, end0 as usize, "lineNext", None), end1);
assert_eq!(go(&mut s, id, start1 as usize, "linePrev", Some(x)), lines[0]["start"].as_u64().unwrap());
}
fn check_navigation_queries_are_read_only() {
let mut s = session();
let id = create(&mut s, json!({"x": 24, "y": 200, "text": "WWWWWW\nI", "size": 28}));
let caret0 = s.execute("type.caret", json!({"layer": id, "index": 0})).unwrap();
let x = caret0["segment"][0][0].as_f64().unwrap();
// Queries do not record history or a journal entry.
let steps = s.active().unwrap().history.entries().len();
let rev = s.active().unwrap().revision;
+19
View File
@@ -244,6 +244,13 @@ fn step_char_metrics(t: &mut TextLayer, a: usize, b: usize, p: &Value) -> bool {
/// Applies character-style keys from JSON. Returns true if any key was present.
pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool {
let mut any = apply_font_props(s, p);
any |= apply_char_values(s, p);
any |= apply_char_features(s, p);
any
}
fn apply_font_props(s: &mut CharStyle, p: &Value) -> bool {
let mut any = false;
let mut hit = |b: bool| any |= b;
let font_key = ["font", "family", "fontStyle", "weight", "italic"].iter().any(|k| p.get(k).is_some());
@@ -309,6 +316,12 @@ pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool {
if font_key && s.postscript_name.is_none() {
s.postscript_name = installed_postscript(&s.font_family, s.weight, s.italic);
}
any
}
fn apply_char_values(s: &mut CharStyle, p: &Value) -> bool {
let mut any = false;
let mut hit = |b: bool| any |= b;
if let Some(v) = f32p(p, "size") {
s.size_pt = v.max(0.01);
hit(true);
@@ -396,6 +409,12 @@ pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool {
hit(true);
}
}
any
}
fn apply_char_features(s: &mut CharStyle, p: &Value) -> bool {
let mut any = false;
let mut hit = |b: bool| any |= b;
if let Some(Value::Object(m)) = p.get("features") {
for (tag, v) in m {
let value = v.as_u64().map(|x| x as u16).or_else(|| v.as_bool().map(u16::from)).unwrap_or(1);
+4 -1
View File
@@ -1,4 +1,7 @@
use super::*;
use super::{
Color, EngineError, Fill, FillRule, GradientStyle, Knot, LayerId, LineCap, LineJoin, LiveShape, Path, PathOp, Point, Result, Session, ShapeStroke,
StrokeAlign, Subpath, Value, bad, json,
};
pub(crate) fn layer_id(s: &Session, p: &Value) -> Result<LayerId> {
match p.get("layer").and_then(Value::as_u64) {
+4 -1
View File
@@ -1,6 +1,9 @@
use super::params::{color, f64p, layer_id, op_from, parse_path, path_json};
use super::shape::{map_path, map_shape, transform_shape, with_shape};
use super::*;
use super::{
Affine, BlendMode, ClippingPath, Color, Document, EngineError, LayerContent, LayerId, NamedPath, Path, Rect, Result, SelectionMode, Session, Value, bad,
blend_from_str, json, sel, vector,
};
// ---------------------------------------------------------------------------
// Document paths
+4 -1
View File
@@ -2,7 +2,10 @@ use super::params::{
f64p, fill_json, layer_id, live_from_params, live_json, nums, op_from, parse_fill, parse_path, parse_stroke, path_json, radii, stroke_json,
};
use super::vector_mask::with;
use super::*;
use super::{
Affine, Color, Document, EngineError, Fill, FillRule, Layer, LayerContent, LayerId, LiveShape, Path, PathOp, Point, Result, SHAPE_BLOCKS, Session,
ShapeLayer, Value, bad, json, sel, vector,
};
fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> {
let d = s.active().ok_or("no document open")?;
@@ -1,7 +1,7 @@
use super::params::{layer_id, parse_path, path_json};
use super::paths::{is_work, resolve_path};
use super::shape::with_shape;
use super::*;
use super::{EngineError, LayerContent, LayerId, Path, Result, Session, Value, VectorMask, bad, json, vector};
// ---------------------------------------------------------------------------
// Vector masks
+1 -1
View File
@@ -1,6 +1,6 @@
use super::optimizer::{optimize, web_document};
use super::settings::{WebFormat, WebMetadata, WebSettings};
use super::*;
use super::{Dither, DocId, Document, EngineError, LayerContent, LayerId, Result, Session, Value, is_windows_device_name, join, json, other, stem, write_file};
// ---------- Generate › Image Assets ----------
+1 -1
View File
@@ -1,5 +1,5 @@
use super::settings::{WebFormat, WebMetadata, WebSettings};
use super::*;
use super::{Dither, Document, EngineError, Forced, PaletteKind, Rect, Result, Session, Value, json, other, quantize};
// ---------- the image ----------
+1 -1
View File
@@ -1,6 +1,6 @@
use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp};
use super::settings::WebSettings;
use super::*;
use super::{EngineError, Result, Session, Value, bad, join, json, other, stem, write_file};
// ---------- Export Preferences / Quick Export ----------
+1 -1
View File
@@ -1,7 +1,7 @@
use super::assets::{asset_output_path, asset_path_components};
use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp};
use super::settings::{WebSettings, rgb_hex};
use super::*;
use super::{EngineError, Rect, ResolvedSlice, Result, Session, SliceKind, Value, bad, join, json, other, portable_device_name, slices, stem, write_file};
/// A file-name-safe slice name.
fn slice_file(name: &str) -> String {
+1 -1
View File
@@ -1,5 +1,5 @@
use super::optimizer::to8;
use super::*;
use super::{Dither, PaletteKind, Result, Value, bad, json};
// ---------- settings ----------
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cmds, history_cmds, layer_multi_cmds, symmetry_cmds};
/// Per-document editing state.
#[derive(Clone, Debug)]
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::LayerId;
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
+244 -232
View File
@@ -610,248 +610,260 @@ fn overlay_gradient(g: &mut Gradient, p: &Value) {
/// parameter units. Absent (or unparseable) keys leave the effect unchanged, so
/// a dialog round trip never touches what it doesn't model: an imported
/// gradient stroke keeps its gradient while its opacity is edited.
fn overlay_color(p: &Value, k: &str, c: &mut Color) {
if let Some(x) = color_of(p, k) {
*c = x;
}
}
fn overlay_contour(p: &Value, key: &str, c: &mut Contour) {
if let Some(x) = p.get(key).and_then(contour_from_param) {
*c = x;
}
}
fn overlay_bool(p: &Value, key: &str, b: &mut bool) {
if let Some(x) = b_of(p, key) {
*b = x;
}
}
fn overlay_common(c: &mut FxCommon, p: &Value) {
if let Some(x) = b_of(p, "enabled") {
c.enabled = x;
}
if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) {
c.blend = x;
}
if let Some(x) = f_of(p, "opacity") {
c.opacity = (x / 100.0).clamp(0.0, 1.0);
}
}
fn overlay_shadow(s: &mut Shadow, p: &Value, inner: bool) {
overlay_common(&mut s.common, p);
overlay_color(p, "color", &mut s.color);
if let Some(x) = f_of(p, "angle") {
s.angle = x;
}
if let Some(x) = b_of(p, "useGlobalLight") {
s.use_global_light = x;
}
if let Some(x) = f_of(p, "distance") {
s.distance = x;
}
if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) {
s.spread = (x / 100.0).clamp(0.0, 1.0);
}
if let Some(x) = f_of(p, "size") {
s.size = x;
}
overlay_contour(p, "contour", &mut s.contour);
overlay_bool(p, "antiAlias", &mut s.anti_alias);
if let Some(x) = f_of(p, "noise") {
s.noise = (x / 100.0).clamp(0.0, 1.0);
}
if !inner && let Some(x) = b_of(p, "knocksOut") {
s.knocks_out = x;
}
}
fn overlay_glow(g: &mut Glow, p: &Value, inner: bool) {
overlay_common(&mut g.common, p);
if let Some(c) = color_of(p, "color") {
g.paint = FxPaint::Color(c);
}
if let Some(t) = p.get("technique").and_then(Value::as_str) {
g.technique = if t == "precise" { GlowTechnique::Precise } else { GlowTechnique::Softer };
}
if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) {
g.spread = (x / 100.0).clamp(0.0, 1.0);
}
if let Some(x) = f_of(p, "size") {
g.size = x;
}
overlay_contour(p, "contour", &mut g.contour);
overlay_bool(p, "antiAlias", &mut g.anti_alias);
if let Some(x) = f_of(p, "range") {
g.range = (x / 100.0).clamp(0.01, 1.0);
}
if let Some(x) = f_of(p, "noise") {
g.noise = (x / 100.0).clamp(0.0, 1.0);
}
if inner && let Some(s) = p.get("source").and_then(Value::as_str) {
g.source = if s == "center" { GlowSource::Center } else { GlowSource::Edge };
}
}
fn overlay_stroke(s: &mut StrokeFx, p: &Value) {
overlay_common(&mut s.common, p);
if let Some(x) = f_of(p, "size") {
s.size = x;
}
if let Some(pos) = p.get("position").and_then(Value::as_str) {
s.position = match pos {
"inside" => StrokePosition::Inside,
"center" => StrokePosition::Center,
_ => StrokePosition::Outside,
};
}
overlay_bool(p, "overprint", &mut s.overprint);
if p.get("from").is_some() {
s.paint = FxPaint::Gradient(gradient(p));
} else if let Some(c) = color_of(p, "color") {
s.paint = FxPaint::Color(c);
}
}
fn overlay_pattern(fx: &mut Effect, p: &Value) {
let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = fx else { return };
overlay_common(common, p);
if let Some(x) = p.get("pattern").and_then(Value::as_str) {
*name = x.to_string();
*id = String::new();
}
if let Some(x) = f_of(p, "scale") {
*scale = (x / 100.0).clamp(0.01, 10.0);
}
if let Some(x) = f_of(p, "angle") {
*angle = x;
}
if let Some(x) = b_of(p, "link") {
*link = x;
}
if let Some(x) = f_of(p, "phaseX") {
phase.0 = x;
}
if let Some(x) = f_of(p, "phaseY") {
phase.1 = x;
}
}
fn overlay_satin(s: &mut Satin, p: &Value) {
overlay_common(&mut s.common, p);
overlay_color(p, "color", &mut s.color);
if let Some(x) = f_of(p, "angle") {
s.angle = x;
}
if let Some(x) = f_of(p, "distance") {
s.distance = x;
}
if let Some(x) = f_of(p, "size") {
s.size = x;
}
if let Some(x) = b_of(p, "invert") {
s.invert = x;
}
overlay_contour(p, "contour", &mut s.contour);
overlay_bool(p, "antiAlias", &mut s.anti_alias);
}
fn overlay_bevel(bv: &mut Bevel, p: &Value) {
if let Some(x) = b_of(p, "enabled") {
bv.enabled = x;
}
if let Some(s) = p.get("style").and_then(Value::as_str) {
bv.style = match s {
"outer" => BevelStyle::OuterBevel,
"emboss" => BevelStyle::Emboss,
"pillow" => BevelStyle::PillowEmboss,
"stroke" => BevelStyle::StrokeEmboss,
_ => BevelStyle::InnerBevel,
};
}
if let Some(t) = p.get("technique").and_then(Value::as_str) {
bv.technique = match t {
"chiselHard" => BevelTechnique::ChiselHard,
"chiselSoft" => BevelTechnique::ChiselSoft,
_ => BevelTechnique::Smooth,
};
}
if let Some(x) = f_of(p, "depth") {
bv.depth = x / 100.0;
}
if let Some(d) = p.get("direction").and_then(Value::as_str) {
bv.up = d != "down";
}
if let Some(x) = f_of(p, "size") {
bv.size = x;
}
if let Some(x) = f_of(p, "soften") {
bv.soften = x;
}
if let Some(x) = f_of(p, "angle") {
bv.angle = x;
}
if let Some(x) = f_of(p, "altitude") {
bv.altitude = x;
}
if let Some(x) = b_of(p, "useGlobalLight") {
bv.use_global_light = x;
}
overlay_contour(p, "glossContour", &mut bv.gloss_contour);
overlay_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias);
if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) {
bv.highlight.blend = blend;
}
if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) {
bv.shadow.blend = blend;
}
overlay_color(p, "highlightColor", &mut bv.highlight_color);
overlay_color(p, "shadowColor", &mut bv.shadow_color);
if let Some(x) = f_of(p, "highlightOpacity") {
bv.highlight.opacity = (x / 100.0).clamp(0.0, 1.0);
}
if let Some(x) = f_of(p, "shadowOpacity") {
bv.shadow.opacity = (x / 100.0).clamp(0.0, 1.0);
}
match b_of(p, "contour") {
Some(false) => bv.contour = None,
Some(true) if bv.contour.is_none() => bv.contour = Some(photocraft_doc::BevelContour::default()),
_ => {}
}
if let Some(c) = &mut bv.contour {
overlay_contour(p, "contourName", &mut c.contour);
if let Some(x) = f_of(p, "contourRange") {
c.range = (x / 100.0).clamp(0.01, 1.0);
}
overlay_bool(p, "contourAntiAlias", &mut c.anti_alias);
}
if let Some(t) = p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()) {
bv.texture = Some(photocraft_doc::BevelTexture {
name: t.to_string(),
id: t.to_string(),
scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0),
depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0),
invert: b(p, "textureInvert", false),
link: b(p, "textureLink", true),
phase: (0.0, 0.0),
});
}
}
pub fn overlay_effect(fx: &mut Effect, p: &Value) {
if crate::commands::check_f32_values("layer.layerStyle", p).is_err() {
return;
}
fn set_color(p: &Value, k: &str, c: &mut Color) {
if let Some(x) = color_of(p, k) {
*c = x;
}
}
fn set_contour(p: &Value, key: &str, c: &mut Contour) {
if let Some(x) = p.get(key).and_then(contour_from_param) {
*c = x;
}
}
fn set_bool(p: &Value, key: &str, b: &mut bool) {
if let Some(x) = b_of(p, key) {
*b = x;
}
}
fn common(c: &mut FxCommon, p: &Value) {
if let Some(x) = b_of(p, "enabled") {
c.enabled = x;
}
if let Some(x) = p.get("blend").and_then(Value::as_str).and_then(blend_from_str) {
c.blend = x;
}
if let Some(x) = f_of(p, "opacity") {
c.opacity = (x / 100.0).clamp(0.0, 1.0);
}
}
let inner_shadow = matches!(fx, Effect::InnerShadow(_));
let inner_glow = matches!(fx, Effect::InnerGlow(_));
match fx {
Effect::DropShadow(s) | Effect::InnerShadow(s) => {
let inner = inner_shadow;
common(&mut s.common, p);
set_color(p, "color", &mut s.color);
if let Some(x) = f_of(p, "angle") {
s.angle = x;
}
if let Some(x) = b_of(p, "useGlobalLight") {
s.use_global_light = x;
}
if let Some(x) = f_of(p, "distance") {
s.distance = x;
}
if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) {
s.spread = (x / 100.0).clamp(0.0, 1.0);
}
if let Some(x) = f_of(p, "size") {
s.size = x;
}
set_contour(p, "contour", &mut s.contour);
set_bool(p, "antiAlias", &mut s.anti_alias);
if let Some(x) = f_of(p, "noise") {
s.noise = (x / 100.0).clamp(0.0, 1.0);
}
if !inner && let Some(x) = b_of(p, "knocksOut") {
s.knocks_out = x;
}
Effect::DropShadow(s) => overlay_shadow(s, p, false),
Effect::InnerShadow(s) => overlay_shadow(s, p, true),
Effect::OuterGlow(g) => overlay_glow(g, p, false),
Effect::InnerGlow(g) => overlay_glow(g, p, true),
Effect::Stroke(s) => overlay_stroke(s, p),
Effect::ColorOverlay { common, color } => {
overlay_common(common, p);
overlay_color(p, "color", color);
}
Effect::OuterGlow(g) | Effect::InnerGlow(g) => {
let inner = inner_glow;
common(&mut g.common, p);
if let Some(c) = color_of(p, "color") {
g.paint = FxPaint::Color(c);
}
if let Some(t) = p.get("technique").and_then(Value::as_str) {
g.technique = if t == "precise" { GlowTechnique::Precise } else { GlowTechnique::Softer };
}
if let Some(x) = f_of(p, if inner { "choke" } else { "spread" }) {
g.spread = (x / 100.0).clamp(0.0, 1.0);
}
if let Some(x) = f_of(p, "size") {
g.size = x;
}
set_contour(p, "contour", &mut g.contour);
set_bool(p, "antiAlias", &mut g.anti_alias);
if let Some(x) = f_of(p, "range") {
g.range = (x / 100.0).clamp(0.01, 1.0);
}
if let Some(x) = f_of(p, "noise") {
g.noise = (x / 100.0).clamp(0.0, 1.0);
}
if inner && let Some(s) = p.get("source").and_then(Value::as_str) {
g.source = if s == "center" { GlowSource::Center } else { GlowSource::Edge };
}
}
Effect::Stroke(s) => {
common(&mut s.common, p);
if let Some(x) = f_of(p, "size") {
s.size = x;
}
if let Some(pos) = p.get("position").and_then(Value::as_str) {
s.position = match pos {
"inside" => StrokePosition::Inside,
"center" => StrokePosition::Center,
_ => StrokePosition::Outside,
};
}
set_bool(p, "overprint", &mut s.overprint);
if p.get("from").is_some() {
s.paint = FxPaint::Gradient(gradient(p));
} else if let Some(c) = color_of(p, "color") {
s.paint = FxPaint::Color(c);
}
}
Effect::ColorOverlay { common: c, color } => {
common(c, p);
set_color(p, "color", color);
}
Effect::GradientOverlay { common: c, gradient: g, dither, interpolation } => {
common(c, p);
gradient_overlay::overlay(g, interpolation, p);
Effect::GradientOverlay { common, gradient, dither, interpolation } => {
overlay_common(common, p);
gradient_overlay::overlay(gradient, interpolation, p);
if let Some(x) = b_of(p, "dither") {
*dither = x;
}
}
Effect::PatternOverlay { common: c, name, id, scale, angle, link, phase } => {
common(c, p);
if let Some(x) = p.get("pattern").and_then(Value::as_str) {
*name = x.to_string();
*id = String::new();
}
if let Some(x) = f_of(p, "scale") {
*scale = (x / 100.0).clamp(0.01, 10.0);
}
if let Some(x) = f_of(p, "angle") {
*angle = x;
}
if let Some(x) = b_of(p, "link") {
*link = x;
}
if let Some(x) = f_of(p, "phaseX") {
phase.0 = x;
}
if let Some(x) = f_of(p, "phaseY") {
phase.1 = x;
}
}
Effect::Satin(s) => {
common(&mut s.common, p);
set_color(p, "color", &mut s.color);
if let Some(x) = f_of(p, "angle") {
s.angle = x;
}
if let Some(x) = f_of(p, "distance") {
s.distance = x;
}
if let Some(x) = f_of(p, "size") {
s.size = x;
}
if let Some(x) = b_of(p, "invert") {
s.invert = x;
}
set_contour(p, "contour", &mut s.contour);
set_bool(p, "antiAlias", &mut s.anti_alias);
}
Effect::BevelEmboss(bv) => {
if let Some(x) = b_of(p, "enabled") {
bv.enabled = x;
}
if let Some(s) = p.get("style").and_then(Value::as_str) {
bv.style = match s {
"outer" => BevelStyle::OuterBevel,
"emboss" => BevelStyle::Emboss,
"pillow" => BevelStyle::PillowEmboss,
"stroke" => BevelStyle::StrokeEmboss,
_ => BevelStyle::InnerBevel,
};
}
if let Some(t) = p.get("technique").and_then(Value::as_str) {
bv.technique = match t {
"chiselHard" => BevelTechnique::ChiselHard,
"chiselSoft" => BevelTechnique::ChiselSoft,
_ => BevelTechnique::Smooth,
};
}
if let Some(x) = f_of(p, "depth") {
bv.depth = x / 100.0;
}
if let Some(d) = p.get("direction").and_then(Value::as_str) {
bv.up = d != "down";
}
if let Some(x) = f_of(p, "size") {
bv.size = x;
}
if let Some(x) = f_of(p, "soften") {
bv.soften = x;
}
if let Some(x) = f_of(p, "angle") {
bv.angle = x;
}
if let Some(x) = f_of(p, "altitude") {
bv.altitude = x;
}
if let Some(x) = b_of(p, "useGlobalLight") {
bv.use_global_light = x;
}
set_contour(p, "glossContour", &mut bv.gloss_contour);
set_bool(p, "glossAntiAlias", &mut bv.gloss_anti_alias);
// Keep imported PSD shading settings when a command edits other bevel fields.
if let Some(blend) = p.get("highlightBlend").and_then(Value::as_str).and_then(blend_from_str) {
bv.highlight.blend = blend;
}
if let Some(blend) = p.get("shadowBlend").and_then(Value::as_str).and_then(blend_from_str) {
bv.shadow.blend = blend;
}
set_color(p, "highlightColor", &mut bv.highlight_color);
set_color(p, "shadowColor", &mut bv.shadow_color);
if let Some(x) = f_of(p, "highlightOpacity") {
bv.highlight.opacity = (x / 100.0).clamp(0.0, 1.0);
}
if let Some(x) = f_of(p, "shadowOpacity") {
bv.shadow.opacity = (x / 100.0).clamp(0.0, 1.0);
}
// The Contour element: `contour` turns it on/off; its curve, Range and
// Anti-aliased edit the element in place, so an imported curve survives.
match b_of(p, "contour") {
Some(false) => bv.contour = None,
Some(true) if bv.contour.is_none() => bv.contour = Some(photocraft_doc::BevelContour::default()),
_ => {}
}
if let Some(c) = &mut bv.contour {
set_contour(p, "contourName", &mut c.contour);
if let Some(x) = f_of(p, "contourRange") {
c.range = (x / 100.0).clamp(0.01, 1.0);
}
set_bool(p, "contourAntiAlias", &mut c.anti_alias);
}
if let Some(t) = p.get("texture").and_then(Value::as_str).filter(|t| !t.is_empty()) {
bv.texture = Some(photocraft_doc::BevelTexture {
name: t.to_string(),
id: t.to_string(),
scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0),
depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0),
invert: b(p, "textureInvert", false),
link: b(p, "textureLink", true),
phase: (0.0, 0.0),
});
}
}
Effect::PatternOverlay { .. } => overlay_pattern(fx, p),
Effect::Satin(s) => overlay_satin(s, p),
Effect::BevelEmboss(bv) => overlay_bevel(bv, p),
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
use super::customize::{keyboard_shortcuts, menus};
use super::validate::{SECTIONS, get_path, keyed};
use super::*;
use super::{CommandSpec, EngineError, Map, Result, Session, ToolbarCustomization, Value, json};
// ------------------------------------------------------------------ commands
+71 -60
View File
@@ -1,7 +1,7 @@
use super::cmds::bad;
use super::files::{file_target, read_text_file, rename_path, writable, write_files_atomically};
use super::shortcuts::{BindKind, alternate_keys, bindable, bindable_items, conflicts, default_alternates, is_tool, normalize_shortcut, reserved_shortcut};
use super::*;
use super::{MenuCustomization, Preferences, Result, Session, Value, json};
/// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts.
pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result<Value> {
@@ -108,65 +108,7 @@ pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => &empty,
Some(v) => v.as_object().ok_or_else(|| bad(cmd, "`alternates` maps command ids to lists of shortcuts"))?,
};
if !set.is_empty() || !alts.is_empty() {
let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false);
changed = true;
// Reserved system keys can't be bound, by hand or from a file.
let reserved = |v: &Value| -> Option<String> {
let keys = match v {
Value::String(s) => vec![s.clone()],
other => alternate_keys(other).unwrap_or_default(),
};
keys.into_iter().find(|k| reserved_shortcut(k))
};
if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) {
return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned")));
}
for (id, v) in set {
if !bindable().any(|(b, _)| b == id) && !allow_unknown {
return Err(bad(cmd, format!("unknown command `{id}`")));
}
next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?;
}
for (id, v) in alts {
if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown {
return Err(bad(cmd, format!("unknown command `{id}`")));
}
next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?;
}
// Like Photoshop, a shortcut moved to a new command is taken away from the old one,
// whether the old one held it as its main key or as an alternate (#3665).
if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) {
let assigned: Vec<(&str, String)> = set
.iter()
.filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?)))
.chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k))))
.collect();
for (id, sc) in assigned {
for (c, def) in bindable() {
// Tools may share a key: they cycle with Shift, as Photoshop's groups do.
if is_tool(id) && is_tool(c) {
continue;
}
// Never strip a command that this same call is assigning:
// two entries for one key are a clash inside the call, which
// the returned conflicts list reports (#719). Stripping
// each other here unbound both silently.
if c == id || set.contains_key(c) || alts.contains_key(c) {
continue;
}
let main = next.shortcut(c, def).map(str::to_string);
if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) {
next.shortcuts.insert(c.to_string(), String::new());
}
let held = next.alternates(c, main.as_deref());
if held.contains(&sc) {
next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect());
}
}
}
}
}
changed |= apply_shortcut_changes(&mut next, p, set, alts, cmd)?;
// Then the sets are saved, deleted or switched, from the bindings as they now stand.
changed |= crate::shortcut_sets::store(&mut next, p).map_err(|e| bad(cmd, e))?;
// The reply and the exports read the bindings as they will be; they are committed only once
@@ -262,6 +204,75 @@ pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
fn apply_shortcut_changes(
next: &mut Preferences,
p: &Value,
set: &serde_json::Map<String, Value>,
alts: &serde_json::Map<String, Value>,
cmd: &str,
) -> Result<bool> {
if set.is_empty() && alts.is_empty() {
return Ok(false);
}
let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false);
// Reserved system keys can't be bound, by hand or from a file.
let reserved = |v: &Value| -> Option<String> {
let keys = match v {
Value::String(s) => vec![s.clone()],
other => alternate_keys(other).unwrap_or_default(),
};
keys.into_iter().find(|k| reserved_shortcut(k))
};
if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) {
return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned")));
}
for (id, v) in set {
if !bindable().any(|(b, _)| b == id) && !allow_unknown {
return Err(bad(cmd, format!("unknown command `{id}`")));
}
next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?;
}
for (id, v) in alts {
if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown {
return Err(bad(cmd, format!("unknown command `{id}`")));
}
next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?;
}
// Like Photoshop, a shortcut moved to a new command is taken away from the old one,
// whether the old one held it as its main key or as an alternate (#3665).
if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) {
let assigned: Vec<(&str, String)> = set
.iter()
.filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?)))
.chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k))))
.collect();
for (id, sc) in assigned {
for (c, def) in bindable() {
// Tools may share a key: they cycle with Shift, as Photoshop's groups do.
if is_tool(id) && is_tool(c) {
continue;
}
// Never strip a command that this same call is assigning:
// two entries for one key are a clash inside the call, which
// the returned conflicts list reports (#719). Stripping
// each other here unbound both silently.
if c == id || set.contains_key(c) || alts.contains_key(c) {
continue;
}
let main = next.shortcut(c, def).map(str::to_string);
if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) {
next.shortcuts.insert(c.to_string(), String::new());
}
let held = next.alternates(c, main.as_deref());
if held.contains(&sc) {
next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect());
}
}
}
}
Ok(true)
}
/// Edit › Menus: hide/show items and give them colours.
pub(super) fn menus(s: &mut Session, p: &Value) -> Result<Value> {
let ids = |k: &str| -> Vec<String> {
+1 -1
View File
@@ -1,5 +1,5 @@
use super::cmds::bad;
use super::*;
use super::{Result, Value};
/// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object
/// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` →
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{BTreeMap, Value};
/// Most further keys one command may hold; Photoshop's own defaults use one.
pub const MAX_ALTERNATES: usize = 8;
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{Deserialize, Map, Preferences, Serialize, Value};
// ------------------------------------------------------------------ store
+6 -1
View File
@@ -1,5 +1,10 @@
use super::shortcuts::normalize_shortcut;
use super::*;
use super::{
AppearanceMode, Ask, CanvasBorder, CanvasColor, CheckerColors, CheckerSize, ColorPicker, DarkTheme, ExportLocation, ExportMetadata, FontPreview,
GpuBackend, Interpolation, LightTheme, LineStyle, LinuxDisplayServer, LogDestination, LogDetail, OtherCursor, PaintingCursor, PointSize, PressureCurve,
QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RenderingMode, RightClickPaint, TextEngine, Theme, TypeUnit, UiFontSize, UiScale,
Unit, Value,
};
/// Preferences dialog sections in Photoshop's order: (id, title).
pub const SECTIONS: [(&str, &str); 18] = [
+4 -1
View File
@@ -1,6 +1,9 @@
use super::doc_state::DocState;
use super::error::{EngineError, Result};
use super::*;
use super::{
Arc, Document, LayerId, LayerTarget, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds, smart_cmds,
type_cmds,
};
mod documents;
mod execute;
+1 -1
View File
@@ -1,5 +1,5 @@
use super::history::fix_selection;
use super::*;
use super::{DocState, Document, Session, channel_cmds, smart_cmds};
/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when
/// `i` is out of range.
+5 -2
View File
@@ -1,5 +1,8 @@
use super::history::fix_selection;
use super::*;
use super::history::{fix_selection, visibility_changes};
use super::{
Arc, Document, EngineError, LayerId, Result, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds,
smart_cmds,
};
impl Session {
/// Run a command by id with JSON params. Returns a JSON result.
+1 -1
View File
@@ -1,5 +1,5 @@
use super::documents::fix_active;
use super::*;
use super::{Arc, DocState, Document, LayerId, LayerTarget, Session, channel_cmds, layer_multi_cmds};
impl Session {
pub fn undo(&mut self) -> bool {
+1 -1
View File
@@ -1,5 +1,5 @@
use super::history::fix_selection;
use super::*;
use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, type_cmds};
impl Session {
/// Replace the active document's active layer without creating a history step.
+2
View File
@@ -196,6 +196,8 @@ pub(super) fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec<u8> {
#[cfg(test)]
mod tests {
use super::*;
use photocraft_doc::{Layer, LayerContent};
use photocraft_raster::Surface;
fn previous_merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool) -> (Vec<u8>, bool, bool) {
if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, &Interrupt::NONE) {
+9 -1
View File
@@ -1,5 +1,13 @@
use super::services::{ExportSettings, FormatChoices, SAVE_OPTIONS_OPEN, SaveKind, Services, plain_raster, saved_revision_after_write};
use super::*;
use super::{
ControlRequest, DocId, Document, HashMap, PhotocraftApp, Receiver, Session, SyntheticTarget, Tool, UiState, Value, actions, analysis_ui, brush_panel,
brush_picker, camera_raw_ui, canvas, dds_options_ui, delete_layer_prompt, dialogs, discard_ui, distort_ui, dock, field_wheel, file_open,
filter_preview_worker, gpu_canvas, gpu_status, gradient_ui, histogram_panel, i18n, jobs_ui, jpeg_options_ui, json, kys_import, last_brush, layers_panel_ui,
mask_thumbs_ui, mask_trash_prompt, monitor_status, native_menu, notices, open_prompt, paint_mouse, palette, panel_docking, panels, prefs_ui,
preset_files_ui, preset_panels, rasterize_prompt, screen_picker, shape_stroke_ui, shortcuts, single_line_drag, state, stroke_trace, stylus,
targa_options_ui, text_field_menu, theme, tiff_options_ui, timeline_ui, titlebar, tool_cursor, tool_memory, transform_tool, type_panels_ui, type_tool,
type_transform, updates_ui, vector_ui, view_cmds, wheel_nav, wide_angle_ui, widgets, work_area, workspace_ui,
};
mod clipboard;
mod commands;
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::PhotocraftApp;
fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 {
let mut sig = (w as u64) << 32 | h as u64;
+92 -77
View File
@@ -1,4 +1,7 @@
use super::*;
use super::{
DocId, PhotocraftApp, Tool, Value, actions, canvas, delete_layer_prompt, dock, gpu_canvas, jobs_ui, json, mask_trash_prompt, notices, panel_docking, state,
transform_tool, type_transform, vector_ui,
};
impl PhotocraftApp {
/// Run an engine command, reporting errors in the status bar.
@@ -115,82 +118,7 @@ impl PhotocraftApp {
jobs_ui::run(self, id, params)
};
let creates_adjustment_or_fill = id.starts_with("layer.newAdjustmentLayer.") || id.starts_with("layer.newFillLayer.");
if r.is_ok() && ADDS_LAYER_MASK.contains(&id) {
// Adding an explicit mask targets it, as in Photoshop (#2166).
self.ui.mask_target = true;
self.ui.vector_mask_target = false;
self.ui.properties_layer = None;
} else if r.is_ok() && creates_adjustment_or_fill {
// Panel Options may suppress a fill layer's default mask. Never target a
// nonexistent mask; an active path creates a vector mask instead.
let masks = self
.session
.active()
.and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id)))
.map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some()))
.unwrap_or((false, false));
self.ui.mask_target = masks.0;
self.ui.vector_mask_target = !masks.0 && masks.1;
// Keep Properties on the new layer contents, as on main (#3369).
self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0);
}
if r.is_ok() && creates_adjustment_or_fill {
// Properties comes to the front, shown and expanded, so the new layer's settings can
// be edited at once, as in Photoshop (#4028). The layer is made whatever happens here.
if self.ui.docking.is_some() {
let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"}));
} else {
self.ui.dock_tabs.properties = 0;
dock::reveal(self, dock::Group::Properties);
}
}
// Making a new selection reveals its outline after View > Extras was hidden (#5597).
// These interactive selection commands complete inline; a failed command, deselection,
// or painting inside an existing selection must leave the user's view choice alone.
if r.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true)))
&& matches!(
id,
"select.rect"
| "select.lasso"
| "select.magneticLasso"
| "select.magicWand"
| "select.quick"
| "select.object"
| "select.loadSelection"
| "select.loadLuminosity"
| "path.toSelection"
)
&& self.session.active().is_some_and(|st| st.doc.selection.is_some())
{
self.ui.view.extras = true;
}
if r.is_ok() && id == "select.toWorkPath" {
// Make Work Path selects the new work path in the Paths panel, as in Photoshop.
self.ui.selected_path = Some("work".into());
}
if r.is_ok() && path_mask {
// The new layer's vector mask becomes the active path, as in Photoshop: the path it
// was made from is no longer selected, so the next fill layer isn't masked by it too.
self.ui.selected_path = Some("layer".into());
}
if r.is_ok() && creates_active_mask {
// Adding a mask selects its thumbnail: the next brush or footer Delete targets it.
self.ui.mask_target = true;
self.ui.vector_mask_target = false;
}
if r.is_ok() && creates_active_vector_mask {
// Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a
// mask made from a path becomes the active path.
self.ui.vector_mask_target = true;
self.ui.mask_target = false;
if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") {
self.ui.selected_path = Some("layer".into());
}
}
if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {
self.clip_external = false;
self.export_os_clipboard();
}
self.sync_command_side_effects(id, &r, creates_active_mask, creates_active_vector_mask, creates_adjustment_or_fill, path_mask);
self.perf.last_command = id.to_string();
self.perf.command_ms = gpu_canvas::now_ms() - t0;
match &r {
@@ -227,6 +155,93 @@ impl PhotocraftApp {
self.tool_override.unwrap_or(self.ui.tool)
}
fn sync_command_side_effects(
&mut self,
id: &str,
result: &Result<Value, String>,
creates_active_mask: bool,
creates_active_vector_mask: bool,
creates_adjustment_or_fill: bool,
path_mask: bool,
) {
if result.is_ok() && ADDS_LAYER_MASK.contains(&id) {
// Adding an explicit mask targets it, as in Photoshop (#2166).
self.ui.mask_target = true;
self.ui.vector_mask_target = false;
self.ui.properties_layer = None;
} else if result.is_ok() && creates_adjustment_or_fill {
// Panel Options may suppress a fill layer's default mask. Never target a
// nonexistent mask; an active path creates a vector mask instead.
let masks = self
.session
.active()
.and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id)))
.map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some()))
.unwrap_or((false, false));
self.ui.mask_target = masks.0;
self.ui.vector_mask_target = !masks.0 && masks.1;
// Keep Properties on the new layer contents, as on main (#3369).
self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0);
}
if result.is_ok() && creates_adjustment_or_fill {
// Properties comes to the front, shown and expanded, so the new layer's settings can
// be edited at once, as in Photoshop (#4028). The layer is made whatever happens here.
if self.ui.docking.is_some() {
let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"}));
} else {
self.ui.dock_tabs.properties = 0;
dock::reveal(self, dock::Group::Properties);
}
}
// Making a new selection reveals its outline after View > Extras was hidden (#5597).
// These interactive selection commands complete inline; a failed command, deselection,
// or painting inside an existing selection must leave the user's view choice alone.
if result.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true)))
&& matches!(
id,
"select.rect"
| "select.lasso"
| "select.magneticLasso"
| "select.magicWand"
| "select.quick"
| "select.object"
| "select.loadSelection"
| "select.loadLuminosity"
| "path.toSelection"
)
&& self.session.active().is_some_and(|st| st.doc.selection.is_some())
{
self.ui.view.extras = true;
}
if result.is_ok() && id == "select.toWorkPath" {
// Make Work Path selects the new work path in the Paths panel, as in Photoshop.
self.ui.selected_path = Some("work".into());
}
if result.is_ok() && path_mask {
// The new layer's vector mask becomes the active path, as in Photoshop: the path it
// was made from is no longer selected, so the next fill layer isn't masked by it too.
self.ui.selected_path = Some("layer".into());
}
if result.is_ok() && creates_active_mask {
// Adding a mask selects its thumbnail: the next brush or footer Delete targets it.
self.ui.mask_target = true;
self.ui.vector_mask_target = false;
}
if result.is_ok() && creates_active_vector_mask {
// Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a
// mask made from a path becomes the active path.
self.ui.vector_mask_target = true;
self.ui.mask_target = false;
if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") {
self.ui.selected_path = Some("layer".into());
}
}
if result.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {
self.clip_external = false;
self.export_os_clipboard();
}
}
pub fn sync_views(&mut self) {
type_transform::cancel_stale(self);
crate::cam_transform::cancel_stale(self);
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{ControlRequest, PhotocraftApp, Receiver};
impl PhotocraftApp {
/// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests).
+4 -1
View File
@@ -1,4 +1,7 @@
use super::*;
use super::{
DocId, ExportSettings, FormatChoices, PhotocraftApp, SAVE_OPTIONS_OPEN, SaveKind, Value, camera_raw_ui, dds_options_ui, file_open, jobs_ui,
jpeg_options_ui, json, notices, open_prompt, plain_raster, preset_files_ui, saved_revision_after_write, targa_options_ui, tiff_options_ui,
};
impl PhotocraftApp {
/// Record `path` as the most-recently-opened file (File › Open Recent): de-duplicated, newest
+7 -1
View File
@@ -1,4 +1,10 @@
use super::*;
use super::{
PhotocraftApp, analysis_ui, brush_panel, brush_picker, camera_raw_ui, canvas, dds_options_ui, dialogs, discard_ui, distort_ui, field_wheel, file_open,
filter_preview_worker, gpu_canvas, gpu_status, gradient_ui, i18n, jobs_ui, jpeg_options_ui, kys_import, last_brush, layers_panel_ui, monitor_status,
native_menu, notices, paint_mouse, palette, panels, prefs_ui, preset_panels, rasterize_prompt, screen_picker, shape_stroke_ui, shortcuts, targa_options_ui,
text_field_menu, theme, tiff_options_ui, timeline_ui, titlebar, tool_cursor, tool_memory, transform_tool, type_panels_ui, type_tool, updates_ui, vector_ui,
view_cmds, wide_angle_ui, work_area, workspace_ui,
};
impl PhotocraftApp {
/// Wait out the rest of [`Self::min_frame_ms`] since the last frame started.
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{PhotocraftApp, gpu_canvas, gpu_status};
impl PhotocraftApp {
/// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures.
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{PhotocraftApp, type_tool};
impl PhotocraftApp {
/// Install the callback-mode markers in an app creator, before the first `run_ui` on this
+1 -1
View File
@@ -1,4 +1,4 @@
use super::*;
use super::{PhotocraftApp, SyntheticTarget};
/// Remove one contiguous run equal to `batch` from `events` (eframe's preserved synthetic
/// input). A no-op when the run is not present.
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff. Show more