Skip to content

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

Keep the type style when a data set replaces text (#2742) (#2785)

Fabio Lussi7c9e7e5ae333
diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs
index 3da65c166..507861090 100644
--- a/crates/engine/src/variables_cmds.rs
+++ b/crates/engine/src/variables_cmds.rs
@@ -7,6 +7,7 @@
use std::sync::Arc;
use photocraft_algo::resample::{Resample, resize_surface, translate_surface};
+use photocraft_doc::text::{ParagraphRun, TextRun};
use photocraft_doc::variables::Value as VarValue;
use photocraft_doc::{DataSet, DataValue, Document, LayerContent, LayerId, PixelAlign, PixelMethod, VarKind, VariableDef, Variables};
use serde_json::{Value, json};
@@ -168,9 +169,15 @@ fn apply_to_doc(doc: &mut Document, vars: &Variables, set: &DataSet) -> Result<(
if let Some(l) = doc.layer_mut(def.layer)
&& let LayerContent::Text(t) = &mut l.content
{
+ // As in Photoshop, the new text takes the style of the first character it
+ // replaces (and its paragraph's settings): clearing the runs fell back to the
+ // summary style and lost weight, italic, tracking, caps… (#2742).
+ let style = t.char_runs().into_iter().next().map(|r| r.style).unwrap_or_default();
+ let para = t.paragraph_runs().into_iter().next().map(|r| r.style).unwrap_or_default();
t.text = text.clone();
- t.runs.clear(); // re-flow as one run from the summary style
- t.paragraphs.clear();
+ t.runs = vec![TextRun { len: t.text.len(), style }];
+ t.paragraphs = vec![ParagraphRun { len: t.text.len(), style: para }];
+ t.sync_summary();
// The compositor draws a type layer from its cache: clearing it left the
// layer blank until some other edit re-rendered it (#990).
crate::type_cmds::refresh(&snapshot, t);
diff --git a/crates/engine/src/variables_cmds/tests.rs b/crates/engine/src/variables_cmds/tests.rs
index 68fcc9d6a..28fc14a36 100644
--- a/crates/engine/src/variables_cmds/tests.rs
+++ b/crates/engine/src/variables_cmds/tests.rs
@@ -483,3 +483,107 @@ fn applied_text_is_rendered_in_the_document_and_in_exports() {
assert!(dark(doc(&s)) > 0, "the applied text is drawn");
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// A text layer created bold-italic with tracking, underline, all caps and colour, bound to a
+/// `headline` text variable with one data set per value.
+fn styled_text_session(values: &[&str]) -> (Session, Value) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 400, "height": 120, "background": "white"})).unwrap();
+ let id = s
+ .execute(
+ "type.create",
+ json!({"x": 10, "y": 60, "text": "Before", "font": "Inter", "weight": 700, "italic": true, "size": 40,
+ "color": "#C0392B", "tracking": 120, "underline": true, "caps": "all"}),
+ )
+ .unwrap()["layer"]
+ .clone();
+ s.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": id, "type": "textReplacement"}]})).unwrap();
+ let sets: Vec<Value> =
+ values.iter().enumerate().map(|(i, v)| json!({"name": format!("s{i}"), "values": [{"variable": "headline", "kind": "text", "value": v}]})).collect();
+ s.execute("image.variables.dataSets", json!({ "dataSets": sets })).unwrap();
+ (s, id)
+}
+
+fn text_layer(s: &Session, id: &Value) -> TextLayer {
+ match &doc(s).layer(LayerId(id.as_u64().unwrap())).unwrap().content {
+ LayerContent::Text(t) => t.clone(),
+ _ => panic!("not a text layer"),
+ }
+}
+
+#[test]
+fn applied_text_keeps_the_character_style() {
+ // Applying a text value cleared the style runs, so weight, italic, tracking, underline and
+ // caps fell back to the defaults (#2742). The new text takes the first character's style.
+ let (mut s, id) = styled_text_session(&["After"]);
+ let before = text_layer(&s, &id);
+ let style = before.char_runs()[0].style.clone();
+ assert_eq!((style.weight, style.italic), (700, true), "precondition: {style:?}");
+ let paragraphs = before.paragraph_runs()[0].style.clone();
+ s.execute("image.applyDataSet", json!({"name": "s0"})).unwrap();
+ let after = text_layer(&s, &id);
+ assert_eq!(after.text, "After");
+ let runs = after.char_runs();
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].len, "After".len());
+ assert_eq!(runs[0].style, style, "the whole character style is kept");
+ assert_eq!(after.paragraph_runs()[0].style, paragraphs, "paragraph settings are kept");
+ assert_eq!((after.font_family.as_str(), after.size_pt, after.color), (before.font_family.as_str(), before.size_pt, before.color));
+ // type.info reports the same style as before.
+ let info = s.execute("type.info", json!({"layer": id})).unwrap();
+ assert_eq!(info["runs"][0]["style"]["weight"], 700);
+ assert_eq!(info["runs"][0]["style"]["italic"], true);
+
+ // Undo restores the original text and runs.
+ s.execute("edit.undo", json!({})).unwrap();
+ let undone = text_layer(&s, &id);
+ assert_eq!(undone.text, "Before");
+ assert_eq!(undone.runs, before.runs);
+}
+
+#[test]
+fn applied_text_takes_the_first_runs_style_and_survives_empty_values() {
+ let (mut s, id) = styled_text_session(&["One style", ""]);
+ // Make the second half of the text regular, upright and blue: a two-run layer.
+ s.execute("type.edit", json!({"layer": id, "runs": [{"start": 3, "end": 6, "weight": 400, "italic": false, "color": "#0000FF"}]})).unwrap();
+ let before = text_layer(&s, &id);
+ assert_eq!(before.char_runs().len(), 2, "precondition: two runs");
+ let first = before.char_runs()[0].style.clone();
+ s.execute("image.applyDataSet", json!({"name": "s0"})).unwrap();
+ let after = text_layer(&s, &id);
+ assert_eq!(after.text, "One style");
+ let runs = after.char_runs();
+ assert_eq!(runs.len(), 1, "the replacement is one run");
+ assert_eq!(runs[0].style, first, "in the first run's style");
+
+ // An empty value empties the layer without panicking and keeps the style for later text.
+ s.execute("image.applyDataSet", json!({"name": "s1"})).unwrap();
+ let empty = text_layer(&s, &id);
+ assert_eq!(empty.text, "");
+ assert_eq!(empty.char_runs()[0].style, first);
+ s.execute("image.applyDataSet", json!({"name": "s0"})).unwrap();
+ assert_eq!(text_layer(&s, &id).char_runs()[0].style, first);
+}
+
+#[test]
+fn exported_data_sets_keep_the_character_style() {
+ // file.export.dataSetsAsFiles applies each set to a copy of the document the same way.
+ let (mut s, id) = styled_text_session(&["After"]);
+ let style = text_layer(&s, &id).char_runs()[0].style.clone();
+ let dir = tmp("styled-export");
+ let out = s.execute("file.export.dataSetsAsFiles", json!({"dir": dir, "format": "psd"})).unwrap();
+ let path = out["files"][0].as_str().unwrap();
+ let exported = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document;
+ let t = exported
+ .layers
+ .iter()
+ .find_map(|l| match &l.content {
+ LayerContent::Text(t) => Some(t.clone()),
+ _ => None,
+ })
+ .expect("the export keeps the type layer");
+ assert_eq!(t.text, "After");
+ let got = &t.char_runs()[0].style;
+ assert_eq!((got.weight, got.italic, got.underline), (style.weight, style.italic, style.underline));
+ let _ = std::fs::remove_dir_all(&dir);
+}