Skip to content

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

Type: editing text keeps its ligatures and OpenType alternates (#3617) (#3747)

David Mannb071929ecb9d
diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs
index 2c0ca38af..b1359f31b 100644
--- a/crates/text/src/psd.rs
+++ b/crates/text/src/psd.rs
@@ -140,9 +140,11 @@ pub fn parse_txt2(data: &[u8]) -> Option<E> {
ed::parse(&wrapped).ok().filter(|v| matches!(v, E::Dict(_)))
}
-/// Applies the automatic kerning modes that Photoshop keeps only in `Txt2` (EngineData writes
-/// Optical and "0" alike as `AutoKerning true`) to `layer`, read from `tysh`. Only when the
-/// layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2`
+/// Applies what Photoshop keeps only in `Txt2` to `layer`, read from `tysh`: the automatic
+/// kerning modes (EngineData writes Optical and "0" alike as `AutoKerning true`) and the
+/// OpenType settings besides (discretionary) ligatures: stylistic sets, contextual alternates,
+/// swashes and the rest ([`TXT2_FEATURES`]), which Photoshop leaves out of EngineData. Only when
+/// the layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2`
/// stale).
///
/// Observed layout: `Txt2 /1` is the list of text objects; an object's `/0` is its text model
@@ -168,11 +170,10 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
let Some(style_runs) = model.path(&["6", "0"]).and_then(E::as_array) else {
return;
};
- let modes: Vec<(f64, Option<i64>)> =
- style_runs.iter().map(|r| (r.get("1").and_then(E::as_f64).unwrap_or(0.0), r.path(&["0", "0", "6", "11"]).and_then(E::as_i64))).collect();
- let lens = utf16_to_byte_lengths(text, &modes.iter().map(|m| m.0).collect::<Vec<_>>());
- // Auto-kern mode per byte segment, then split the model runs at segment boundaries.
- let mut segs: Vec<(usize, Option<i64>)> = lens.into_iter().zip(modes.iter().map(|m| m.1)).collect();
+ let styles: Vec<(f64, Option<&E>)> = style_runs.iter().map(|r| (r.get("1").and_then(E::as_f64).unwrap_or(0.0), r.path(&["0", "0", "6"]))).collect();
+ let lens = utf16_to_byte_lengths(text, &styles.iter().map(|m| m.0).collect::<Vec<_>>());
+ // Txt2 style per byte segment, then split the model runs at segment boundaries.
+ let mut segs: Vec<(usize, Option<&E>)> = lens.into_iter().zip(styles.iter().map(|m| m.1)).collect();
segs.retain(|s| s.0 > 0);
let runs = layer.char_runs();
let mut out: Vec<TextRun> = Vec::new();
@@ -187,14 +188,18 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
}
let piece_end = if at < seg_end { end.min(seg_end) } else { end };
let mut style = r.style.clone();
+ let txt2_style = segs.get(si).and_then(|s| s.1).filter(|_| at < seg_end);
// Txt2 has the exact mode (EngineData's reading also marks neighbours of manual
// kerns manual, like Photoshop's legacy reader).
- match segs.get(si).and_then(|s| s.1).filter(|_| at < seg_end) {
+ match txt2_style.and_then(|st| st.get("11")).and_then(E::as_i64) {
Some(0) => style.kerning = Kerning::Off,
Some(1) => style.kerning = Kerning::Metrics,
Some(2) => style.kerning = Kerning::Optical,
_ => {}
}
+ if let Some(st) = txt2_style {
+ add_txt2_features(&mut style, st);
+ }
let len = piece_end - at;
match out.last_mut() {
Some(last) if last.style == style => last.len += len,
@@ -207,6 +212,43 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) {
layer.sync_summary();
}
+/// OpenType settings of a `Txt2` style that are on/off flags, by style key, as Photoshop
+/// writes them (each turned on alone in the Character panel's OpenType settings and read back):
+/// `/20` Contextual Alternates, `/23` Fractions, `/24` Ordinals, `/25` Swash, `/26` Titling
+/// Alternates, `/28` Stylistic Alternates, `/29` Ornaments. (`/18` and `/19` are the standard and
+/// discretionary ligatures, which EngineData carries too; `/27` is Arabic connection forms.)
+pub const TXT2_FEATURES: [(&str, &str); 7] = [("20", "calt"), ("23", "frac"), ("24", "ordn"), ("25", "swsh"), ("26", "titl"), ("28", "salt"), ("29", "ornm")];
+
+/// The `Txt2` style key holding the Stylistic Sets as a bit mask: bit n is set n + 1
+/// (`ss01`..`ss20`).
+pub const TXT2_STYLISTIC_SETS: &str = "85";
+
+/// Sets in `style` the OpenType features a `Txt2` style dictionary turns on ([`TXT2_FEATURES`]
+/// and the Stylistic Sets mask). A feature the style already sets keeps its value. A flag that is
+/// off changes nothing, except Contextual Alternates: shapers apply `calt` by default, Photoshop
+/// only when it is on (its default is off), so off is written as `calt` 0.
+fn add_txt2_features(style: &mut CharStyle, txt2_style: &E) {
+ let mut set = |tag: String, value: u16| {
+ if !style.features.iter().any(|f| f.tag == tag) {
+ style.features.push(photocraft_doc::text::FontFeature { tag, value });
+ }
+ };
+ for (key, tag) in TXT2_FEATURES {
+ match txt2_style.get(key).and_then(E::as_bool) {
+ Some(true) => set(tag.to_string(), 1),
+ Some(false) if tag == "calt" => set(tag.to_string(), 0),
+ _ => {}
+ }
+ }
+ // A mask beyond the 20 sets is not Photoshop's: ignore it.
+ let sets = txt2_style.get(TXT2_STYLISTIC_SETS).and_then(E::as_i64).filter(|m| (0..1 << 20).contains(m)).unwrap_or(0);
+ for n in 0..20 {
+ if sets & (1 << n) != 0 {
+ set(format!("ss{:02}", n + 1), 1);
+ }
+ }
+}
+
/// Builds a [`TextLayer`] (model, text and transform; no cache, no `psd_raw`) from `TySh` data.
pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option<TextLayer> {
let t = parse_tysh(data)?;
diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs
index 75b775b78..b1a1949ca 100644
--- a/crates/text/src/tests.rs
+++ b/crates/text/src/tests.rs
@@ -682,6 +682,11 @@ fn warp_bends_rendered_text_and_outlines() {
/// `Txt2` as Photoshop writes it (a bare `/key value` sequence; text objects at `/1 /1`, style
/// runs at `/0 /6 /0`, auto-kern mode at `/11`), for the layer text `text`.
fn txt2_with_modes(text: &str, modes: &[(usize, i64)]) -> Vec<u8> {
+ txt2_with_styles(text, &modes.iter().map(|(len, m)| (*len, format!("/11 {m}"))).collect::<Vec<_>>())
+}
+
+/// [`txt2_with_modes`] with each style run's keys given as EngineData text (`"/11 1 /85 2"`).
+fn txt2_with_styles(text: &str, styles: &[(usize, String)]) -> Vec<u8> {
let mut v = b"\n\n/98 << /0 14 >> /0 << >> /1 << /1 [ << /0 << /0 (\xfe\xff".to_vec();
for u in format!("{text}\r").encode_utf16() {
let b = u.to_be_bytes();
@@ -693,8 +698,8 @@ fn txt2_with_modes(text: &str, modes: &[(usize, i64)]) -> Vec<u8> {
}
}
v.extend_from_slice(b") /6 << /0 [ ");
- for (len, m) in modes {
- v.extend_from_slice(format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /6 << /0 0 /11 {m} >> >> >> /1 {len} >> ").as_bytes());
+ for (len, keys) in styles {
+ v.extend_from_slice(format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /6 << /0 0 {keys} >> >> >> /1 {len} >> ").as_bytes());
}
v.extend_from_slice(b"] >> >> >> ] >>");
v
@@ -741,6 +746,55 @@ fn txt2_carries_optical_kerning() {
assert!(l.char_runs().iter().all(|r| r.style.kerning == Kerning::Optical));
}
+/// #3617: Photoshop keeps Stylistic Sets, Contextual Alternates, Swash and the other OpenType
+/// settings besides (discretionary) ligatures only in `Txt2`. Import reads them, so the layout
+/// our engine draws when the type is edited keeps Photoshop's glyphs instead of falling back to
+/// the default ones.
+#[test]
+fn txt2_carries_opentype_features() {
+ let feats = |l: &TextLayer| l.char_runs().iter().map(|r| r.style.features.iter().map(|f| (f.tag.clone(), f.value)).collect::<Vec<_>>()).collect::<Vec<_>>();
+ let f = |tag: &str, value: u16| (tag.to_string(), value);
+ // "Il->36" plus the engine's closing break: Stylistic Set 2 (mask 2), Contextual Alternates
+ // and Swash on "Il"; Contextual Alternates off (Photoshop's default), Stylistic Set 1 and
+ // Fractions on the rest.
+ let text = "Il->36";
+ let plain = styled(text, CharStyle { font_family: "Inter".into(), ..Default::default() });
+ let tysh = with_text_index(&crate::psd::build_tysh(&plain, 72.0, None), 0);
+ let styles = [(2, "/11 1 /18 true /19 false /20 true /25 true /85 2".to_string()), (5, "/11 1 /20 false /23 true /85 1".to_string())];
+ let txt2 = crate::psd::parse_txt2(&txt2_with_styles(text, &styles)).unwrap();
+ let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();
+ assert_eq!(feats(&back), vec![Vec::<(String, u16)>::new()], "EngineData alone doesn't have them");
+ crate::psd::apply_txt2(&mut back, &tysh, &txt2);
+ assert_eq!(feats(&back), vec![vec![f("calt", 1), f("swsh", 1), f("ss02", 1)], vec![f("calt", 0), f("frac", 1), f("ss01", 1)]]);
+ assert_eq!(back.char_runs().iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 4]);
+ // What editing shows (our layout) has Photoshop's glyphs: Inter's `ss02` draws another I and
+ // l, `ss01` another 3 and 6, and `->` stays two glyphs without `calt` (with it, an arrow).
+ let mut e = TextEngine::new();
+ let ids = |e: &mut TextEngine, t: &TextLayer| e.layout(t, 72.0).glyphs.iter().map(|g| g.id).collect::<Vec<_>>();
+ let with = |len: usize, tags: &[(&str, u16)]| TextRun {
+ len,
+ style: CharStyle {
+ features: tags.iter().map(|(tag, value)| FontFeature { tag: (*tag).into(), value: *value }).collect(),
+ ..back.char_runs()[0].style.clone()
+ },
+ };
+ let mut expected = back.clone();
+ expected.runs = vec![with(2, &[("ss02", 1)]), with(4, &[("calt", 0), ("ss01", 1)])];
+ let shown = ids(&mut e, &back);
+ assert_eq!(shown, ids(&mut e, &expected));
+ let defaults = ids(&mut e, &crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap());
+ assert_eq!((shown.len(), defaults.len()), (6, 5), "`->` is two glyphs, as in Photoshop, not an arrow");
+ assert!(shown.first() != defaults.first() && shown.last() != defaults.last(), "{shown:?} vs {defaults:?}");
+ // A feature the style already sets (from EngineData, read first) keeps its value; masks and
+ // flags of the wrong type, masks beyond the 20 sets and unknown keys change nothing.
+ let mut t = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap();
+ t.runs = vec![TextRun { len: text.len(), style: CharStyle { features: vec![FontFeature { tag: "ss01".into(), value: 0 }], ..Default::default() } }];
+ let odd =
+ [(1, "/85 1".to_string()), (1, "/85 (x) /20 (x) /25 (true)".to_string()), (1, "/85 -1".to_string()), (4, "/85 99999999999 /999 true".to_string())];
+ crate::psd::apply_txt2(&mut t, &tysh, &crate::psd::parse_txt2(&txt2_with_styles(text, &odd)).unwrap());
+ assert_eq!(feats(&t), vec![vec![f("ss01", 0)]]);
+}
+
/// A `Txt2` written by [`crate::psd::build_txt2`] (what PSD export writes for the type layers)
/// restores every auto-kern mode on import (#1348: a new Optical layer used to reopen as
/// Metrics, because EngineData's `AutoKerning true` covers both).