Merge pull request #7226 from dotCooCoo/fix/legacy-ai-type-kerning

PDF/.ai import: legacy type keeps manual kerning, discretionary hyphens and language
This commit is contained in:
BFlat
2026-11-14 07:34:10 +07:00
committed by GitHub
38 changed files with 459 additions and 37 deletions
+143 -7
View File
@@ -3,8 +3,11 @@
//! type runs along, `TP`), the modal character and paragraph attributes
//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging
//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`, and §15.3.4's writing direction `TV`,
//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`), the paint
//! style, and the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the
//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`, and §22.6's
//! hyphenation language `XL`), the paint style, the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends
//! a paragraph), manual kerning pairs (`Tk`, overflow `TK`) and discretionary hyphens (`T+`, `T-`,
//! read as soft hyphens). The line breaking value `TG` and the Japanese layout rules `Xu` (`Tu`) are
//! not kept: a visible text object read while one is set gives a warning. Type set in rendering modes 4 to 7 is a mask (§5.7): the
//! text object clips the objects of its clipping group. Final-form operators (the
//! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the
//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s
@@ -59,6 +62,14 @@ const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound
/// The warning when `TV` changes after a text object's first character: the object keeps the
/// direction of that character.
const DIRECTION_CHANGE_LEFT_OUT: &str = "type that changes writing direction inside a text object opens in the direction of its first character";
/// The warning when a visible text object is read while a line breaking value (`TG`) is set.
const LINE_BREAKING_LEFT_OUT: &str = "the Line Breaking setting of legacy type was left out";
/// The warning when a visible text object is read while Japanese layout rules (`Xu`, `Tu`) are set.
const JAPANESE_LAYOUT_LEFT_OUT: &str = "the Japanese layout rules of legacy type were left out";
/// The manual kerning range `text.setRangeStyle` takes, in 1/1000 em.
const KERNING_RANGE: (f64, f64) = (-1000.0, 10_000.0);
/// The soft hyphen a discretionary hyphen (`T+`, `T-`) is read as.
const SOFT_HYPHEN: char = '\u{ad}';
/// A text path (`Tp` … `TP`).
#[derive(Debug, Default)]
@@ -124,6 +135,9 @@ pub(super) struct LegacyText {
vertical: bool,
/// A later character was set in the other direction.
direction_changed: bool,
/// A manual kerning value (`Tk`, `TK`) read at the start of a line, in 1/1000 em: the space
/// before the next character, which starts the line.
kern_before: Option<f64>,
/// The state when it began (lock, visibility), and whether it began on a `%_` line.
gs: GState,
hidden: bool,
@@ -148,6 +162,40 @@ impl LegacyText {
}
}
/// Add `text` in `style` to `runs`: to the last run when it has that style, else as a new run.
fn push_run(runs: &mut Vec<TextRun>, text: String, style: CharStyle) {
if text.is_empty() {
return;
}
match runs.last_mut() {
Some(last) if last.inline.is_none() && last.style == style => last.text.push_str(&text),
_ => runs.push(TextRun::new(text, style)),
}
}
/// Give the last character of `runs` the manual kerning `kerning` (None: automatic), in a run of
/// its own unless its run has one character, which joins the run before it when their styles
/// match. False when there is no character or the last one ends a paragraph: the kerning is at
/// the start of a line.
fn set_last_kerning(runs: &mut Vec<TextRun>, kerning: Option<f64>) -> bool {
let Some(last) = runs.last_mut().filter(|r| r.inline.is_none()) else { return false };
let Some(c) = last.text.chars().next_back().filter(|&c| c != '\n') else { return false };
if last.style.kerning == kerning {
return true;
}
if last.text.len() > c.len_utf8() {
last.text.pop();
let style = CharStyle { kerning, ..last.style.clone() };
runs.push(TextRun::new(c.to_string(), style));
return true;
}
last.style.kerning = kerning;
if let Some(one) = runs.pop() {
push_run(runs, one.text, one.style);
}
true
}
/// Are `a` and `b` the same, leaving their tab stops out?
fn same_but_tabs(a: &mut ParaStyle, b: &mut ParaStyle) -> bool {
let (a_tabs, b_tabs) = (std::mem::take(&mut a.tabs), std::mem::take(&mut b.tabs));
@@ -203,6 +251,10 @@ pub(super) struct TypeState {
vertical: bool,
/// `TY`: a Kumi block recorded for later use, which horizontal type keeps as its mark.
kumi_recorded: bool,
/// A line breaking value (`TG`) was read: VectorCraft has no setting for it.
line_breaking: bool,
/// Japanese layout rules (`Xu`, `Tu`) were read: VectorCraft has no setting for them.
japanese_layout: bool,
/// The encoding strings are in, by code (`TE`); None where it says nothing.
encoding: Vec<Option<char>>,
/// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s).
@@ -232,6 +284,8 @@ impl Default for TypeState {
render: 0,
vertical: false,
kumi_recorded: false,
line_breaking: false,
japanese_layout: false,
encoding: vec![None; 256],
fonts: vec![],
font_encodings: vec![],
@@ -684,6 +738,23 @@ impl Reader<'_> {
st.tabs_version = st.tabs_version.wrapping_add(1);
}
}
// `languageID XL` (§22.6), the hyphenation language: 0 U.S. English (the default
// language, none), then U.K. English, French, German, Spanish, Dutch, Italian, Swedish,
// Norwegian, Finnish, Danish and Hungarian, as the Character panel's language tags.
"XL" => {
const TAGS: [&str; 11] = ["en-GB", "fr", "de", "es", "nl", "it", "sv", "nb", "fi", "da", "hu"];
match n0 {
Some(0.0) => st.style.language = None,
Some(id) if id.fract() == 0.0 && (1.0..=11.0).contains(&id) => {
st.style.language = TAGS.get(id as usize - 1).map(|t| t.to_string());
}
_ => {}
}
}
// `linebreak TG` and `prop cjkLayout cjkRoman cjkCjk Xu` (`Tu` the same, §22.6). Either
// one is set only when its operands are numbers.
"TG" => st.line_breaking |= n0.is_some(),
"Xu" | "Tu" => st.japanese_layout |= nums::<4>(vals).is_some(),
_ => {}
}
}
@@ -691,14 +762,59 @@ impl Reader<'_> {
/// `(…) Tx` (`Tj`, overflow `TX`): characters in the current style and paint.
pub(super) fn text_body(&mut self, w: &str, vals: &[V]) {
let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return };
if self.text.is_none() {
return;
}
let decoded = self.type_state.decode(&bytes);
self.add_chars(w == "TX", decoded);
}
/// `autoKern kernValue Tk` (`TK` in overflow text): the space between the character before it
/// and the character after it. With `autoKern` 0 the pair takes `kernValue` in 1/1000 em as
/// manual kerning, kept to the range `text.setRangeStyle` takes; with 1 the pair takes the
/// automatic kerning. The value is the kerning after the character before it; at the start of
/// a line it is the space before the character after it. Operands that are missing, are not
/// numbers, or a flag other than 0 and 1 leave the type as it was, and so does a `Tk` outside a
/// text object.
pub(super) fn text_kern(&mut self, vals: &[V]) {
let Some([auto, value]) = nums::<2>(vals) else { return };
let Some(auto) = flag(auto) else { return };
let Some(t) = self.text.as_mut() else { return };
let kerning = (!auto).then(|| value.clamp(KERNING_RANGE.0, KERNING_RANGE.1));
let line_start = t.pending_break.is_some() || !set_last_kerning(&mut t.runs, kerning);
if line_start {
t.kern_before = kerning;
}
}
/// `T+` (a discretionary hyphen that doesn't print) or `T-` (`printed`: the character before it
/// is a discretionary hyphen that prints, §15.4.10.1): a soft hyphen, which shows as a hyphen
/// only where a line breaks at it. A printed hyphen character (`-` or U+2010) before `T-`
/// becomes the soft hyphen; else one is added.
pub(super) fn discretionary_hyphen(&mut self, printed: bool) {
let Some(t) = self.text.as_mut() else { return };
if printed
&& t.pending_break.is_none()
&& let Some(last) = t.runs.last_mut()
&& last.inline.is_none()
&& last.text.ends_with(['-', '\u{2010}'])
{
last.text.pop();
last.text.push(SOFT_HYPHEN);
return;
}
self.add_chars(false, SOFT_HYPHEN.to_string());
}
/// Characters in the current style and paint (`overflow`: read by `TX`).
fn add_chars(&mut self, overflow: bool, decoded: String) {
let st = &mut self.type_state;
let Some(t) = self.text.as_mut() else { return };
let decoded = st.decode(&bytes);
if decoded.is_empty() {
return;
}
// Overflow text ending the story with a paragraph break (`(\r) TX`) adds no paragraph.
if w == "TX" && decoded == "\n" {
if overflow && decoded == "\n" {
if t.pending_break.is_none() {
let para = (!t.para_taken).then(|| (st.para.clone(), st.tabs_version));
t.pending_break = Some(PendingBreak { vertical: st.vertical, para });
@@ -744,6 +860,8 @@ impl Reader<'_> {
text.push('\n');
t.para_taken = false;
}
// Where the characters start in `text`, after a break read before them.
let at = text.len();
for c in decoded.chars() {
if c != '\n' && !t.para_taken {
t.begin_para(&mut st.para, st.tabs_version);
@@ -757,10 +875,19 @@ impl Reader<'_> {
t.para_taken = false;
}
}
match t.runs.last_mut() {
Some(last) if last.style == style => last.text.push_str(&text),
_ => t.runs.push(TextRun::new(text, style)),
// Kerning read at the start of the line is the space before its first character; a
// paragraph break there leaves no character for it.
let first = decoded.chars().next().filter(|&c| c != '\n');
if let (Some(k), Some(c)) = (t.kern_before.take(), first) {
let end = at + c.len_utf8();
let (rest, after) = (text.split_off(end), CharStyle { kerning_before: k, ..style.clone() });
let own = text.split_off(at);
push_run(&mut t.runs, text, style.clone());
push_run(&mut t.runs, own, after);
push_run(&mut t.runs, rest, style);
return;
}
push_run(&mut t.runs, text, style);
}
/// `TO`: the text object ends. Area type with several linked areas becomes one frame for each
@@ -792,6 +919,15 @@ impl Reader<'_> {
if t.direction_changed {
self.warn(DIRECTION_CHANGE_LEFT_OUT);
}
// A copy on `%_` lines is not the type the document shows.
if !(t.hidden || hidden) {
if self.type_state.line_breaking {
self.warn(LINE_BREAKING_LEFT_OUT);
}
if self.type_state.japanese_layout {
self.warn(JAPANESE_LAYOUT_LEFT_OUT);
}
}
let mut paras = std::mem::take(&mut t.paras);
if paras.is_empty() {
paras.push(ParaRun { style: self.type_state.para.clone(), count: 1, tabs_version: 0 });
+9 -6
View File
@@ -383,17 +383,20 @@ impl<'a> Reader<'a> {
// `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`.
"Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals),
"Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "TV" | "Tv" | "Ty" | "TY" | "Tg" | "Xb"
| "Xe" | "XB" => {
| "Xe" | "XB" | "XL" | "TG" | "Xu" | "Tu" => {
self.text_attr(w, &vals);
}
// Attributes the reader doesn't keep (kerning pairs, line breaking and Japanese layout
// rules) and final-form positions (§15.3).
"Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TG" | "Tu" | "Xu" => {}
// A kerning pair (`Tk`, `TK` in overflow text, §15.4.6.1) and discretionary hyphens
// (`T+`, `T-`, §15.4.10.1).
"Tk" | "TK" => self.text_kern(&vals),
"T+" => self.discretionary_hyphen(false),
"T-" => self.discretionary_hyphen(true),
// Final-form positions (§15.4.7: `Tc Tw Tm Td T* TR`, printing only), which the type's
// layout computes again.
"Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" => {}
// `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the
// reader takes `Te` with any number of operands.
"TM" | "Te" => {}
// The hyphenation language (`XL`), which the reader doesn't keep either (§22).
"XL" => {}
"TE" => self.te(&vals),
"TZ" => self.tz(&vals),
// An image whose samples follow in comment lines (read at `%AI5_EndRaster`).
+113
View File
@@ -4284,6 +4284,119 @@ fn legacy_end_render_and_text_matrix_pop_read() {
}
}
/// The text, manual kerning and space before each run of a legacy-format file's first text object.
fn legacy_kerning(art: &str) -> Vec<(String, Option<f64>, f64)> {
legacy_texts(art)[0].runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect()
}
/// `autoKern kernValue Tk` (§15.4.6.1) spaces the character before it from the one after it: with
/// `autoKern` 0 by `kernValue` (1/1000 em, kept to -1000 to 10,000) as the manual kerning after the
/// character before it, with 1 by the automatic kerning; `TK` does the same in overflow text. At
/// the start of a line it is the space before the line's first character.
#[test]
fn legacy_manual_pair_kerning_is_kept() {
let s = |x: &str| x.to_string();
let runs = legacy_kerning(&point_type("0 TA\n(A) Tx\n0 -80 Tk", "V"));
assert_eq!(runs, [(s("A"), Some(-80.0), 0.0), (s("V"), Some(0.0), 0.0)]);
// Inside a run, the character before it takes the value alone.
let runs = legacy_kerning(&point_type("(WAVE) Tx\n0 50 Tk", "S"));
assert_eq!(runs, [(s("WAV"), None, 0.0), (s("E"), Some(50.0), 0.0), (s("S"), None, 0.0)]);
// `autoKern` 1 gives the pair the automatic kerning, whatever its value.
let runs = legacy_kerning(&point_type("0 TA\n(AV) Tx\n1 -50 Tk", "A"));
assert_eq!(runs, [(s("A"), Some(0.0), 0.0), (s("V"), None, 0.0), (s("A"), Some(0.0), 0.0)]);
// Pairs with the same value in a row stay one run.
let runs = legacy_kerning(&point_type("0 TA\n(A) Tx\n0 50 Tk\n(B) Tx\n0 50 Tk", "C"));
assert_eq!(runs, [(s("AB"), Some(50.0), 0.0), (s("C"), Some(0.0), 0.0)]);
// At the start of the text and of a paragraph, the space before the line's first character.
let runs = legacy_kerning(&point_type("0 -30 Tk", "Hi"));
assert_eq!(runs, [(s("H"), None, -30.0), (s("i"), None, 0.0)]);
let runs = legacy_kerning(&point_type("(a\\r) Tx\n0 40 Tk", "b"));
assert_eq!(runs, [(s("a\n"), None, 0.0), (s("b"), None, 40.0)]);
let runs = legacy_kerning(&point_type("(a) Tx\n(\\r) TX\n0 40 TK", "b"));
assert_eq!(runs, [(s("a\n"), None, 0.0), (s("b"), None, 40.0)]);
// In overflow text.
let runs = legacy_kerning(&point_type("(ab) Tx\n0 25 TK", "c").replace("(c) Tx", "(c) TX"));
assert_eq!(runs, [(s("a"), None, 0.0), (s("b"), Some(25.0), 0.0), (s("c"), None, 0.0)]);
// Kept to the range `text.setRangeStyle` takes.
let runs = legacy_kerning(&point_type("(a) Tx\n0 -5000 Tk\n(b) Tx\n0 20000 Tk", "c"));
assert_eq!(runs, [(s("a"), Some(-1000.0), 0.0), (s("b"), Some(10_000.0), 0.0), (s("c"), None, 0.0)]);
// The pair is spaced as the kerning says.
let x = |art: &str| legacy_origins(&legacy_texts(art)[0])[1].0;
let (plain, kerned) = (x(&point_type("0 TA\n(A) Tx", "V")), x(&point_type("0 TA\n(A) Tx\n0 -80 Tk", "V")));
assert!((plain - kerned - 0.96).abs() < 1e-6, "{plain} {kerned}");
}
/// A `Tk` whose operands are missing or are not numbers, or whose flag is not 0 or 1, and a `Tk`
/// outside a text object leave the type as it was.
#[test]
fn legacy_pair_kerning_with_bad_operands_leaves_the_type_as_it_was() {
let want = legacy_kerning(&point_type("(H) Tx", "i"));
for bad in ["0 Tk", "Tk", "/x 50 Tk", "0 /x Tk", "2 50 Tk", "0.5 50 Tk", "(0) 50 Tk"] {
assert_eq!(legacy_kerning(&point_type(&format!("(H) Tx\n{bad}"), "i")), want, "{bad}");
}
let outside = legacy_kerning(&format!("0 50 Tk\n{}", point_type("(H) Tx", "i")));
assert_eq!(outside, want);
}
/// `T+` (a discretionary hyphen, §15.4.10.1) is a soft hyphen where it stands, in overflow text
/// too; `T-` makes the printed hyphen before it a soft hyphen, or adds one. Outside a text object
/// they add nothing.
#[test]
fn legacy_discretionary_hyphens_are_soft_hyphens() {
for (art, text) in [
(point_type("(co) Tx\nT+", "operate"), "co\u{ad}operate"),
(point_type("(co-) Tx\nT-", "operate"), "co\u{ad}operate"),
(point_type("(co) Tx\nT-", "operate"), "co\u{ad}operate"),
(point_type("(co) Tx\nT+", "operate").replace("(operate) Tx", "(operate) TX"), "co\u{ad}operate"),
(format!("T+\nT-\n{}", point_type("", "co")), "co"),
] {
let texts = legacy_texts(&art);
assert_eq!(texts[0].plain_text(), text, "{art}");
}
}
/// `languageID XL` (§22.6) is the characters' language, 0 (U.S. English) the default; it lasts into
/// the next text object, and an ID that is not 0 to 11 leaves the language as it was.
#[test]
fn legacy_hyphenation_language_is_kept() {
let lang = |t: &vectorcraft_doc::TextObject| t.runs.iter().map(|r| r.style.language.clone()).collect::<Vec<_>>();
let texts = legacy_texts(&format!("{}{}", point_type("%_ 3 XL\n(a) Tx\n%_ 0 XL\n(b) Tx\n%_ 8 XL", "c"), point_type("", "d")));
assert_eq!(lang(&texts[0]), [Some("de".to_string()), None, Some("nb".to_string())]);
assert_eq!(lang(&texts[1]), [Some("nb".to_string())]);
for bad in ["12 XL", "-1 XL", "1.5 XL", "/x XL", "XL"] {
let texts = legacy_texts(&point_type(&format!("2 XL\n{bad}"), "a"));
assert_eq!(lang(&texts[0]), [Some("fr".to_string())], "{bad}");
}
}
/// The line breaking value (`TG`) and the Japanese layout rules (`Xu`, `Tu`, §22.6) are not kept:
/// a visible text object read while one is set gives a warning, once for each in a file. A copy of
/// a text object on `%_` lines gives none, and the final-form positions (§15.4.7) give none.
#[test]
fn legacy_line_breaking_and_japanese_layout_rules_are_warned_once() {
const LINE_BREAKING: &str = "the Line Breaking setting of legacy type was left out";
const JAPANESE_LAYOUT: &str = "the Japanese layout rules of legacy type were left out";
let r = legacy_read(&format!("{}{}", point_type("50 TG\n0 1 120 150 Xu", "a"), point_type("60 TG", "b")));
assert_eq!(r.warnings, [LINE_BREAKING, JAPANESE_LAYOUT]);
assert_eq!(legacy_read(&point_type("0 1 120 150 Tu", "a")).warnings, [JAPANESE_LAYOUT]);
let hidden: String = point_type("50 TG", "a").lines().map(|l| format!("%_{l}\n")).collect();
assert_eq!(legacy_read(&hidden).warnings, Vec::<String>::new());
let final_form = point_type("1 0 0 1 10 50 Tm\n0 0 Td\nT*\n0 Tc\n0 Tw\n1 0 0 1 0 0 TR\nTe\nTM", "Hi");
let r = legacy_read(&final_form);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert_eq!(art_texts(&r.doc)[0].plain_text(), "Hi");
}
/// `TG`, `Xu` and `Tu` with missing or non-numeric operands set nothing, so they give no warning.
#[test]
fn legacy_line_breaking_and_japanese_layout_rules_with_bad_operands_are_not_warned() {
for attrs in ["TG", "(a) TG", "1 120 150 Xu", "0 1 (a) 150 Xu", "Tu", "0 1 120 (a) Tu"] {
let r = legacy_read(&point_type(attrs, "a"));
assert!(r.warnings.is_empty(), "{attrs}: {:?}", r.warnings);
assert_eq!(art_texts(&r.doc)[0].plain_text(), "a", "{attrs}");
}
}
/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum
/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges
/// `text.setFormat` takes.
+12 -8
View File
@@ -208,15 +208,15 @@ fn a_postscript_ai_with_a_multi_layer_mask_opens_with_its_layers() {
assert!(r.warnings.iter().any(|w| w.contains("clipping group in each layer")), "{:?}", r.warnings);
}
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation and
/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition) and `Th`
/// (hyphen control). The reader drops `XL` and keeps the tab definition as the paragraph's tab
/// stops rather than failing the file the way it did before (the symptom seen on Illustrator 6/8
/// EPS files whose `Adobe_level2_AI5` program can't be run).
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation, tab-ruler
/// and kerning attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition), `Th`
/// (hyphen control), `Tk` (a manual kerning pair) and `T+` (a discretionary hyphen). The reader
/// keeps the language, the tab definition as the paragraph's tab stops, the pair's kerning and the
/// soft hyphen.
#[test]
fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\
%_ 0 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n";
%_ 3 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(h) Tx\n0 -40 Tk\n(i) Tx\nT+\n(ho) Tx\nTO\n";
// The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped
// on a hidden one), beside the square so the layer is never empty.
let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer"));
@@ -228,10 +228,14 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
let mut texts = vec![];
r.document.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
texts.push(t.para_at(0).clone());
texts.push((**t).clone());
}
});
let [p] = texts.as_slice() else { panic!("{texts:?}") };
let [t] = texts.as_slice() else { panic!("{texts:?}") };
assert_eq!(t.plain_text(), "hi\u{ad}ho");
let runs: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.kerning, r.style.language.as_deref())).collect();
assert_eq!(runs, [("h", Some(-40.0), Some("de")), ("i\u{ad}ho", None, Some("de"))]);
let p = t.para_at(0);
assert!(!p.hyphenate);
assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25));
let tabs: Vec<_> = p.tabs.iter().map(|t| (t.position, t.align)).collect();
+4 -2
View File
@@ -33,7 +33,9 @@
//! - Type (§15): point type, area type and type on a path as text objects, `type To`, `a b c d tx
//! ty startPt Tp` (the text matrix; the frame or path in art space between it and `TP`), each
//! run's paint style, `Tr` (fill, stroke, both or neither), `/_font size ascent descent Tf`,
//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Standard
//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), with manual
//! kerning as `0 value Tk` after each character that has it and before a paragraph's first
//! character that has space before it (§15.4.6.1) and soft hyphens as `T+` (§15.4.10.1), `TO`. Standard
//! Vertical Roman Alignment is written as `1 Tv` and `0 Tv`, and Tate-chu-yoko in horizontal
//! type as a Kumi block recorded for later use, `1 TY` … `0 TY` (§15.3.4); neither operator is
//! written for type that has neither mark. Only the
@@ -99,7 +101,7 @@ const HEX_LINE: usize = 60;
pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)";
pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines";
pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)";
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, manual kerning, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)";
pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)";
pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)";
-1
View File
@@ -120,7 +120,6 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool {
let run_lost = |s: &CharStyle| {
s.underline
|| s.strikethrough
|| s.kerning.is_some_and(|k| k != 0.0)
|| s.optical_kerning
|| s.small_caps.is_some()
|| s.position != CharPosition::Normal
+1
View File
@@ -107,6 +107,7 @@ VCLegacy begin
/To {pop} bd /Tp {7 {pop} repeat} bd /TP {} bd /TO {} bd
/Tr {pop} bd /Tf {pop pop pop pop} bd /Ts {pop} bd /Tz {pop pop} bd /Tt {pop} bd /TA {pop} bd
/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd /Tv {pop} bd /TY {pop} bd
/Tk {pop pop} bd /T+ {} bd
% The page trailer (3): annotatepage marks nothing.
/annotatepage {} bd
end
+68 -6
View File
@@ -1494,12 +1494,12 @@ fn type_on_a_path_alignment_and_end_bracket_are_warned_as_left_out() {
assert!(warned(&|t| t.kind = TextKind::OnPath { path: two(false), start: 0.25, end: None }));
}
/// Kerning other than Auto or 0, optical kerning, Optical Margin Alignment, System Layout,
/// fractional widths off and an area type frame with a second subpath are not held by a legacy
/// `.ai` text object: type with any of them is written as text, with the warning that they are
/// left out.
/// Optical kerning, Optical Margin Alignment, System Layout, fractional widths off and an area
/// type frame with a second subpath are not held by a legacy `.ai` text object: type with any of
/// them is written as text, with the warning that they are left out. Manual kerning is held
/// (`Tk`), with no warning.
#[test]
fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
fn optical_kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
use vectorcraft_doc::{TextKind, TextObject};
let warned = |edit: &dyn Fn(&mut TextObject)| {
let mut doc = typed();
@@ -1513,7 +1513,8 @@ fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
};
assert!(!warned(&|_| {}));
assert!(!warned(&|t| t.runs[0].style.kerning = Some(0.0)));
assert!(warned(&|t| t.runs[0].style.kerning = Some(50.0)));
assert!(!warned(&|t| t.runs[0].style.kerning = Some(50.0)));
assert!(!warned(&|t| t.runs[0].style.kerning_before = 50.0));
assert!(warned(&|t| t.runs[0].style.optical_kerning = true));
assert!(warned(&|t| t.optical_margin = true));
assert!(warned(&|t| t.system_layout = true));
@@ -1526,6 +1527,67 @@ fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
assert!(warned(&|t| t.kind = TextKind::Area { frame: PathData::new(vec![square(10.0), square(120.0)]) }));
}
/// Manual kerning is written as `0 value Tk` after each character that has it, the space before a
/// paragraph's first character as `Tk` before it, and a soft hyphen as a discretionary hyphen
/// (`T+`, §15.4.6.1 and §15.4.10.1); each reads back on the same characters.
#[test]
fn manual_kerning_and_soft_hyphens_are_written_and_read_back() {
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
let plain = style(12.0, Paint::solid(Color::BLACK));
let kerned = CharStyle { kerning: Some(-80.0), ..plain.clone() };
let before = CharStyle { kerning_before: 40.0, ..plain.clone() };
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", kerned.clone());
for (text, st) in [("A co\u{ad}op\n", &plain), ("W", &before), ("ord", &plain), ("d\u{ad}", &kerned)] {
t.runs.push(TextRun::new(text, st.clone()));
}
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = write(&doc);
assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
let text = String::from_utf8(out.bytes.clone()).unwrap();
assert!(text.contains("(A) Tx\n0 -80 Tk\n(V) Tx\n0 -80 Tk\n"), "{text}");
assert!(text.contains("(A co) Tx\nT+\n(op\\r) Tx\n"), "{text}");
assert!(text.contains("0 40 Tk\n(W) Tx\n"), "{text}");
// A soft hyphen with manual kerning keeps it too.
assert!(text.contains("(d) Tx\n0 -80 Tk\nT+\n0 -80 Tk\n"), "{text}");
let read = texts(&crate::import(&out.bytes).unwrap().document);
let runs: Vec<(String, Option<f64>, f64)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect();
let s = |x: &str| x.to_string();
assert_eq!(
runs,
[
(s("AV"), Some(-80.0), 0.0),
(s("A co\u{ad}op\n"), None, 0.0),
(s("W"), None, 40.0),
(s("ord"), None, 0.0),
(s("d\u{ad}"), Some(-80.0), 0.0)
]
);
}
/// Manual kerning of 0 is written as `0 0 Tk` and reads back as manual kerning, not as the
/// automatic kerning of a pair with no `Tk`.
#[test]
fn manual_kerning_of_zero_is_written_and_read_back() {
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
let plain = style(12.0, Paint::solid(Color::BLACK));
let zero = CharStyle { kerning: Some(0.0), ..plain.clone() };
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", zero);
t.runs.push(TextRun::new("To", plain));
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = write(&doc);
let text = String::from_utf8(out.bytes.clone()).unwrap();
assert!(text.contains("(A) Tx\n0 0 Tk\n(V) Tx\n0 0 Tk\n"), "{text}");
let read = texts(&crate::import(&out.bytes).unwrap().document);
let runs: Vec<(String, Option<f64>)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning)).collect();
assert_eq!(runs, [("AV".to_string(), Some(0.0)), ("To".to_string(), None)]);
}
/// Type whose font size measures the cap height is written at the em size it is drawn at, with
/// no warning: 14 pt measuring a 0.7 em cap height reads back as 20 pt type.
#[test]
+45 -3
View File
@@ -843,6 +843,8 @@ impl<'a> Writer<'a> {
self.line("TP");
let mut para = 0usize;
let mut para_start = true;
// No character of the current paragraph has been written.
let mut line_start = true;
for run in &t.runs {
let text = if run.style.all_caps { run.text.to_uppercase() } else { run.text.clone() };
let mut pieces = text.split('\n').peekable();
@@ -856,14 +858,38 @@ impl<'a> Writer<'a> {
para_start = false;
}
self.char_style(&run.style, t.para_at(para));
let mut bytes: Vec<u8> = piece.chars().filter_map(latin::encode).collect();
// The space before a line's first character, kerning before it (§15.4.6.1).
if line_start && !piece.is_empty() && run.style.kerning_before != 0.0 {
self.kern(run.style.kerning_before);
}
line_start = false;
// Manual kerning after each character (0 included, which differs from automatic
// kerning), a soft hyphen as a discretionary hyphen (§15.4.10.1).
let kerning = run.style.kerning;
let mut bytes = vec![];
for c in piece.chars() {
if c == '\u{ad}' {
self.text_string(&mut bytes);
self.line("T+");
if let Some(k) = kerning {
self.kern(k);
}
continue;
}
let Some(b) = latin::encode(c) else { continue };
bytes.push(b);
if let Some(k) = kerning {
self.text_string(&mut bytes);
self.kern(k);
}
}
if ends_paragraph {
bytes.push(b'\r');
para += 1;
para_start = true;
line_start = true;
}
self.body.push_str(&ps::bytes(&bytes));
self.line(" Tx");
self.text_string(&mut bytes);
}
}
if self.kumi {
@@ -873,6 +899,22 @@ impl<'a> Writer<'a> {
self.line("TO");
}
/// `bytes` as a string of characters, `(…) Tx`, when there are any; `bytes` is left empty.
fn text_string(&mut self, bytes: &mut Vec<u8>) {
if !bytes.is_empty() {
self.body.push_str(&ps::bytes(bytes));
self.line(" Tx");
bytes.clear();
}
}
/// Manual kerning of `k` 1/1000 em between the characters before and after it: `0 k Tk`.
fn kern(&mut self, k: f64) {
self.body.push_str("0 ");
ps::push_num(&mut self.body, finite(k, 0.0));
self.line(" Tk");
}
/// A paragraph's attributes: alignment `Ta` and indents `Ti` (first line's, left, right).
fn paragraph(&mut self, p: &ParaStyle) {
let align = match p.justify {