Skip to content

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

Apply Type formatting to selected text layers (#2266)

Harrison O'Connor-Hooverec03c602b464
diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs
index dfbefdaf1..0cfc25696 100644
--- a/crates/engine/src/type_cmds.rs
+++ b/crates/engine/src/type_cmds.rs
@@ -454,6 +454,93 @@ fn with_text_layer<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&m
Ok(r)
}
+/// Direct formatting follows the selected Type layers, while an explicit layer or character
+/// range keeps its single-layer scope. Selected groups are not expanded.
+pub(crate) fn format_targets(s: &Session, p: &Value) -> Result<Vec<LayerId>> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let single = p.get("layer").is_some() || (p.get("range").is_some() && p.get("layers").is_none());
+ let ids = if single {
+ vec![layer_id(s, p)?]
+ } else if let Some(value) = p.get("layers") {
+ value
+ .as_array()
+ .ok_or_else(|| EngineError::Other("layers must be an array of layer IDs".into()))?
+ .iter()
+ .map(|v| v.as_u64().map(LayerId).ok_or_else(|| EngineError::Other("layers must contain layer IDs".into())))
+ .collect::<Result<Vec<_>>>()?
+ } else {
+ st.selected_layers()
+ };
+ let mut targets = Vec::new();
+ for id in ids {
+ let l = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ if matches!(l.content, LayerContent::Text(_)) {
+ if !targets.contains(&id) {
+ targets.push(id);
+ }
+ } else if single {
+ return Err(EngineError::Other(format!("layer {} is {} {} layer, not a type layer", id.0, l.content.article(), l.content.kind_name())));
+ }
+ }
+ if targets.is_empty() {
+ return Err(EngineError::Other("select a type layer".into()));
+ }
+ Ok(targets)
+}
+
+pub(crate) fn has_format_target(s: &Session) -> std::result::Result<(), String> {
+ format_targets(s, &Value::Null).map(|_| ()).map_err(|e| e.to_string())
+}
+
+/// One history step for a formatting batch. Structural text edits keep their singular helper.
+pub(crate) fn with_text_targets(
+ s: &mut Session,
+ p: &Value,
+ label: &str,
+ mut f: impl FnMut(&mut TextLayer, (usize, usize)) -> Result<()>,
+) -> Result<Vec<LayerId>> {
+ let ids = format_targets(s, p)?;
+ let damage = s.edit(label, |doc, _| {
+ let snapshot = doc.clone();
+ let mut damage = Some(photocraft_geom::Rect::EMPTY);
+ for id in &ids {
+ let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) else { return Err(EngineError::NoLayer(*id)) };
+ let before = t.cache.as_ref().map(|c| c.tile_bounds());
+ let range = if p.get("layers").is_none() || p.get("layer").is_some() { range_param(&t.text, p) } else { (0, t.text.len()) };
+ f(t, range)?;
+ refresh(&snapshot, t);
+ // An unknown old/new cache retains Session.edit's full-refresh fallback.
+ damage = damage.zip(before).zip(t.cache.as_ref().map(|c| c.tile_bounds())).map(|((all, a), b)| all.union(&a).union(&b));
+ }
+ Ok(damage)
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.last_damage = damage;
+ }
+ Ok(ids)
+}
+
+/// UI size/leading are measured after the layer transform; command callers otherwise use points.
+fn shown_style_params<'a>(t: &TextLayer, p: &'a Value) -> Result<std::borrow::Cow<'a, Value>> {
+ if p.get("metricsAsShown").and_then(Value::as_bool) != Some(true) {
+ return Ok(std::borrow::Cow::Borrowed(p));
+ }
+ let m = t.transform.m;
+ let scale = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() as f32;
+ let scale = if scale.is_finite() && scale > 1e-3 { f64::from(scale) } else { 1.0 };
+ let mut params = p.clone();
+ for key in ["size", "leading"] {
+ if let Some(value) = p.get(key).and_then(Value::as_f64) {
+ let value = value / scale;
+ if !value.is_finite() || value.abs() > f64::from(f32::MAX) {
+ return Err(bad("type.setStyle", "shown size and leading must convert to finite point values"));
+ }
+ params[key] = json!(value);
+ }
+ }
+ Ok(std::borrow::Cow::Owned(params))
+}
+
/// Whether a type layer still has the name it got from its text, so the name follows edits to
/// the text. A layer renamed to anything else keeps its name (#483).
pub(crate) fn is_auto_named(l: &Layer) -> bool {
@@ -705,21 +792,20 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: Box::leak(
- format!(r##"{{"layer":id?,"range":[startChar,endChar]? (default all), {CHAR_PARAMS}, paragraph keys: "align":"left|center|right|justify|justifyCenter|justifyRight|justifyAll","firstLineIndent":pt,"startIndent":pt,"endIndent":pt,"spaceBefore":pt,"spaceAfter":pt,"autoLeading":%,"direction":"auto|ltr|rtl","hyphenate":bool}}"##)
+ format!(r##"{{"layer":id? or "layers":[id,…]? (default selected Type layers),"range":[startChar,endChar]? (single layer; default all),"metricsAsShown":bool=false (size/leading include each layer's transform scale), {CHAR_PARAMS}, paragraph keys: "align":"left|center|right|justify|justifyCenter|justifyRight|justifyAll","firstLineIndent":pt,"startIndent":pt,"endIndent":pt,"spaceBefore":pt,"spaceAfter":pt,"autoLeading":%,"direction":"auto|ltr|rtl","hyphenate":bool}}"##)
.into_boxed_str(),
),
enabled: has_doc,
journal: true,
run: |s, p| {
- let id = layer_id(s, p)?;
check_kerning(p).map_err(|m| bad("type.setStyle", m))?;
- check_size_tracking(p).map_err(|m| bad("type.setStyle", m))?;
- with_text_layer(s, p, "Set Type Style", |t, _, _| {
- let (a, b) = range_param(&t.text, p);
+ let ids = with_text_targets(s, p, "Set Type Style", |t, (a, b)| {
+ let props = shown_style_params(t, p)?;
+ check_size_tracking(&props).map_err(|m| bad("type.setStyle", m))?;
let mut probe = CharStyle::default();
- if apply_char_props(&mut probe, p) {
+ if apply_char_props(&mut probe, &props) {
style_range(t, a, b, &|st| {
- apply_char_props(st, p);
+ apply_char_props(st, &props);
});
}
let mut pprobe = ParagraphStyle::default();
@@ -730,6 +816,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
Ok(())
})?;
+ let id = ids.first().ok_or_else(|| EngineError::Other("select a type layer".into()))?;
info(s, &json!({ "layer": id.0 }))
},
},
diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rs
index 78c463d46..1ca11526a 100644
--- a/crates/engine/src/type_extra_cmds.rs
+++ b/crates/engine/src/type_extra_cmds.rs
@@ -14,7 +14,7 @@ use photocraft_text::render::PathEl;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, layer_param};
-use crate::type_cmds::{is_auto_named, layer_name, refresh, replace_text, style_paragraphs, style_range};
+use crate::type_cmds::{format_targets, has_format_target, is_auto_named, layer_name, refresh, replace_text, style_paragraphs, style_range, with_text_targets};
use crate::{EngineError, Result, Session};
/// Photoshop's Paste Lorem Ipsum filler.
@@ -58,7 +58,7 @@ fn any_text(s: &Session) -> std::result::Result<(), String> {
}
fn has_defaults(s: &Session) -> std::result::Result<(), String> {
- has_text(s)?;
+ has_format_target(s)?;
s.type_defaults.as_ref().map(|_| ()).ok_or_else(|| "no default type styles have been saved".into())
}
@@ -121,7 +121,7 @@ pub fn aa_name(a: AntiAlias) -> &'static str {
}
fn set_aa(s: &mut Session, p: &Value, aa: AntiAlias) -> Result<Value> {
- with_text(s, p, "Anti-Alias", |t, _| {
+ with_text_targets(s, p, "Anti-Alias", |t, _| {
t.antialias = aa;
Ok(())
})?;
@@ -129,7 +129,7 @@ fn set_aa(s: &mut Session, p: &Value, aa: AntiAlias) -> Result<Value> {
}
fn set_orientation(s: &mut Session, p: &Value, o: Orientation) -> Result<Value> {
- with_text(s, p, "Change Text Orientation", |t, _| {
+ with_text_targets(s, p, "Change Text Orientation", |t, _| {
t.orientation = o;
Ok(())
})?;
@@ -334,8 +334,8 @@ fn warp_text(s: &mut Session, p: &Value) -> Result<Value> {
horizontal: p.get("orientation").and_then(Value::as_str) != Some("vertical"),
});
let out = json!({"warp": warp});
- with_text(s, p, "Warp Text", |t, _| {
- t.warp = warp;
+ with_text_targets(s, p, "Warp Text", |t, _| {
+ t.warp = warp.clone();
Ok(())
})?;
Ok(out)
@@ -366,13 +366,14 @@ fn set_feature(st: &mut photocraft_doc::text::CharStyle, tag: &str, on: bool) {
}
fn toggle_opentype(s: &mut Session, p: &Value, tag: &'static str) -> Result<Value> {
- let cur = active_text(s).ok().and_then(|t| t.char_runs().first().map(|r| feature_on(&r.style, tag))).unwrap_or(false);
+ let ids = format_targets(s, p)?;
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let representative = st.active_layer.filter(|id| ids.contains(id)).or_else(|| ids.first().copied());
+ let cur = representative
+ .and_then(|id| st.doc.layer(id))
+ .is_some_and(|l| matches!(&l.content, LayerContent::Text(t) if t.char_runs().first().is_some_and(|r| feature_on(&r.style, tag))));
let on = p.get("on").and_then(Value::as_bool).unwrap_or(!cur);
- with_text(s, p, "Change OpenType Feature", |t, _| {
- let (a, b) = match p.get("range").and_then(Value::as_array) {
- Some(r) if r.len() == 2 => (byte_index(&t.text, r[0].as_u64().unwrap_or(0) as usize), byte_index(&t.text, r[1].as_u64().unwrap_or(0) as usize)),
- _ => (0, t.text.len()),
- };
+ with_text_targets(s, p, "Change OpenType Feature", |t, (a, b)| {
style_range(t, a.min(b), a.max(b), &|st| set_feature(st, tag, on));
Ok(())
})?;
@@ -496,7 +497,7 @@ fn save_defaults(s: &mut Session) -> Result<Value> {
fn load_defaults(s: &mut Session, p: &Value) -> Result<Value> {
let (c, pp) = s.type_defaults.clone().ok_or(EngineError::Other("no default type styles have been saved".into()))?;
- with_text(s, p, "Load Default Type Styles", |t, _| {
+ with_text_targets(s, p, "Load Default Type Styles", |t, _| {
let n = t.text.len();
style_range(t, 0, n, &|st| *st = c.clone());
style_paragraphs(t, 0, n, &|st| *st = pp.clone());
@@ -514,27 +515,36 @@ pub fn specs() -> Vec<CommandSpec> {
};
}
const LP: &str = r##"{"layer":id?}"##;
- const OT: &str = r##"{"layer":id?,"on":bool? (default: toggle),"range":[startChar,endChar]? (default all)}"##;
+ const FP: &str = r##"{"layer":id? or "layers":[id,…]? (default selected Type layers)}"##;
+ const OT: &str = r##"{"layer":id? or "layers":[id,…]? (default selected Type layers),"on":bool? (default: toggle representative),"range":[startChar,endChar]? (single layer; default all)}"##;
vec![
- spec!("type.antiAlias.none", "None", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::None)),
- spec!("type.antiAlias.sharp", "Sharp", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Sharp)),
- spec!("type.antiAlias.crisp", "Crisp", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Crisp)),
- spec!("type.antiAlias.strong", "Strong", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Strong)),
- spec!("type.antiAlias.smooth", "Smooth", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Smooth)),
- spec!("type.antiAlias.windowsLcd", "Windows LCD", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::WindowsLcd)),
- spec!("type.antiAlias.windows", "Windows", &["Type", "Anti-Alias"], LP, has_text, |s, p| set_aa(s, p, AntiAlias::Windows)),
- spec!("type.orientation.horizontal", "Horizontal", &["Type", "Orientation"], LP, has_text, |s, p| set_orientation(s, p, Orientation::Horizontal)),
- spec!("type.orientation.vertical", "Vertical", &["Type", "Orientation"], LP, has_text, |s, p| set_orientation(s, p, Orientation::Vertical)),
- spec!("type.openType.standardLigatures", "Standard Ligatures", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "liga")),
- spec!("type.openType.contextualAlternates", "Contextual Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "calt")),
- spec!("type.openType.discretionaryLigatures", "Discretionary Ligatures", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "dlig")),
- spec!("type.openType.swash", "Swash", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "swsh")),
- spec!("type.openType.oldstyle", "Oldstyle", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "onum")),
- spec!("type.openType.stylisticAlternates", "Stylistic Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "salt")),
- spec!("type.openType.titlingAlternates", "Titling Alternates", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "titl")),
- spec!("type.openType.ornaments", "Ornaments", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "ornm")),
- spec!("type.openType.ordinals", "Ordinals", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "ordn")),
- spec!("type.openType.fractions", "Fractions", &["Type", "OpenType"], OT, has_text, |s, p| toggle_opentype(s, p, "frac")),
+ spec!("type.antiAlias.none", "None", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::None)),
+ spec!("type.antiAlias.sharp", "Sharp", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::Sharp)),
+ spec!("type.antiAlias.crisp", "Crisp", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::Crisp)),
+ spec!("type.antiAlias.strong", "Strong", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::Strong)),
+ spec!("type.antiAlias.smooth", "Smooth", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::Smooth)),
+ spec!("type.antiAlias.windowsLcd", "Windows LCD", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::WindowsLcd)),
+ spec!("type.antiAlias.windows", "Windows", &["Type", "Anti-Alias"], FP, has_format_target, |s, p| set_aa(s, p, AntiAlias::Windows)),
+ spec!("type.orientation.horizontal", "Horizontal", &["Type", "Orientation"], FP, has_format_target, |s, p| set_orientation(
+ s,
+ p,
+ Orientation::Horizontal
+ )),
+ spec!("type.orientation.vertical", "Vertical", &["Type", "Orientation"], FP, has_format_target, |s, p| set_orientation(s, p, Orientation::Vertical)),
+ spec!("type.openType.standardLigatures", "Standard Ligatures", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "liga")),
+ spec!("type.openType.contextualAlternates", "Contextual Alternates", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(
+ s, p, "calt"
+ )),
+ spec!("type.openType.discretionaryLigatures", "Discretionary Ligatures", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(
+ s, p, "dlig"
+ )),
+ spec!("type.openType.swash", "Swash", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "swsh")),
+ spec!("type.openType.oldstyle", "Oldstyle", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "onum")),
+ spec!("type.openType.stylisticAlternates", "Stylistic Alternates", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "salt")),
+ spec!("type.openType.titlingAlternates", "Titling Alternates", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "titl")),
+ spec!("type.openType.ornaments", "Ornaments", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "ornm")),
+ spec!("type.openType.ordinals", "Ordinals", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "ordn")),
+ spec!("type.openType.fractions", "Fractions", &["Type", "OpenType"], OT, has_format_target, |s, p| toggle_opentype(s, p, "frac")),
spec!("type.createWorkPath", "Create Work Path", &["Type"], LP, has_text, create_work_path),
spec!("type.convertToShape", "Convert to Shape", &["Type"], LP, has_text, convert_to_shape),
spec!("type.rasterizeTypeLayer", "Rasterize Type Layer", &["Type"], LP, has_text, |s, p| s.execute("type.rasterize", p.clone())),
@@ -544,8 +554,8 @@ pub fn specs() -> Vec<CommandSpec> {
"type.warpText",
"Warp Text…",
&["Type"],
- r##"{"layer":id?,"style":"none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist"="arc","bend":-100..100=50,"horizontalDistortion":-100..100=0,"verticalDistortion":-100..100=0,"orientation":"horizontal|vertical"="horizontal"}"##,
- has_text,
+ r##"{"layer":id? or "layers":[id,…]? (default selected Type layers),"style":"none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist"="arc","bend":-100..100=50,"horizontalDistortion":-100..100=0,"verticalDistortion":-100..100=0,"orientation":"horizontal|vertical"="horizontal"}"##,
+ has_format_target,
warp_text
),
spec!("type.updateAllTextLayers", "Update All Text Layers", &["Type"], "{}", any_text, |s, _| update_all(s)),
@@ -578,7 +588,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_text,
|s, _| save_defaults(s)
),
- spec!("type.loadDefaultTypeStyles", "Load Default Type Styles", &["Type"], LP, has_defaults, load_defaults),
+ spec!("type.loadDefaultTypeStyles", "Load Default Type Styles", &["Type"], FP, has_defaults, load_defaults),
]
}
diff --git a/crates/engine/tests/type_format_targets.rs b/crates/engine/tests/type_format_targets.rs
new file mode 100644
index 000000000..54e7d3f8a
--- /dev/null
+++ b/crates/engine/tests/type_format_targets.rs
@@ -0,0 +1,236 @@
+//! Direct formatting applies only the requested properties to every selected Type layer.
+
+use photocraft_doc::text::{AntiAlias, Caps, CharStyle, Kerning, Orientation, TextAlign};
+use photocraft_doc::{LayerContent, LayerId, TextLayer};
+use photocraft_engine::Session;
+use serde_json::{Value, json};
+
+fn text(s: &Session, id: LayerId) -> TextLayer {
+ let LayerContent::Text(t) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("not type") };
+ t.clone()
+}
+
+fn select(s: &mut Session, ids: &[LayerId]) {
+ for (i, id) in ids.iter().enumerate() {
+ s.execute("layer.select", json!({"layer": id.0, "mode": if i == 0 { "replace" } else { "add" }})).unwrap();
+ }
+}
+
+fn fixture() -> (Session, Vec<LayerId>, LayerId) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 400, "height": 240, "background": "white"})).unwrap();
+ let raster = s.active().unwrap().active_layer.unwrap();
+ let mut ids = Vec::new();
+ for (i, (size, weight, italic, kern)) in
+ [(50, 400, false, 0), (30, 700, false, 0), (20, 400, true, -100), (10, 400, false, -50), (18, 600, false, 25)].into_iter().enumerate()
+ {
+ let id = s
+ .execute(
+ "type.create",
+ json!({"text": "AéBC", "x": 20 + i * 55, "y": 80, "size": size, "font": "Inter", "weight": weight, "italic": italic, "kerning": kern}),
+ )
+ .unwrap()["layer"]
+ .as_u64()
+ .unwrap();
+ s.execute("type.setStyle", json!({"layer": id, "range": [1, 3], "tracking": 30 + i, "underline": i % 2 == 0})).unwrap();
+ ids.push(LayerId(id));
+ }
+ (s, ids, raster)
+}
+
+fn assert_styles(actual: &TextLayer, expected: &TextLayer) {
+ assert_eq!(actual.runs, expected.runs);
+ assert_eq!(actual.paragraphs, expected.paragraphs);
+ assert_eq!(actual.text, expected.text);
+ assert_eq!(actual.transform, expected.transform);
+ assert_eq!(actual.shape, expected.shape);
+}
+
+#[test]
+fn selected_type_properties_preserve_each_layers_other_attributes_and_one_history_step() {
+ let (mut s, ids, raster) = fixture();
+ type StyleCase<'a> = (&'a [usize], Value, fn(&mut CharStyle));
+ let cases: [StyleCase<'_>; 4] = [
+ (&[0, 2], json!({"font": "New Family"}), |st| {
+ st.font_family = "New Family".into();
+ st.postscript_name = None;
+ }),
+ (&[1, 3], json!({"kerning": 50}), |st| {
+ st.kerning = Kerning::Off;
+ st.kern = 50.0;
+ }),
+ (&[0, 1, 2, 3], json!({"font": "Another Family"}), |st| {
+ st.font_family = "Another Family".into();
+ st.postscript_name = None;
+ }),
+ (&[1, 2, 3], json!({"size": 35}), |st| st.size_pt = 35.0),
+ ];
+ for (indices, params, change) in cases {
+ let mut selected: Vec<_> = indices.iter().map(|i| ids[*i]).collect();
+ selected.push(raster); // The primary layer need not be Type.
+ select(&mut s, &selected);
+ let target = (s.active().unwrap().active_layer, s.active().unwrap().selected_layers());
+ let before: Vec<_> = ids.iter().map(|id| text(&s, *id)).collect();
+ let steps = s.active().unwrap().history.entries().len();
+ s.execute("type.setStyle", params).unwrap();
+ assert_eq!(s.active().unwrap().history.entries().len(), steps + 1);
+ assert_eq!((s.active().unwrap().active_layer, s.active().unwrap().selected_layers()), target);
+ for (i, id) in ids.iter().enumerate() {
+ let mut expected = before[i].clone();
+ if indices.contains(&i) {
+ for run in &mut expected.runs {
+ change(&mut run.style);
+ }
+ }
+ let actual = text(&s, *id);
+ assert_styles(&actual, &expected);
+ if indices.contains(&i) {
+ assert_ne!(actual.psd_raw, before[i].psd_raw, "editable PSD data refreshed");
+ let damage = s.active().unwrap().last_damage.unwrap();
+ for t in [&before[i], &actual] {
+ let bounds = t.cache.as_ref().unwrap().tile_bounds();
+ assert_eq!(damage.intersect(&bounds), bounds);
+ }
+ }
+ }
+ assert!(s.undo());
+ for (id, old) in ids.iter().zip(&before) {
+ assert_styles(&text(&s, *id), old);
+ }
+ assert!(s.redo());
+ assert_eq!((s.active().unwrap().active_layer, s.active().unwrap().selected_layers()), target);
+ }
+}
+
+#[test]
+fn explicit_type_layer_ranges_and_batch_paragraph_properties_keep_their_scope() {
+ let (mut s, ids, raster) = fixture();
+ select(&mut s, &ids[..4]);
+ let before: Vec<_> = ids.iter().map(|id| text(&s, *id)).collect();
+ s.execute("type.setStyle", json!({"layer": ids[0].0, "range": [1, 3], "fauxBold": true})).unwrap();
+ let changed = text(&s, ids[0]);
+ assert!(!changed.runs[0].style.faux_bold);
+ assert!(changed.runs[1].style.faux_bold);
+ assert!(!changed.runs[2].style.faux_bold);
+ for i in 1..ids.len() {
+ assert_styles(&text(&s, ids[i]), &before[i]);
+ }
+ assert!(s.undo());
+ s.execute("type.setStyle", json!({"layers": [ids[0].0, ids[1].0, ids[0].0, raster.0], "caps": "all", "fauxItalic": true, "horizontalScale": 120, "align": "center", "firstLineIndent": 7, "hyphenate": false})).unwrap();
+ for (i, id) in ids.iter().enumerate() {
+ let mut expected = before[i].clone();
+ if i < 2 {
+ for run in &mut expected.runs {
+ run.style.caps = Caps::AllCaps;
+ run.style.faux_italic = true;
+ run.style.horizontal_scale = 1.2;
+ }
+ for para in &mut expected.paragraphs {
+ para.style.align = TextAlign::Center;
+ para.style.first_line_indent_pt = 7.0;
+ para.style.hyphenate = false;
+ }
+ }
+ assert_styles(&text(&s, *id), &expected);
+ }
+}
+
+#[test]
+fn shown_type_metrics_convert_per_target_coalesce_and_fail_atomically() {
+ let (mut s, ids, _) = fixture();
+ s.execute("type.edit", json!({"layer": ids[0].0, "transform": [2, 0, 0, 2, 20, 80]})).unwrap();
+ s.execute("type.edit", json!({"layer": ids[1].0, "transform": [0.5, 0, 0, 0.5, 75, 80]})).unwrap();
+ select(&mut s, &ids[..2]);
+ let before = [text(&s, ids[0]), text(&s, ids[1])];
+ let steps = s.active().unwrap().history.entries().len();
+ for size in [24, 30] {
+ s.execute("type.setStyle", json!({"metricsAsShown": true, "size": size, "leading": 40, "coalesce": "batch-size"})).unwrap();
+ }
+ for (i, scale) in [2.0, 0.5].into_iter().enumerate() {
+ let t = text(&s, ids[i]);
+ assert!(t.runs.iter().all(|r| r.style.size_pt == 30.0 / scale && r.style.leading_pt == Some(40.0 / scale)));
+ assert_eq!(t.transform, before[i].transform);
+ }
+ assert_eq!(s.active().unwrap().history.entries().len(), steps + 1);
+ assert!(s.undo());
+ for i in 0..2 {
+ assert_styles(&text(&s, ids[i]), &before[i]);
+ }
+ assert!(s.redo());
+ let unchanged = [text(&s, ids[0]), text(&s, ids[1])];
+ let revision = s.active().unwrap().revision;
+ let steps = s.active().unwrap().history.entries().len();
+ // The second target would exceed the existing 1296pt limit after conversion.
+ assert!(s.execute("type.setStyle", json!({"metricsAsShown": true, "size": 700})).is_err());
+ assert_eq!(s.active().unwrap().revision, revision);
+ assert_eq!(s.active().unwrap().history.entries().len(), steps);
+ for i in 0..2 {
+ assert_styles(&text(&s, ids[i]), &unchanged[i]);
+ }
+ s.execute("type.setStyle", json!({"size": 22, "leading": 26})).unwrap();
+ for id in &ids[..2] {
+ assert!(text(&s, *id).runs.iter().all(|r| r.style.size_pt == 22.0 && r.style.leading_pt == Some(26.0)));
+ }
+}
+
+#[test]
+fn direct_type_formatting_menu_routes_batch_without_enabling_structural_commands() {
+ let (mut s, ids, raster) = fixture();
+ s.execute("type.saveDefaultTypeStyles", json!({})).unwrap();
+ let defaults = text(&s, ids[4]);
+ select(&mut s, &[ids[0], ids[1], raster]);
+ for (command, params) in [
+ ("type.antiAlias.crisp", json!({})),
+ ("type.orientation.vertical", json!({})),
+ ("type.openType.fractions", json!({"on": true})),
+ ("type.warpText", json!({"style": "arc", "bend": 15})),
+ ("type.loadDefaultTypeStyles", json!({})),
+ ] {
+ assert!(s.is_enabled(command), "{command} supports selected Type peers");
+ assert!(!s.is_enabled("type.convertToShape"));
+ let before: Vec<_> = ids.iter().map(|id| text(&s, *id)).collect();
+ let steps = s.active().unwrap().history.entries().len();
+ s.execute(command, params).unwrap();
+ assert_eq!(s.active().unwrap().history.entries().len(), steps + 1);
+ for (i, id) in ids.iter().enumerate() {
+ let actual = text(&s, *id);
+ let mut expected = before[i].clone();
+ if i < 2 {
+ match command {
+ "type.antiAlias.crisp" => expected.antialias = AntiAlias::Crisp,
+ "type.orientation.vertical" => expected.orientation = Orientation::Vertical,
+ "type.openType.fractions" => {
+ for run in &mut expected.runs {
+ run.style.features.push(photocraft_doc::text::FontFeature { tag: "frac".into(), value: 1 });
+ }
+ }
+ "type.warpText" => {
+ assert_eq!(actual.warp.as_ref().unwrap().value, 15.0);
+ expected.warp = actual.warp.clone();
+ }
+ _ => {
+ expected.runs = vec![photocraft_doc::text::TextRun { len: expected.text.len(), style: defaults.runs[0].style.clone() }];
+ expected.paragraphs = defaults.paragraphs.clone();
+ }
+ }
+ }
+ assert_styles(&actual, &expected);
+ assert_eq!(actual.antialias, expected.antialias);
+ assert_eq!(actual.orientation, expected.orientation);
+ assert_eq!(actual.warp, expected.warp);
+ }
+ assert!(s.undo());
+ }
+}
+
+#[test]
+fn invalid_explicit_type_targets_leave_the_whole_batch_unchanged() {
+ let (mut s, ids, _) = fixture();
+ let before = text(&s, ids[0]);
+ let revision = s.active().unwrap().revision;
+ for params in [json!({"layers": [ids[0].0, u64::MAX], "size": 40}), json!({"layers": [ids[0].0, "bad"], "size": 40})] {
+ assert!(s.execute("type.setStyle", params).is_err());
+ assert_eq!(s.active().unwrap().revision, revision);
+ assert_styles(&text(&s, ids[0]), &before);
+ }
+}
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 319f71bfd..03db139ca 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -358,6 +358,24 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
"layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => {
crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string())
}
+ // Formatting menus follow an inline text selection when editing. Outside an edit,
+ // snapshot the selected type layers; explicit automation targets retain their scope.
+ t if (t.starts_with("type.antiAlias.")
+ || t.starts_with("type.orientation.")
+ || t.starts_with("type.openType.")
+ || matches!(t, "type.warpText" | "type.loadDefaultTypeStyles"))
+ && params.get("layer").is_none()
+ && params.get("layers").is_none()
+ && params.get("range").is_none() =>
+ {
+ let Some(mut p) = crate::type_tool::formatting_params(app) else { return app.run(id, params) };
+ if let Some(props) = params.as_object() {
+ for (key, value) in props {
+ p[key] = value.clone();
+ }
+ }
+ app.run(id, p)
+ }
"type.editText" => {
crate::type_tool::edit_active(app)?;
if let Some(focus) = ctx.memory(|m| m.focused()) {
diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs
index 27584a189..0e0317560 100644
--- a/crates/ui-egui/src/type_tool.rs
+++ b/crates/ui-egui/src/type_tool.rs
@@ -878,15 +878,34 @@ pub(crate) fn family_picker_in(ui: &mut egui::Ui, salt: &str, current: &mut Stri
changed
}
-/// The type layer the options bar edits: the one being edited, else the active layer if it is type.
+/// Representative for the displayed properties: the edit layer, else a selected type layer.
fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> {
if let Some(ed) = &app.ui.text_edit {
let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));
return Some((ed.layer, (a < b).then_some([a, b])));
}
let st = app.session.active()?;
- let id = st.active_layer?;
- text_layer(&st.doc, id).map(|_| (id.0, None))
+ let id = st
+ .active_layer
+ .filter(|id| text_layer(&st.doc, *id).is_some())
+ .or_else(|| st.selected_layers().into_iter().find(|id| text_layer(&st.doc, *id).is_some()))?;
+ Some((id.0, None))
+}
+
+/// Snapshot the mutation scope separately from the representative used to display properties.
+/// An inline edit remains on its layer/range; layer selection formats every selected type layer.
+pub(crate) fn formatting_params(app: &PhotocraftApp) -> Option<serde_json::Value> {
+ if let Some(ed) = &app.ui.text_edit {
+ let mut params = json!({"layer": ed.layer, "coalesce": ed.session});
+ let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor));
+ if a < b {
+ params["range"] = json!([a, b]);
+ }
+ return Some(params);
+ }
+ let st = app.session.active()?;
+ let layers: Vec<u64> = st.selected_layers().into_iter().filter(|id| text_layer(&st.doc, *id).is_some()).map(|id| id.0).collect();
+ (!layers.is_empty()).then(|| json!({"layers": layers}))
}
/// Scale of the target layer's transform. Like Photoshop, sizes show and edit as the layer
@@ -907,14 +926,13 @@ fn drag_key(ctx: &egui::Context) -> Option<String> {
Some(format!("type-drag-{}-{}", id.value(), t.to_bits()))
}
-/// Apply character/paragraph properties to the target (selection, else whole layer) and remember
-/// them as tool defaults.
+/// Apply only the supplied properties to the text-edit scope or selected type layers.
fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_json::Value) {
- let Some((layer, range)) = target(app) else { return };
- let mut p = props;
- p["layer"] = json!(layer);
- if let Some(r) = range {
- p["range"] = json!(r);
+ let Some(mut p) = formatting_params(app) else { return };
+ if let Some(props) = props.as_object() {
+ for (key, value) in props {
+ p[key] = value.clone();
+ }
}
if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()).or_else(|| drag_key(ctx)) {
p["coalesce"] = json!(key);
@@ -925,14 +943,7 @@ fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_json::Value)
/// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling
/// the dialog never changes the text selection, tool colours, or document history.
pub fn open_color_picker(app: &mut PhotocraftApp, rgb: [f32; 3]) -> u64 {
- if let Some((layer, range)) = target(app) {
- let mut params = json!({"layer": layer});
- if let Some(range) = range {
- params["range"] = json!(range);
- }
- if let Some(ed) = &app.ui.text_edit {
- params["coalesce"] = json!(ed.session);
- }
+ if let Some(params) = formatting_params(app) {
crate::color_picker_ui::open_for_command(app, "Color Picker (Text Color)", rgb, "type.setStyle", params)
} else {
crate::color_picker_ui::open(app, "foreground")
@@ -967,9 +978,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
};
if crate::icons::button(ui, "text-cursor", 24.0, false, tl!("Toggle text orientation")).clicked()
&& let Some((layer, _)) = target(app)
+ && let Some(params) = formatting_params(app)
{
let to = if is_vertical(app, LayerId(layer)) { "horizontal" } else { "vertical" };
- if let Err(e) = app.run(&format!("type.orientation.{to}"), json!({"layer": layer})) {
+ if let Err(e) = app.run(&format!("type.orientation.{to}"), params) {
app.ui.status = e;
app.ui.status_error = true;
}
@@ -979,7 +991,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let st = styles(&fam);
style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) };
app.ui.tool_options.type_style = style.clone();
- apply(app, ui.ctx(), json!({"font": fam, "fontStyle": style}));
+ apply(app, ui.ctx(), json!({"font": fam}));
}
let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), style_label(&s))).collect();
let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();
@@ -991,10 +1003,12 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::icons::paint(ui, r, "type", 13.0, t.icon);
if crate::widgets::value_field(ui, &mut size, 1.0..=1296.0, "pt", 66.0).changed() {
app.ui.tool_options.type_size = size;
- let k = shown_scale(app);
- apply(app, ui.ctx(), json!({"size": size / k}));
+ apply(app, ui.ctx(), json!({"size": size, "metricsAsShown": true}));
}
- let mut aa = o.type_aa.clone();
+ let mut aa = target(app)
+ .and_then(|(id, _)| app.session.active().and_then(|st| text_layer(&st.doc, LayerId(id))))
+ .map(|t| photocraft_engine::type_extra_cmds::aa_name(t.antialias).to_string())
+ .unwrap_or_else(|| o.type_aa.clone());
let aa_opts = [
("none".to_string(), tl!("None")),
("sharp".to_string(), tl!("Sharp")),
@@ -1004,12 +1018,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
];
if crate::widgets::dropdown(ui, "type-aa", &mut aa, &aa_opts, 80.0) {
app.ui.tool_options.type_aa = aa.clone();
- if let Some((layer, _)) = target(app) {
- let mut p = json!({"layer": layer, "antialias": aa});
- if let Some(ed) = &app.ui.text_edit {
- p["coalesce"] = json!(ed.session);
- }
- let _ = app.run("type.edit", p);
+ if let Some(params) = formatting_params(app) {
+ let _ = app.run(&format!("type.antiAlias.{aa}"), params);
}
}
crate::widgets::vline(ui, 22.0);
@@ -1278,9 +1288,7 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa
row(ui, &mut |ui| {
if font_picker(ui, &mut fam, full) {
app.ui.tool_options.type_font = fam.clone();
- let st = styles(&fam);
- let style = if st.contains(&c.font_style) { c.font_style.clone() } else { st.first().cloned().unwrap_or_else(|| tl!("Regular").into()) };
- apply(app, ui.ctx(), json!({"font": fam, "fontStyle": style}));
+ apply(app, ui.ctx(), json!({"font": fam}));
}
});
row(ui, &mut |ui| {
@@ -1295,11 +1303,11 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa
let k = shown_scale(app);
if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k, 0.1..=1296.0, "pt", w) {
app.ui.tool_options.type_size = v;
- apply(app, ui.ctx(), json!({"size": v / k}));
+ apply(app, ui.ctx(), json!({"size": v, "metricsAsShown": true}));
}
let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k;
if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead, 0.1..=5000.0, "pt", w) {
- apply(app, ui.ctx(), json!({"leading": v / k}));
+ apply(app, ui.ctx(), json!({"leading": v, "metricsAsShown": true}));
}
});
row(ui, &mut |ui| {
@@ -1516,7 +1524,8 @@ fn type_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
});
ui.add_space(crate::theme::ROW_GAP);
if let Some(id) = run
- && let Err(e) = app.run(&id, json!({}))
+ && let Some(params) = formatting_params(app)
+ && let Err(e) = app.run(&id, params)
{
app.ui.status = e;
app.ui.status_error = true;
diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs
index 6936f9c84..d1049cf29 100644
--- a/crates/ui-egui/src/type_tool_tests.rs
+++ b/crates/ui-egui/src/type_tool_tests.rs
@@ -489,6 +489,8 @@ fn command_t_while_typing_toggles_the_character_panel() {
fn text_color_dialog_edits_only_the_selected_range_and_cancel_is_inert() {
let mut app = new_app();
let id = LayerId(app.run("type.create", json!({"text":"Hello world","size":40,"color":"#000000"})).unwrap()["layer"].as_u64().unwrap());
+ let peer = LayerId(app.run("type.create", json!({"text":"Selected peer","color":"#000000"})).unwrap()["layer"].as_u64().unwrap());
+ app.run("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();
app.ui.text_edit = Some(crate::state::TextEdit {
layer: id.0,
caret: 11,
@@ -523,6 +525,7 @@ fn text_color_dialog_edits_only_the_selected_range_and_cancel_is_inert() {
app.ui.dialogs.last_mut().unwrap().fields.insert("color".into(), json!("#0000ff"));
crate::dialogs::confirm(&mut app, dialog).unwrap();
assert_eq!(app.session.active().unwrap().history.entries().len(), before + 1, "one editing-session undo step");
+ assert_eq!(rgb_at(&app, peer, 0), [0, 0, 0, 255], "a selected peer is outside the active text edit");
}
#[test]
@@ -1194,3 +1197,268 @@ fn the_font_menu_lists_served_families() {
photocraft_text::served::add_families(["Served Menu Test Serif".to_string()]);
assert!(super::families().iter().any(|f| f == "Served Menu Test Serif"));
}
+
+/// #2236: formatting applies to the selected type layers, while an active text edit stays local.
+mod multi_layer_formatting {
+ use super::*;
+ use egui::accesskit::Role;
+ use photocraft_doc::text::{AntiAlias, CharStyle, Orientation, TextAlign};
+
+ fn selected(app: &mut PhotocraftApp, ids: &[LayerId]) {
+ for (i, id) in ids.iter().enumerate() {
+ app.run("layer.select", json!({"layer": id.0, "mode": if i == 0 { "replace" } else { "add" }})).unwrap();
+ }
+ }
+
+ fn fixture() -> (PhotocraftApp, [LayerId; 3]) {
+ let mut app = new_app();
+ let ids = std::array::from_fn(|i| {
+ LayerId(
+ app.run("type.create", json!({"text": "AéBCD", "font": "Inter", "size": 12 + i * 4, "color": "#000000"})).unwrap()["layer"].as_u64().unwrap(),
+ )
+ });
+ app.run("type.setStyle", json!({"layer": ids[0].0, "fontStyle": "Bold Italic", "tracking": 20})).unwrap();
+ selected(&mut app, &ids[..2]);
+ (app, ids)
+ }
+
+ fn style(app: &PhotocraftApp, id: LayerId, ci: usize) -> CharStyle {
+ let t = text(app, id);
+ let byte = t.text.char_indices().nth(ci).unwrap().0;
+ let mut end = 0;
+ t.char_runs()
+ .into_iter()
+ .find(|r| {
+ end += r.len;
+ byte < end
+ })
+ .unwrap()
+ .style
+ }
+
+ fn controls(app: PhotocraftApp, properties: bool) -> Harness<'static, PhotocraftApp> {
+ let mut h = Harness::builder().with_size(vec2(1100.0, 800.0)).build_ui_state(
+ move |ui, app| {
+ if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
+ if properties {
+ ui.set_width(340.0);
+ super::super::type_properties(app, ui);
+ } else {
+ ui.horizontal(|ui| super::super::options_bar(app, ui));
+ }
+ }
+ },
+ app,
+ );
+ PhotocraftApp::setup_context(&h.ctx, Default::default());
+ h.run_steps(4);
+ h
+ }
+
+ fn number(h: &mut Harness<'static, PhotocraftApp>, index: usize, value: &str) {
+ h.get_all_by_role(Role::SpinButton).nth(index).expect("numeric field").click();
+ h.run();
+ h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A);
+ h.event(egui::Event::Text(value.into()));
+ h.key_press(egui::Key::Enter);
+ h.run();
+ }
+
+ fn editing(app: &mut PhotocraftApp, id: LayerId) {
+ app.ui.text_edit = Some(crate::state::TextEdit {
+ layer: id.0,
+ caret: 3,
+ anchor: 1,
+ session: "batch-type-edit".into(),
+ created: false,
+ dragging: false,
+ resize: None,
+ preedit: None,
+ });
+ }
+
+ #[test]
+ fn options_font_family_preserves_peer_faces_and_batches_layer_flags() {
+ let (app, ids) = fixture();
+ let before = ids.map(|id| style(&app, id, 0));
+ let mut h = controls(app, false);
+ h.get_all_by_role(Role::ComboBox).next().unwrap().click();
+ h.run();
+ h.get_by_role(Role::TextInput).type_text("JetBrains");
+ h.key_press(egui::Key::ArrowDown);
+ h.run();
+ h.key_press(egui::Key::Enter);
+ h.run();
+ for i in 0..2 {
+ let mut expected = before[i].clone();
+ expected.font_family = "JetBrains Mono".into();
+ expected.postscript_name = None;
+ assert_eq!(style(h.state(), ids[i], 0), expected, "family changes preserve each peer's face and metrics");
+ }
+ assert_eq!(style(h.state(), ids[2], 0), before[2]);
+ h.get_all_by_role(Role::ComboBox).nth(2).unwrap().click();
+ h.run();
+ h.get_by_label("Sharp").click();
+ h.run();
+ // The options bar's leading orientation icon has a tooltip but no accessibility label.
+ h.get_all_by_role(Role::Unknown).next().expect("orientation icon").click();
+ h.run();
+ for id in &ids[..2] {
+ let t = text(h.state(), *id);
+ assert_eq!(t.antialias, AntiAlias::Sharp);
+ assert_eq!(t.orientation, Orientation::Vertical);
+ }
+ assert_eq!(text(h.state(), ids[2]).orientation, Orientation::Horizontal);
+ assert_ne!(text(h.state(), ids[2]).antialias, AntiAlias::Sharp);
+ }
+
+ #[test]
+ fn properties_edit_shown_metrics_and_paragraphs_with_a_non_type_primary() {
+ let (mut app, ids) = fixture();
+ let untouched = style(&app, ids[2], 0);
+ for (id, scale) in [(ids[0], 2.0), (ids[1], 4.0)] {
+ app.run("type.edit", json!({"layer": id.0, "transform": [scale, 0.0, 0.0, scale, 0.0, 0.0]})).unwrap();
+ }
+ let raster = LayerId(app.run("layer.new.layer", json!({"name": "Selected raster"})).unwrap()["layer"].as_u64().unwrap());
+ selected(&mut app, &[ids[0], ids[1], raster]);
+ let mut h = controls(app, true);
+ number(&mut h, 0, "60");
+ // Differ from the automatic 72 pt leading so this is an actual property change.
+ number(&mut h, 1, "84");
+ h.get_by_label("Faux Bold").click();
+ h.run();
+ h.get_by_label("Center text").click();
+ h.run();
+ h.get_by_label("Hyphenate").click();
+ h.run();
+ number(&mut h, 6, "9");
+ for (id, scale) in [(ids[0], 2.0), (ids[1], 4.0)] {
+ let c = style(h.state(), id, 0);
+ assert_eq!(c.size_pt * scale, 60.0);
+ assert_eq!(c.leading_pt.unwrap() * scale, 84.0);
+ assert!(c.faux_bold);
+ let p = text(h.state(), id).paragraph_runs()[0].style.clone();
+ assert_eq!(p.align, TextAlign::Center);
+ assert!(p.hyphenate);
+ assert_eq!(p.start_indent_pt, 9.0);
+ }
+ assert_eq!(style(h.state(), ids[2], 0), untouched);
+ assert_eq!(h.state().session.active().unwrap().active_layer, Some(raster));
+ // The same controls edit only the selected Unicode span during a text session.
+ let peer = text(h.state(), ids[1]).char_runs();
+ editing(h.state_mut(), ids[0]);
+ h.run();
+ number(&mut h, 0, "40");
+ assert_eq!((size_at(h.state(), ids[0], 0), size_at(h.state(), ids[0], 1), size_at(h.state(), ids[0], 3)), (30.0, 20.0, 30.0));
+ assert_eq!(text(h.state(), ids[1]).char_runs(), peer);
+ }
+
+ #[test]
+ fn formatting_menus_isolate_the_edit_layer_and_range_but_honor_explicit_targets() {
+ let (mut app, ids) = fixture();
+ let ctx = egui::Context::default();
+ let peer = text(&app, ids[1]);
+ editing(&mut app, ids[0]);
+ for command in ["type.antiAlias.sharp", "type.orientation.vertical", "type.openType.discretionaryLigatures"] {
+ crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap();
+ }
+ assert_eq!(text(&app, ids[0]).antialias, AntiAlias::Sharp);
+ assert_eq!(text(&app, ids[0]).orientation, Orientation::Vertical);
+ assert!(!style(&app, ids[0], 0).discretionary_ligatures);
+ assert!(style(&app, ids[0], 1).discretionary_ligatures);
+ assert!(!style(&app, ids[0], 3).discretionary_ligatures);
+ assert_eq!(text(&app, ids[1]).char_runs(), peer.char_runs());
+ assert_eq!(text(&app, ids[1]).antialias, peer.antialias);
+ assert_eq!(text(&app, ids[1]).orientation, peer.orientation);
+ crate::menus::invoke(&mut app, &ctx, "type.antiAlias.crisp", json!({"layer": ids[1].0})).unwrap();
+ crate::menus::invoke(&mut app, &ctx, "type.orientation.vertical", json!({"layers": [ids[2].0]})).unwrap();
+ assert_eq!(text(&app, ids[1]).antialias, AntiAlias::Crisp);
+ assert_eq!(text(&app, ids[2]).orientation, Orientation::Vertical);
+ assert_eq!(text(&app, ids[0]).antialias, AntiAlias::Sharp);
+ }
+
+ #[test]
+ fn warp_dialog_captures_layer_selection_or_inline_edit_before_confirmation() {
+ for inline in [false, true] {
+ let (mut app, ids) = fixture();
+ if inline {
+ editing(&mut app, ids[0]);
+ }
+ let styles = ids.map(|id| text(&app, id).char_runs());
+ let steps = app.session.active().unwrap().history.entries().len();
+ crate::menus::invoke(&mut app, &egui::Context::default(), "type.warpText", json!({})).unwrap();
+ let dialog = app.ui.dialogs.last().unwrap().id;
+ let fields = &app.ui.dialogs.last().unwrap().fields;
+ if inline {
+ assert_eq!(fields["layer"], ids[0].0);
+ assert_eq!(fields["coalesce"], "batch-type-edit");
+ } else {
+ let targets = fields["layers"].as_array().unwrap();
+ assert_eq!(targets.len(), 2);
+ assert!(targets.contains(&json!(ids[0].0)) && targets.contains(&json!(ids[1].0)));
+ }
+ let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state(
+ |ui, app| {
+ if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
+ crate::dialogs::show(app, ui.ctx());
+ }
+ },
+ app,
+ );
+ PhotocraftApp::setup_context(&h.ctx, Default::default());
+ h.run_steps(4);
+ assert!(h.query_by_label("Bend").is_some(), "the actual Warp form is visible");
+ for label in ["Layer", "Layers", "Range", "Coalesce"] {
+ assert!(h.query_by_label(label).is_none(), "target metadata must not become a form field: {label}");
+ }
+ h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("bend".into(), json!(25.0));
+ selected(h.state_mut(), &[ids[2]]);
+ h.get_by_label("OK").click();
+ h.run_steps(3);
+ assert!(h.state().ui.dialogs.is_empty());
+ for (i, id) in ids.into_iter().enumerate() {
+ let t = text(h.state(), id);
+ assert_eq!(t.warp.as_ref().map(|w| w.value), (i == 0 || (!inline && i == 1)).then_some(25.0), "inline={inline}, layer={i}");
+ assert_eq!(t.char_runs(), styles[i], "Warp leaves character formatting intact");
+ }
+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + 1);
+ if inline {
+ assert_eq!(h.state().session.active().unwrap().coalesce.as_deref(), Some("batch-type-edit"));
+ }
+ }
+ }
+
+ #[test]
+ fn text_swatch_captures_selected_targets_and_cancel_does_not_edit() {
+ let (app, ids) = fixture();
+ let originals = ids.map(|id| style(&app, id, 0));
+ let mut h = controls(app, false);
+ let steps = h.state().session.active().unwrap().history.entries().len();
+ for confirm in [false, true] {
+ selected(h.state_mut(), &ids[..2]);
+ h.run();
+ h.get_by_label("Set the text color").click();
+ h.run();
+ let dialog = h.state().ui.dialogs.last().unwrap().id;
+ h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#00ff00"));
+ selected(h.state_mut(), &[ids[2]]);
+ if confirm {
+ crate::dialogs::confirm(h.state_mut(), dialog).unwrap();
+ } else {
+ h.state_mut().ui.close_dialog(dialog).unwrap();
+ }
+ for i in 0..3 {
+ let mut expected = originals[i].clone();
+ if confirm && i < 2 {
+ expected.color = photocraft_color::Color::rgb(0.0, 1.0, 0.0);
+ }
+ assert_eq!(style(h.state(), ids[i], 0), expected);
+ }
+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps + usize::from(confirm));
+ }
+ assert!(h.state_mut().session.undo());
+ for (id, expected) in ids.into_iter().zip(originals) {
+ assert_eq!(style(h.state(), id, 0), expected);
+ }
+ }
+}
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
index c56196587..9bfd6bb01 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -761,7 +761,9 @@ mod label_tests {
/// Body of a `__form` dialog: text fields, number fields, checkboxes and `__choices` dropdowns.
pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let choices = f.get("__choices").cloned().unwrap_or(Value::Null);
- let keys: Vec<String> = f.keys().filter(|k| !k.starts_with("__")).cloned().collect();
+ let warp_text = f.get("__command").and_then(Value::as_str) == Some("type.warpText");
+ let keys: Vec<String> =
+ f.keys().filter(|k| !(k.starts_with("__") || warp_text && matches!(k.as_str(), "layer" | "layers" | "range" | "coalesce"))).cloned().collect();
egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
for k in keys {
let v = f.get(&k).cloned().unwrap_or(Value::Null);
@@ -883,11 +885,13 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
}
"type.warpText" => {
let styles: Vec<&str> = std::iter::once("none").chain(photocraft_text::warp::STYLES.iter().map(|(_, s)| *s)).collect();
- dialog(
- app,
- json!({"style": "arc", "orientation": "horizontal", "bend": 50.0, "horizontalDistortion": 0.0, "verticalDistortion": 0.0}),
- json!({"style": styles, "orientation": ["horizontal", "vertical"]}),
- )
+ let mut fields = json!({"style": "arc", "orientation": "horizontal", "bend": 50.0, "horizontalDistortion": 0.0, "verticalDistortion": 0.0});
+ if let Some(Value::Object(target)) = crate::type_tool::formatting_params(app) {
+ for (key, value) in target {
+ fields[key] = value;
+ }
+ }
+ dialog(app, fields, json!({"style": styles, "orientation": ["horizontal", "vertical"]}))
}
"file.export.layersToFiles" => {
let (_, _, name) = doc?;