Skip to content

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

Edit > Stroke: a full options dialog with Fill's blending controls (#1477)

Nigel Ihza Firdausy0f2900da34d7
diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs
index ed06ea854..b424fe84d 100644
--- a/crates/engine/src/extra_cmds.rs
+++ b/crates/engine/src/extra_cmds.rs
@@ -123,8 +123,29 @@ fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut
/// Edit › Stroke: a band along the selection edge (or the layer's opaque edge without a selection).
fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
let width = p.get("width").and_then(Value::as_f64).unwrap_or(1.0).clamp(1.0, 250.0) as f32;
- let mut color = color_param(p, "color", s.tools.foreground);
- color[3] *= (p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0).clamp(0.0, 1.0);
+ let color = color_param(p, "color", s.tools.foreground);
+ let mode = match p.get("mode") {
+ None | Some(Value::Null) => photocraft_color::BlendMode::Normal,
+ Some(Value::String(m)) => crate::commands::blend_from_str(m)
+ .filter(|m| *m != photocraft_color::BlendMode::PassThrough)
+ .ok_or_else(|| EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("unknown blend mode `{m}`") })?,
+ Some(v) => return Err(EngineError::BadParams { cmd: "edit.stroke".into(), msg: format!("mode must be a blend mode name, not {v}") }),
+ };
+ let opacity = match p.get("opacity") {
+ None | Some(Value::Null) => 1.0,
+ Some(v) => {
+ (v.as_f64()
+ .filter(|x| x.is_finite())
+ .ok_or_else(|| EngineError::BadParams { cmd: "edit.stroke".into(), msg: "opacity must be a finite number from 0 to 100".into() })?
+ .clamp(0.0, 100.0)
+ / 100.0) as f32
+ }
+ };
+ let preserve = match p.get("preserveTransparency") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(v)) => *v,
+ Some(_) => return Err(EngineError::BadParams { cmd: "edit.stroke".into(), msg: "preserveTransparency must be true or false".into() }),
+ };
let location = p.get("location").and_then(Value::as_str).unwrap_or("center").to_string();
let id = layer_param(s, p)?;
s.edit("Stroke", |doc, _| {
@@ -151,7 +172,7 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
let area = band.content_bounds().intersect(&canvas);
if !area.is_empty() {
- crate::pixels::fill_surface(surf, area, color, Some(&band), lock);
+ crate::fill_cmds::blend_color_mask(surf, area, color, &band, mode, opacity, preserve || lock);
surf.prune();
}
Ok(())
@@ -624,7 +645,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke…",
&["Edit"],
None,
- r##"{"width":1..250=1,"color":"#rrggbb|[r,g,b,a]"=foreground,"location":"inside|center|outside"="center","opacity":0..100=100}"##,
+ r##"{"width":1..250=1,"color":"#rrggbb|[r,g,b,a]"=foreground,"location":"inside|center|outside"="center","mode":"any layer blend mode"="normal","opacity":0..100=100,"preserveTransparency":bool=false}"##,
has_pixels,
stroke
),
@@ -887,6 +908,52 @@ mod tests {
assert_eq!(pixel(&s, 15, 15), vec![0.0, 0.0, 1.0, 1.0]);
}
+ #[test]
+ fn stroke_uses_fill_blending_and_preserves_transparency_at_every_depth() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.5, 0.5, 0.5, 1.0]);
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
+
+ let past = s.active().unwrap().history.past_len();
+ s.execute(
+ "edit.stroke",
+ json!({"width": 2, "color": "#ffffff", "location": "inside", "mode": "multiply", "opacity": 100, "preserveTransparency": true}),
+ )
+ .unwrap();
+ assert_eq!(s.active().unwrap().history.past_len(), past + 1, "Stroke is one history step");
+ let edge = pixel(&s, 10, 15);
+ assert!((edge[0] - 0.5).abs() < 0.015, "{depth}-bit Multiply must preserve gray: {edge:?}");
+ assert_eq!(edge[3], 1.0);
+
+ s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "preserveTransparency": true})).unwrap();
+ assert_eq!(pixel(&s, 9, 15)[3], 0.0, "{depth}-bit transparency lock prevents new outer pixels");
+
+ s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "opacity": 50})).unwrap();
+ let out = pixel(&s, 9, 15);
+ assert!((out[3] - 0.5).abs() < 0.015, "{depth}-bit 50% stroke opacity: {out:?}");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(pixel(&s, 9, 15)[3], 0.0);
+ }
+ }
+
+ #[test]
+ fn stroke_rejects_invalid_blending_options_without_modifying_the_document() {
+ let mut s = session(8);
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
+ let past = s.active().unwrap().history.past_len();
+ for params in [
+ json!({"mode": "unknown-mode"}),
+ json!({"mode": 42}),
+ json!({"mode": "passThrough"}),
+ json!({"opacity": "lots"}),
+ json!({"preserveTransparency": "true"}),
+ ] {
+ assert!(s.execute("edit.stroke", params.clone()).is_err(), "{params}");
+ assert_eq!(s.active().unwrap().history.past_len(), past, "{params} should not create a history step");
+ }
+ }
+
#[test]
fn transform_presets_are_exact() {
let mut s = session(8);
diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs
index a6fb41275..827bef866 100644
--- a/crates/engine/src/fill_cmds.rs
+++ b/crates/engine/src/fill_cmds.rs
@@ -168,6 +168,21 @@ pub(crate) fn composite_over(surf: &mut Surface, src: &Surface, area: Rect, limi
blend_into(surf, area, &source, limit, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false });
}
+/// Reuse Edit › Fill's compositing for Edit › Stroke. The stroke's rasterized band
+/// is already a grayscale coverage mask; opacity, blend modes and alpha locking
+/// must behave identically for both commands at 8/16/32-bit depth.
+pub(crate) fn blend_color_mask(
+ surf: &mut Surface,
+ area: Rect,
+ color: [f32; 4],
+ coverage: &Surface,
+ mode: BlendMode,
+ opacity: f32,
+ preserve_transparency: bool,
+) {
+ blend_into(surf, area, &Source::Color(color), Some(coverage), Blend { mode, opacity, keep_alpha: preserve_transparency, restore: false });
+}
+
/// The selection filled from its surroundings (`photocraft_algo::content_aware`), as straight
/// RGBA over the sampling window. Only the selected pixels are used.
fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, color_adaptation: bool, seed: u64) -> Result<Source> {
diff --git a/crates/ui-egui/src/dialog_blend_ui.rs b/crates/ui-egui/src/dialog_blend_ui.rs
new file mode 100644
index 000000000..0eb8207eb
--- /dev/null
+++ b/crates/ui-egui/src/dialog_blend_ui.rs
@@ -0,0 +1,61 @@
+//! Blending controls shared by Edit › Fill and Edit › Stroke.
+//!
+//! Both commands support the same layer blend modes, opacity and transparency lock.
+//! Keeping one widget and validation implementation prevents their options diverging.
+
+use egui::{Align2, Sense, pos2, vec2};
+use serde_json::{Map, Value, json};
+
+use crate::theme::Tokens;
+
+/// Validate a persisted blending choice before restoring it from Preferences.
+pub fn valid(key: &str, v: &Value) -> bool {
+ match key {
+ "mode" => v.as_str().and_then(photocraft_engine::commands::blend_from_str).is_some_and(|m| m != photocraft_color::BlendMode::PassThrough),
+ "opacity" => v.as_f64().is_some_and(|o| o.is_finite() && (0.0..=100.0).contains(&o)),
+ "preserveTransparency" => v.is_boolean(),
+ _ => false,
+ }
+}
+
+/// UI for the identical Blending section of Fill and Stroke.
+pub fn body(ui: &mut egui::Ui, fields: &mut Map<String, Value>, prefix: &str) {
+ ui.add_space(4.0);
+ crate::widgets::section_label(ui, tl!("Blending"));
+ crate::widgets::hairline(ui);
+ ui.horizontal(|ui| {
+ label(ui, tl!("Mode:"));
+ let mut mode = fields.get("mode").and_then(Value::as_str).unwrap_or("normal").to_string();
+ let opts: Vec<(String, &str)> = photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (mode_key(*m), m.label())).collect();
+ if crate::widgets::dropdown(ui, &format!("{prefix}-mode"), &mut mode, &opts, 170.0) {
+ fields.insert("mode".into(), json!(mode));
+ }
+ });
+ ui.horizontal(|ui| {
+ label(ui, tl!("Opacity:"));
+ let mut opacity = fields.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32;
+ if crate::widgets::value_field(ui, &mut opacity, 0.0..=100.0, "%", 70.0).changed() {
+ fields.insert("opacity".into(), json!(opacity.round()));
+ }
+ });
+ ui.horizontal(|ui| {
+ label(ui, "");
+ let mut preserve = fields.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false);
+ if crate::widgets::checkbox(ui, &mut preserve, tl!("Preserve Transparency")).changed() {
+ fields.insert("preserveTransparency".into(), json!(preserve));
+ }
+ });
+}
+
+fn label(ui: &mut egui::Ui, text: &str) {
+ let t = Tokens::get(ui.ctx());
+ let (r, _) = ui.allocate_exact_size(vec2(112.0, 22.0), Sense::hover());
+ ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim);
+}
+
+/// The `mode` param naming a blend mode ("normal", "colorBurn"…), parsed by the engine.
+fn mode_key(m: photocraft_color::BlendMode) -> String {
+ let s = format!("{m:?}");
+ let mut c = s.chars();
+ c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default()
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 9570d5d68..4ef5aa1f8 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -194,6 +194,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
}
DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields),
+ DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields),
DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields),
DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields),
DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields),
@@ -368,6 +369,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
r
}
DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields),
+ DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields),
DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields),
DialogKind::Command if crate::variables_ui::owns(&d.fields) => crate::variables_ui::confirm(app, &d.fields),
DialogKind::Command if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields),
@@ -406,6 +408,9 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
/// schema dialog for filters, the Color Range dialog for `select.colorRange`, otherwise a bare
/// confirm dialog.
pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) -> u64 {
+ if command == crate::stroke_ui::COMMAND {
+ return crate::stroke_ui::open(app);
+ }
if command == crate::color_range_ui::COMMAND {
return crate::color_range_ui::open(app);
}
diff --git a/crates/ui-egui/src/fill_ui.rs b/crates/ui-egui/src/fill_ui.rs
index 957dcd900..284430bb4 100644
--- a/crates/ui-egui/src/fill_ui.rs
+++ b/crates/ui-egui/src/fill_ui.rs
@@ -45,11 +45,10 @@ fn hex(c: [f32; 4]) -> String {
fn valid(app: &PhotocraftApp, key: &str, v: &Value) -> bool {
match key {
"contents" => v.as_str().is_some_and(|c| CONTENTS.iter().any(|(k, _)| *k == c)),
- "mode" => v.as_str().and_then(photocraft_engine::commands::blend_from_str).is_some_and(|m| m != photocraft_color::BlendMode::PassThrough),
- "opacity" => v.as_f64().is_some_and(|o| (0.0..=100.0).contains(&o)),
+ "mode" | "opacity" | "preserveTransparency" => crate::dialog_blend_ui::valid(key, v),
"color" => v.as_str().is_some_and(|h| h.len() == 7 && h.starts_with('#') && h.get(1..).is_some_and(|d| d.chars().all(|c| c.is_ascii_hexdigit()))),
"pattern" => v.as_str().is_some_and(|p| app.session.patterns.items.iter().any(|q| q.id == p)),
- "colorAdaptation" | "preserveTransparency" => v.is_boolean(),
+ "colorAdaptation" => v.is_boolean(),
_ => false,
}
}
@@ -178,38 +177,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>)
}
_ => {}
}
- ui.add_space(4.0);
- crate::widgets::section_label(ui, "Blending");
- crate::widgets::hairline(ui);
- ui.horizontal(|ui| {
- label(ui, tl!("Mode:"));
- let mut mode = get_str(f, "mode", "normal");
- let opts: Vec<(String, &str)> = photocraft_color::BlendMode::LAYER_MODES.iter().map(|m| (mode_key(*m), m.label())).collect();
- if crate::widgets::dropdown(ui, "fill-mode", &mut mode, &opts, 170.0) {
- f.insert("mode".into(), json!(mode));
- }
- });
- ui.horizontal(|ui| {
- label(ui, tl!("Opacity:"));
- let mut o = f.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32;
- if crate::widgets::value_field(ui, &mut o, 0.0..=100.0, "%", 70.0).changed() {
- f.insert("opacity".into(), json!(o.round()));
- }
- });
- ui.horizontal(|ui| {
- label(ui, "");
- let mut on = f.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false);
- if crate::widgets::checkbox(ui, &mut on, "Preserve Transparency").changed() {
- f.insert("preserveTransparency".into(), json!(on));
- }
- });
-}
-
-/// The `mode` param naming a blend mode (`"normal"`, `"colorBurn"`…), which the engine parses.
-fn mode_key(m: photocraft_color::BlendMode) -> String {
- let s = format!("{m:?}");
- let mut c = s.chars();
- c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default()
+ crate::dialog_blend_ui::body(ui, f, "fill");
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 457a45376..ea332083e 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -1407,6 +1407,9 @@
Stroke Tah
Stroke Catch-up Dotahování tahu
Stroke: Tah:
+ Location Umístění
+ Location: Umístění:
+ Preserve Transparency Zachovat průhlednost
Style Styl
Style Options Možnosti stylu
Style Options… Možnosti stylu…
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 27a593929..4519a1826 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -1391,6 +1391,8 @@
Stroke Kontur
Stroke Catch-up Strich nachführen
Stroke: Kontur:
+ Location Position
+ Location: Position:
Style Stil
Style Options Stiloptionen
Style Options… Stiloptionen…
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 1bbd00a61..ed7284773 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -552,6 +552,7 @@
Middle Μέση
Position Θέση
Location Τοποθεσία
+ Location: Θέση:
Offset Μετατόπιση
Distance Απόσταση
Radius Ακτίνα
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index fed59e6ea..e72a69080 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1392,6 +1392,8 @@
Stroke Trazo
Stroke Catch-up Poner al día del trazo
Stroke: Trazo:
+ Location Ubicación
+ Location: Ubicación:
Style Estilo
Style Options Opciones de estilo
Style Options… Opciones de estilo…
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index c91df2180..25e7e1ecd 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -1376,6 +1376,7 @@
Stroke Contour
Stroke Catch-up Rattrapage du trait
Stroke: Contour :
+ Location: Emplacement :
Style Style
Style Options Options de style
Style Options… Options de style…
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 997674e30..e1215b511 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -1370,6 +1370,7 @@
Stroke Stroke
Stroke Catch-up Stroke Catch-up
Stroke: Stroke:
+ Location: Lokasi:
Style Gaya
Style Options Opsi Gaya
Style Options… Opsi Gaya…
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index b1b7a271b..8e0072b6c 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -1391,6 +1391,8 @@
Stroke Traccia
Stroke Catch-up Recupero traccia
Stroke: Traccia:
+ Location Posizione
+ Location: Posizione:
Style Stile
Style Options Opzioni stile
Style Options… Opzioni stile…
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index f1d73e360..d2df4fba5 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -1397,6 +1397,7 @@
Stroke 線
Stroke Catch-up ストロークの追従
Stroke: 線:
+ Location: 位置:
Style スタイル
Style Options スタイルオプション
Style Options… スタイルオプション…
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index faab7d238..89a06b610 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -1368,6 +1368,9 @@
Stroke 획
Stroke Catch-up 획 따라잡기
Stroke: 획:
+ Location 위치
+ Location: 위치:
+ Preserve Transparency 투명도 유지
Style 스타일
Style Options 스타일 옵션
Style Options… 스타일 옵션…
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index c66d60028..2db906632 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -2405,6 +2405,7 @@ cameraRaw Color Kleur
Degrees Graden
Middle Midden
Location Locatie
+ Location: Locatie:
Diameter Diameter
Intensity Intensiteit
Sensitivity Gevoeligheid
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index b13c74de0..e6337b779 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1391,6 +1391,7 @@
Stroke Obrys
Stroke Catch-up Dogonienie pociągnięcia
Stroke: Obrys:
+ Location: Położenie:
Style Styl
Style Options Opcje stylu
Style Options… Opcje stylu…
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 42611857d..53583057c 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -1375,6 +1375,7 @@
Stroke Traçado
Stroke Catch-up Recuperação do traço
Stroke: Traçado:
+ Location: Local:
Style Estilo
Style Options Opções de estilo
Style Options… Opções de estilo…
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index e567e423b..5e5c64140 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2093,6 +2093,9 @@
Stroke Мазок
Stroke Catch-up Догонять мазком
Stroke: Обводка:
+ Location: Расположение:
+ Inside Внутри
+ Outside Снаружи
Tetrahedral Тетраэдрическая
Texture Each Tip Текстура на каждый отпечаток
The current gradient (pick one in Window › Gradients) Текущий градиент (выберите в Окно › Градиенты)
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index a82b4e37d..8ba626bf0 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -1246,6 +1246,7 @@
Date Created Дата створення
City Місто
Location Розташування
+ Location: Розташування:
Province / State Область / штат
Country Країна
Byline Ім'я автора
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 7ded4bfcf..369b89f92 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1402,6 +1402,9 @@
Stroke 描边
Stroke Catch-up 笔触跟随
Stroke: 描边:
+ Location 位置
+ Location: 位置:
+ Preserve Transparency 保留透明区域
Style 样式
Style Options 样式选项
Style Options… 样式选项…
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 2aaf215ed..d3e009eb4 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1398,6 +1398,9 @@
Stroke 筆畫
Stroke Catch-up 筆畫追補
Stroke: 筆畫:
+ Location 位置
+ Location: 位置:
+ Preserve Transparency 保留透明區域
Style 樣式
Style Options 樣式選項
Style Options… 樣式選項…
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 5ce31d28f..1baf355bc 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -46,6 +46,7 @@ pub mod comps_ui;
pub mod control;
pub mod credits;
pub mod crop_ui;
+pub mod dialog_blend_ui;
pub mod dialogs;
pub mod direct_select;
pub mod discard_ui;
@@ -129,6 +130,7 @@ pub mod snap_ui;
pub mod state;
pub mod stroke_constraint;
pub mod stroke_trail;
+pub mod stroke_ui;
pub mod stylus;
pub mod swatches_ui;
mod tab_strip;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 37a9e9364..d7ce96f0a 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -347,6 +347,14 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
app.ui.dock_tabs.properties = 0;
Ok(r)
}
+ // Edit › Stroke…: open its full options dialog when called from menus/context
+ // menus. Explicit params from Actions, CLI, MCP and control channel execute directly.
+ crate::stroke_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => {
+ if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) {
+ return Err(why);
+ }
+ Ok(json!({"dialog": crate::stroke_ui::open(app)}))
+ }
// Photoshop's "Select and Mask…" is the engine's select.refineEdge.
// Select › Color Range… from the menu: the dialog (with params: the engine directly).
"select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::color_range_ui::open(app)})),
diff --git a/crates/ui-egui/src/stroke_ui.rs b/crates/ui-egui/src/stroke_ui.rs
new file mode 100644
index 000000000..76acbbaad
--- /dev/null
+++ b/crates/ui-egui/src/stroke_ui.rs
@@ -0,0 +1,116 @@
+//! Edit › Stroke…: a Photoshop-style options dialog for the existing `edit.stroke` command.
+//! The engine remains directly callable with parameters by CLI, MCP and Actions.
+
+use egui::{Align2, Sense, pos2, vec2};
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+pub const COMMAND: &str = "edit.stroke";
+const MARK: &str = "__stroke";
+const KEYS: [&str; 6] = ["width", "color", "location", "mode", "opacity", "preserveTransparency"];
+const LOCATIONS: [(&str, &str); 3] = [("inside", "Inside"), ("center", "Center"), ("outside", "Outside")];
+
+pub fn owns(fields: &Map<String, Value>) -> bool {
+ fields.contains_key(MARK)
+}
+
+fn hex(c: [f32; 4]) -> String {
+ let to_byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ format!("#{:02x}{:02x}{:02x}", to_byte(c[0]), to_byte(c[1]), to_byte(c[2]))
+}
+
+fn valid(key: &str, v: &Value) -> bool {
+ match key {
+ "width" => v.as_f64().is_some_and(|x| x.is_finite() && (1.0..=250.0).contains(&x)),
+ "color" => v.as_str().is_some_and(|h| h.len() == 7 && h.starts_with('#') && h[1..].bytes().all(|b| b.is_ascii_hexdigit())),
+ "location" => v.as_str().is_some_and(|s| LOCATIONS.iter().any(|(id, _)| *id == s)),
+ _ => crate::dialog_blend_ui::valid(key, v),
+ }
+}
+
+/// Construct a dialog from defaults and only valid, persisted preferences.
+pub fn fields(app: &PhotocraftApp) -> Map<String, Value> {
+ let mut f = Map::new();
+ f.insert(MARK.into(), json!(true));
+ f.insert("__command".into(), json!(COMMAND));
+ f.insert("__label".into(), json!("Stroke…"));
+ f.insert("width".into(), json!(1.0));
+ f.insert("color".into(), json!(hex(app.session.tools.foreground)));
+ f.insert("location".into(), json!("center"));
+ f.insert("mode".into(), json!("normal"));
+ f.insert("opacity".into(), json!(100.0));
+ f.insert("preserveTransparency".into(), json!(false));
+ if let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(COMMAND) {
+ for key in KEYS {
+ if let Some(value) = saved.get(key).filter(|v| valid(key, v)) {
+ f.insert(key.into(), value.clone());
+ }
+ }
+ }
+ f
+}
+
+pub fn open(app: &mut PhotocraftApp) -> u64 {
+ let f = fields(app);
+ app.ui.open_dialog(crate::state::DialogKind::Command, f)
+}
+
+/// Only Stroke params are passed to the engine; private UI markers are ignored.
+pub fn params(f: &Map<String, Value>) -> Value {
+ Value::Object(KEYS.iter().filter_map(|k| f.get(*k).map(|v| (k.to_string(), v.clone()))).collect())
+}
+
+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ let remembered = params(f);
+ let result = app.run(COMMAND, remembered.clone());
+ if result.is_ok() {
+ app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), remembered));
+ }
+ result
+}
+
+fn label(ui: &mut egui::Ui, text: &str) {
+ let t = Tokens::get(ui.ctx());
+ let (r, _) = ui.allocate_exact_size(vec2(112.0, 22.0), Sense::hover());
+ ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim);
+}
+
+pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ ui.spacing_mut().item_spacing.y = 6.0;
+ crate::widgets::section_label(ui, tl!("Stroke"));
+ crate::widgets::hairline(ui);
+ ui.horizontal(|ui| {
+ label(ui, tl!("Width:"));
+ let mut width = f.get("width").and_then(Value::as_f64).unwrap_or(1.0) as f32;
+ if crate::widgets::value_field(ui, &mut width, 1.0..=250.0, "px", 84.0).changed() {
+ f.insert("width".into(), json!(width.round()));
+ }
+ });
+ ui.horizontal(|ui| {
+ label(ui, tl!("Color:"));
+ let current = f.get("color").and_then(Value::as_str).unwrap_or("#000000");
+ let mut rgb = [1usize, 3, 5].map(|i| current.get(i..i + 2).and_then(|b| u8::from_str_radix(b, 16).ok()).unwrap_or(0));
+ if egui::color_picker::color_edit_button_srgb(ui, &mut rgb).changed() {
+ f.insert("color".into(), json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])));
+ }
+ });
+
+ ui.add_space(4.0);
+ crate::widgets::section_label(ui, tl!("Location"));
+ crate::widgets::hairline(ui);
+ ui.horizontal(|ui| {
+ label(ui, tl!("Location:"));
+ let mut location = f.get("location").and_then(Value::as_str).unwrap_or("center").to_string();
+ let opts: Vec<(String, &str)> = LOCATIONS.iter().map(|(key, label)| (key.to_string(), tl!(label))).collect();
+ if crate::widgets::dropdown(ui, "stroke-location", &mut location, &opts, 170.0) {
+ f.insert("location".into(), json!(location));
+ }
+ });
+ crate::dialog_blend_ui::body(ui, f, "stroke");
+}
+
+#[cfg(test)]
+#[path = "stroke_ui_tests.rs"]
+mod tests;
diff --git a/crates/ui-egui/src/stroke_ui_tests.rs b/crates/ui-egui/src/stroke_ui_tests.rs
new file mode 100644
index 000000000..0d673d2a5
--- /dev/null
+++ b/crates/ui-egui/src/stroke_ui_tests.rs
@@ -0,0 +1,151 @@
+use serde_json::json;
+
+use super::*;
+
+fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap();
+ app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap();
+ app
+}
+
+fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [f32; 4] {
+ let st = app.session.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
+}
+
+#[test]
+fn menu_and_canvas_invocations_open_options_but_explicit_params_run_directly() {
+ let mut app = app();
+ let ctx = egui::Context::default();
+ let opened = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap();
+ assert!(opened["dialog"].is_u64());
+ assert_eq!(app.ui.dialogs.len(), 1);
+ assert!(owns(&app.ui.dialogs[0].fields));
+ assert_eq!(app.session.active().unwrap().history.past_len(), 0);
+ app.ui.close_dialog(opened["dialog"].as_u64().unwrap());
+ let id = crate::dialogs::open_command_dialog(&mut app, COMMAND, "Stroke…");
+ assert!(owns(&app.ui.dialogs.last().unwrap().fields));
+ app.ui.close_dialog(id);
+
+ app.run("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
+ crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"width": 3, "location": "inside", "color": "#00ff00"})).unwrap();
+ assert!(app.ui.dialogs.is_empty(), "explicit params must not show a modal dialog");
+ assert!(pixel(&app, 10, 15)[1] > 0.98);
+
+ let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ assert!(crate::menus::invoke(&mut empty, &ctx, COMMAND, json!({})).is_err());
+ assert!(empty.ui.dialogs.is_empty());
+}
+
+#[test]
+fn stroke_choices_apply_on_confirm_and_cancel_does_not_modify_document() {
+ let mut app = app();
+ app.run("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap();
+ let initial = app.session.active().unwrap().history.past_len();
+ let cancelled = open(&mut app);
+ let dialog = app.ui.dialog_mut(cancelled).unwrap();
+ dialog.fields.insert("color".into(), json!("#00ff00"));
+ dialog.fields.insert("width".into(), json!(4.0));
+ app.ui.close_dialog(cancelled);
+ assert_eq!(app.session.active().unwrap().history.past_len(), initial);
+ assert_eq!(pixel(&app, 10, 15)[3], 0.0);
+
+ let applied = open(&mut app);
+ let d = app.ui.dialog_mut(applied).unwrap();
+ d.fields.insert("color".into(), json!("#00ff00"));
+ d.fields.insert("width".into(), json!(4.0));
+ d.fields.insert("location".into(), json!("inside"));
+ d.fields.insert("mode".into(), json!("normal"));
+ crate::dialogs::confirm(&mut app, applied).unwrap();
+ assert!(pixel(&app, 10, 15)[1] > 0.98, "inside edge receives selected green stroke");
+ assert_eq!(pixel(&app, 15, 15)[3], 0.0, "unselected interior unchanged");
+ assert_eq!(pixel(&app, 9, 15)[3], 0.0, "outside unchanged for Inside location");
+ assert_eq!(app.session.active().unwrap().history.past_len(), initial + 1);
+}
+
+#[test]
+fn preferences_remember_all_choices_and_reject_corrupt_values() {
+ let mut app = app();
+ let defaults = fields(&app);
+ assert_eq!(defaults["width"], 1.0);
+ assert_eq!(defaults["location"], "center");
+ assert_eq!(defaults["mode"], "normal");
+ assert_eq!(defaults["opacity"], 100.0);
+ assert_eq!(defaults["preserveTransparency"], false);
+
+ app.run("select.rect", json!({"x": 5, "y": 5, "width": 15, "height": 12})).unwrap();
+ let id = open(&mut app);
+ let d = app.ui.dialog_mut(id).unwrap();
+ for (key, value) in json!({
+ "width": 5,
+ "color": "#112233",
+ "location": "outside",
+ "mode": "multiply",
+ "opacity": 42,
+ "preserveTransparency": true
+ })
+ .as_object()
+ .unwrap()
+ {
+ d.fields.insert(key.clone(), value.clone());
+ }
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ let saved = app.session.prefs_to_json();
+ let mut restored = photocraft_engine::Session::new();
+ restored.load_prefs_json(&saved).unwrap();
+ let mut again = PhotocraftApp::new(restored, Default::default());
+ again.run("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap();
+ again.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
+ let remembered = fields(&again);
+ assert_eq!(remembered["width"], 5);
+ assert_eq!(remembered["color"], "#112233");
+ assert_eq!(remembered["location"], "outside");
+ assert_eq!(remembered["mode"], "multiply");
+ assert_eq!(remembered["opacity"], 42);
+ assert_eq!(remembered["preserveTransparency"], true);
+
+ again.session.prefs.edit(|p| {
+ p.dialogs.insert(
+ COMMAND.into(),
+ json!({
+ "width": -5, "color": "#nan", "location": "sideways",
+ "mode": "unrecognized", "opacity": "a lot", "preserveTransparency": 7
+ }),
+ )
+ });
+ let fallback = fields(&again);
+ for (key, value) in [
+ ("width", json!(1.0)),
+ ("color", json!("#ff0000")),
+ ("location", json!("center")),
+ ("mode", json!("normal")),
+ ("opacity", json!(100.0)),
+ ("preserveTransparency", json!(false)),
+ ] {
+ assert_eq!(fallback[key], value, "invalid persisted value {key} must be discarded");
+ }
+}
+
+#[test]
+fn command_params_do_not_leak_private_dialog_fields() {
+ let app = app();
+ let fields = fields(&app);
+ let out = params(&fields);
+ assert_eq!(out.as_object().unwrap().len(), 6);
+ assert!(out.get("__stroke").is_none());
+ assert!(out.get("__label").is_none());
+ assert_eq!(out["location"], "center");
+ assert_eq!(out["color"], "#ff0000");
+}
+
+#[test]
+fn stroke_dialog_labels_are_translated_in_every_catalog() {
+ const LABELS: &[&str] =
+ &["Stroke", "Width:", "Color:", "Location", "Location:", "Inside", "Center", "Outside", "Blending", "Mode:", "Opacity:", "Preserve Transparency"];
+ for lang in crate::i18n::Lang::all().filter(|lang| lang.complete_menus()) {
+ for label in LABELS {
+ assert!(crate::i18n::has(lang, label), "{} is missing Stroke dialog label: {label}", lang.code());
+ }
+ }
+}