From f9a2abad18eb1891e7ea1c107836138bcb149f16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:01:23 -0800 Subject: [PATCH 01/26] Paragraph: Kurikaeshi Moji Shori draws a line-start repeat mark as the character it repeats MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paragraph panel menu > Kurikaeshi Moji Shori (text.setFormat {kurikaeshiMojiShori}) is a paragraph attribute, off by default, saved only when on and carried by paragraph styles. On, a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, with the mark's width, and the text keeps the mark. Threaded type looks back into the frames before when a paragraph continues. Live SVG text writes the drawn character and places the text after it. --- crates/doc/src/live/envelope.rs | 1 + crates/doc/src/text.rs | 6 + crates/doc/src/text/object.rs | 1 + crates/doc/src/text/para_style.rs | 9 ++ crates/engine/src/cmd/panelcmds.rs | 6 +- crates/engine/src/cmd/textedit.rs | 2 + crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/threads.rs | 36 +++++- crates/engine/src/cmd/threads/tests.rs | 36 ++++++ crates/engine/src/cmd/typecmd/area_tests.rs | 56 +++++++++ crates/svg/src/export/text.rs | 27 ++++- crates/svg/tests/it/text_layout.rs | 31 +++++ crates/text/src/layout/flow.rs | 45 ++++++- crates/text/src/lib.rs | 7 +- crates/text/src/shape.rs | 59 ++++++++++ crates/text/src/test_fonts.rs | 53 +++++++++ crates/text/src/tests.rs | 117 +++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/paragraph.rs | 17 ++- crates/ui-egui/src/panels/paragraph/tests.rs | 31 +++++ docs/mcp.md | 24 ++++ docs/type-parity.md | 1 + 49 files changed, 583 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 5aa43b0a67..a0ad0eb1e4 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> { let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits))); for h in &mut feed.0 { h.write_u8(u8::from(text.first_para_continues)); + h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from)); for b in inline_bounds.clone() { match b { None => h.write_u8(0), diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d165a086fb..064f18effe 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -67,6 +67,12 @@ pub struct TextObject { /// it on a frame that leaves its thread and on a copy. Not saved. #[serde(skip)] pub first_para_continues: bool, + /// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the + /// last character of that paragraph in the frames before that a repeat mark could stand for + /// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout + /// reads it only while `first_para_continues` is on. Not saved. + #[serde(skip)] + pub first_para_lead: Option, /// Area Type Options (area type only). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub area: AreaOptions, diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index b787cebfe0..617d860927 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -94,6 +94,7 @@ impl TextObject { para: ParaStyle::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: AreaOptions::default(), path_effect: PathEffect::default(), path_align: PathAlign::default(), diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index c3db242ed0..62c6b8dd33 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -271,6 +271,9 @@ pub struct ParaStyle { /// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept /// with kinsoku None, where it has no effect. Off by default. pub bunri_kinshi: bool, + /// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts + /// a line is drawn as the character it repeats, and the text keeps the mark. Off by default. + pub kurikaeshi_moji_shori: bool, /// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and /// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses, /// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari. @@ -375,6 +378,8 @@ struct ParaStyleFile { #[serde(default, skip_serializing_if = "crate::skip::is_default")] bunri_kinshi: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kurikaeshi_moji_shori: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, @@ -412,6 +417,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -439,6 +445,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -470,6 +477,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -496,6 +504,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 20905ffdae..e012257c53 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default),direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -522,6 +522,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "romanHangingPunctuation", "koreanLineBreakAnywhere", "bunriKinshi", + "kurikaeshiMojiShori", ], C, )?; @@ -597,6 +598,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "kinsoku", "kinsokuType", "bunriKinshi", + "kurikaeshiMojiShori", "direction", "leadingModel", "charAlign", @@ -989,6 +991,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = flag("bunriKinshi") { para.bunri_kinshi = v; } + // An omitted or null value keeps the paragraph's own. + para.kurikaeshi_moji_shori = flag("kurikaeshiMojiShori").unwrap_or(para.kurikaeshi_moji_shori); if let Some(v) = direction { para.direction = v; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 769ca7e6c5..0602e23a9a 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1806,6 +1806,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { para: super::create::new_type_para(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), @@ -2112,6 +2113,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option { para: Default::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 18f87d44f7..a6878032b0 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -253,6 +253,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map { ("kinsoku", json!(v.kinsoku)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), + ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index ad41d1d220..7ccf26d3de 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { .collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s); - for (id, part) in live.iter().zip(parts) { + let texts: Vec = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect(); + let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::>()); + for ((id, part), lead) in live.iter().zip(parts).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) { let mut next = (**t).clone(); next.runs = part.runs; @@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { || part.list_count != t.list_count || part.list_level_counts != t.list_level_counts || continues != t.first_para_continues + || lead != t.first_para_lead { t.runs = next.runs; t.para = next.para; @@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { t.list_count = part.list_count; t.list_level_counts = part.list_level_counts; t.first_para_continues = continues; + t.first_para_lead = lead; refresh_bounds(t); } } @@ -384,17 +388,43 @@ pub(crate) fn mark_continued(doc: &mut Document) { let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect(); let marks = vectorcraft_text::thread::continued(&frames); - for (id, on) in live.iter().zip(marks) { + let texts: Vec = frames.iter().map(|t| t.plain_text()).collect(); + let leads = first_para_leads(&texts, &marks); + for ((id, on), lead) in live.iter().zip(marks).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) - && t.first_para_continues != on + && (t.first_para_continues != on || t.first_para_lead != lead) { t.first_para_continues = on; + t.first_para_lead = lead; refresh_bounds(t); } } } } +/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and +/// whether each one's first paragraph `continues` from the frame before: the last character of +/// that paragraph in the frames before that a repeat mark could stand for, or None. +fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { + (0..texts.len()) + .map(|k| { + let mut j = k; + while continues.get(j) == Some(&true) && j > 0 { + j -= 1; + let text = texts.get(j)?; + let tail = text.rfind('\n').map_or(Some(text.as_str()), |at| text.get(at + 1..))?; + if let Some(c) = vectorcraft_text::repeat_base(tail) { + return Some(c); + } + if tail.len() != text.len() { + return None; + } + } + None + }) + .collect() +} + #[cfg(test)] thread_local! { /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 2694a61e6c..ba2cbaa1d4 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2226,3 +2226,39 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0); } + +/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of +/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that +/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph +/// carries none. Flowing the story and opening a file both set it. +#[test] +fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { + let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::>(), continues); + assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]); + assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]); + assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]); + assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]); + assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]); + assert_eq!(leads(&[], &[]), Vec::>::new()); + // Opening a file marks the frames as they were saved. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let mut ids = Vec::new(); + for (x, text) in [(10, "日時"), (200, "々す")] { + let id = + s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + ids.push(NodeId(id)); + } + let mut d = (*s.doc().unwrap().doc).clone(); + d.text_threads = vec![ids.clone()]; + mark_continued(&mut d); + let tb = text_of(&d, ids[1]).unwrap(); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, Some('時')); + // Flowing the story through the frames sets it from the text each frame now holds. + reflow(&d.clone(), &mut d); + let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap()); + assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す"); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); +} diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index a63ebff9c4..6cff9a95a4 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -504,6 +504,62 @@ fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() { assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi); } +/// Paragraph panel menu › Kurikaeshi Moji Shori: off for new type and for a paragraph saved before +/// it, and saved only when on; `text.setFormat {kurikaeshiMojiShori}` sets it per paragraph in one +/// undo step, records nothing when the paragraphs already have the value, refuses a value that is +/// not true or false, and paragraph styles carry it. The text keeps its repeat marks. +#[test] +fn kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "時々\nすゝ"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori, "new type has it off"); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kurikaeshi_moji_shori").is_none()); + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(!old.kurikaeshi_moji_shori, "saved before the option: off"); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the second paragraph. + let second = "時々\n".len(); + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(text(&s).plain_text(), "時々\nすゝ", "the text keeps its marks"); + // The same value again records nothing. + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let saved = serde_json::to_value(text(&s).para_at(1)).unwrap(); + assert_eq!(saved["kurikaeshi_moji_shori"], true); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap(); + assert!(back.kurikaeshi_moji_shori); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert!(!back.para_at(0).kurikaeshi_moji_shori && back.para_at(1).kurikaeshi_moji_shori, "the file keeps it per paragraph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(1).kurikaeshi_moji_shori); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"ids": [id], "kurikaeshiMojiShori": bad, "kinsoku": "none"})).is_err(), "{bad}"); + } + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "kurikaeshiMojiShori": false})).is_err()); + assert!( + text(&s).para_at(1).kurikaeshi_moji_shori && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None, + "a refused call changes nothing" + ); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Repeats", "attrs": {"kurikaeshi_moji_shori": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Repeats", "id": id})).unwrap(); + assert!(text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("paraStyle.new", &json!({"name": "Marks", "attrs": {"kurikaeshi_moji_shori": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Marks", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && !text(&s).para_at(1).kurikaeshi_moji_shori); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 2f8e8b8a1b..5a1e811062 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -491,7 +491,11 @@ impl Writer<'_> { }); let Some(chars) = self.fonts.get_mut(at).map(|u| &mut u.chars) else { continue }; // As written: a list marker's characters, a hyphen where a line breaks, capitals for All - // Caps, the style's Digits. + // Caps, the style's Digits, the character a repeat mark is drawn as. + if let Some(c) = shown_repeat(lay, i, g) { + chars.insert(c); + continue; + } let src = lay.marker_text(i).unwrap_or_else(|| if g.len == 0 { "-" } else { plain.get(g.byte..g.byte + g.len).unwrap_or("") }); for c in src.chars().filter(|c| !c.is_control() && *c != '\u{ad}').map(|c| st.digits.map(c)) { if st.all_caps { @@ -716,6 +720,17 @@ struct Segment { /// given its own position (points). const PLACE_TOLERANCE: f64 = 1e-6; +/// Kurikaeshi Moji Shori: the character glyph `i` of `lay` shows when the layout drew a repeat mark +/// as the character it repeats ([`vectorcraft_text::TextLayout::repeat_marks`]), or None. +fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_text::PositionedGlyph) -> Option { + if lay.repeat_marks.is_empty() || g.len == 0 || lay.marker_text(i).is_some() { + return None; + } + // The marks are in text order, one per line. + let at = lay.repeat_marks.binary_search_by_key(&g.byte, |&(byte, _)| byte).ok()?; + lay.repeat_marks.get(at).map(|&(_, c)| c) +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -804,9 +819,15 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - } None => (g.advance, g.origin.x), }; - let src: String = source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(); + let repeat = shown_repeat(lay, line.glyph_start + k, g); + let src: String = match repeat { + Some(c) => c.to_string(), + None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), + }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; - let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)); + // The character a repeat mark is drawn as takes the mark's width on the canvas, which a + // reader does not know: the text after it is placed anew. + let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)) || repeat.is_some(); // A glyph Glyph Scaling widens or narrows is a segment of its own, stretched to its width. let scale = if reader.is_some() && (g.scale - 1.0).abs() > 1e-9 && g.scale.is_finite() { g.scale } else { 1.0 }; let fresh = std::mem::take(&mut after_inline) || scale != 1.0 || segs.last().is_some_and(|last| last.scale != 1.0); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index c53318c358..a190f21dea 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -910,3 +910,34 @@ fn paragraphs_aligned_differently_keep_their_alignment() { assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.01); } } + +/// With Kurikaeshi Moji Shori on, live type writes a repeat mark that starts a line as the +/// character it is drawn as and places the text after it anew, with and without embedded fonts; a +/// mark inside a line stays. +#[test] +fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), ..style(12.0) }; + for on in [false, true] { + let mut t = TextObject::point(Point::new(20.0, 40.0), "龘\u{2028}々龘龘々", st.clone()); + t.para.kurikaeshi_moji_shori = on; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + for embed_fonts in [false, true] { + let svg = export(&d, &ExportOptions { embed_fonts, ..Default::default() }); + if !on { + assert!(svg.contains(">々龘龘々<"), "{svg}"); + continue; + } + // The drawn character takes the mark's width on the canvas, so the text after it is + // placed where the canvas draws it. + let rest = svg.find(">龘龘々<").unwrap_or_else(|| panic!("{svg}")); + let tag = &svg[svg[..rest].rfind('<').unwrap_or(0)..rest]; + assert!(tag.contains(" x=\""), "{tag}: {svg}"); + assert_eq!(svg.matches('々').count(), 1, "only the mark inside the line stays: {svg}"); + } + } +} diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 0c4e1ae615..f028d47898 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -13,7 +13,7 @@ use super::{ is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words}; +use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeated_char, shape_range}; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -213,6 +213,9 @@ struct ParagraphData<'a, 'text> { bidi: Option>, rtl: bool, continued: bool, + /// Kurikaeshi Moji Shori: the character before a `continued` paragraph in the frames before + /// ([`TextObject::first_para_lead`]). + lead: Option, sg: Vec, compressed: Vec, wakan: Vec, @@ -331,6 +334,7 @@ fn prepare_paragraph<'a, 'text>( bidi, rtl, continued, + lead: t.first_para_lead.filter(|_| continued), sg, compressed, wakan, @@ -1272,6 +1276,40 @@ fn emit_line_glyph( cx.emit(glyph, Affine::translate(at.to_vec2()), at, 0.0, w.advance, line_index); } +/// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of +/// a line of the paragraph starting at byte `para_start`, when `g` is a repeat mark, and the +/// character it shows: the character [`repeated_char`] gives, shaped in the mark's style with the +/// type's features (so vertical type gets the font's vertical forms), from the same face, with the +/// mark's advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, +/// belongs to a tate-chu-yoko or warichu block, nothing before it in the paragraph fits, or the face +/// draws the character with no glyph or with more than one. `lead` stands before a paragraph that +/// continues from the frame before ([`TextObject::first_para_lead`]). +fn repeat_mark_glyph(cx: &Ctx<'_>, para_start: usize, lead: Option, g: &SGlyph) -> Option<(SGlyph, char)> { + if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() { + return None; + } + let c = repeated_char(lead, cx.text.get(para_start..g.byte)?, g.ch)?; + let mut buf = [0; 4]; + let s: &str = c.encode_utf8(&mut buf); + let mut shaped = Vec::with_capacity(1); + shape_range(cx.db, s, 0..s.len(), &[(0..s.len(), cx.style_at(g.byte))], &[], &cx.opts.features, &[], &mut shaped); + let [one] = shaped.as_slice() else { return None }; + (one.gid != 0 && one.face.id() == g.face.id()).then(|| (SGlyph { gid: one.gid, ..g.clone() }, c)) +} + +/// Kurikaeshi Moji Shori: the glyph drawn in place of glyph `first` of `paragraph`, the first +/// character of a line that ends before glyph `end`, when the paragraph has the setting on and +/// [`repeat_mark_glyph`] gives one; it is recorded in [`crate::TextLayout::repeat_marks`]. +fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: usize, end: usize) -> Option { + if !paragraph.para.kurikaeshi_moji_shori || first >= end { + return None; + } + let g = paragraph.sg.get(first)?; + let (glyph, c) = repeat_mark_glyph(cx, paragraph.pr.start, paragraph.lead, g)?; + cx.out.repeat_marks.push((g.byte, c)); + Some(glyph) +} + /// Lay out `line` of `paragraph` as `justification` aligns it: each glyph placed along the /// baseline (tabs as [`tab_glyph`] sets them), its hyphen, and the line's record, then the pen /// moved on past it. @@ -1306,9 +1344,14 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData let mut marker_tab = 0; // The warichu blocks drawn on the line: the byte that names each and where it starts. let mut wari_blocks: Vec<(usize, f64)> = Vec::new(); + // Kurikaeshi Moji Shori: the line's first character after any list marker, drawn as the + // character it repeats when it is a repeat mark. + let first = index.max(paragraph.marker); + let repeat = line_start_repeat(cx, paragraph, first, position.end); for (order_index, &offset) in order.iter().enumerate() { let glyph_index = index + offset; let Some(glyph) = sg.get(glyph_index) else { continue }; + let glyph = if glyph_index == first { repeat.as_ref().unwrap_or(glyph) } else { glyph }; let mut advance = glyph.adv; if glyph_index + 1 == trimmed { advance -= line.end_trim; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..506b7e5b03 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -54,7 +54,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::{aki_space, inseparable, line_start_space, spacing_scale}; +pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; @@ -401,6 +401,10 @@ pub struct TextLayout { pub inlines: Vec, /// List markers, in text order. pub markers: Vec, + /// Kurikaeshi Moji Shori: the repeat marks drawn as the character they stand for, as (the + /// mark's byte offset in the plain text, the character drawn), in text order. Writers that put + /// characters in place of glyphs (live SVG text) write that character. + pub repeat_marks: Vec<(usize, char)>, } impl Default for TextLayout { @@ -419,6 +423,7 @@ impl Default for TextLayout { path_fill: None, inlines: Vec::new(), markers: Vec::new(), + repeat_marks: Vec::new(), } } } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 13cd2e06de..9d09ce076e 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -450,6 +450,65 @@ pub fn inseparable(a: char, b: char) -> bool { ) } +/// Kurikaeshi Moji Shori: the last character of `text` that a repeat mark after it could stand for: +/// the last one that is neither a repeat mark, a soft return (U+2028) nor a combining voicing mark +/// (U+3099, U+309A), or None when there is none. The engine gives a threaded frame whose first +/// paragraph continues from the frame before the result for the text before it +/// (`TextObject::first_para_lead`). +pub fn repeat_base(text: &str) -> Option { + text.chars().rev().find(|&c| !matches!(c, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '\u{2028}' | '\u{3099}' | '\u{309A}')) +} + +/// Kurikaeshi Moji Shori: the character the repeat mark `mark` stands for after the text `before` +/// it, or None when `mark` is not a repeat mark or nothing before it fits. `lead` stands before +/// `before` (the text of a threaded paragraph in the frames before). VectorCraft's rules: the +/// repeated character is the last one before the mark that is neither a repeat mark, a soft return +/// (U+2028) nor a combining voicing mark ([`repeat_base`]); 々 repeats a Han ideograph, ゝ and ゞ a +/// hiragana and ヽ and ヾ a katakana. ゝ and ヽ give the kana without its voicing marks, and ゞ and +/// ヾ its voiced form, or the plain kana when it has none. +pub(crate) fn repeated_char(lead: Option, before: &str, mark: char) -> Option { + let script = match mark { + '々' => Script::Han, + 'ゝ' | 'ゞ' => Script::Hiragana, + 'ヽ' | 'ヾ' => Script::Katakana, + _ => return None, + }; + let base = repeat_base(before).or(lead)?; + if base.script() != script || (script != Script::Han && !matches!(base as u32, 0x3041..=0x3096 | 0x30A1..=0x30F6)) { + return None; + } + if script == Script::Han { + return Some(base); + } + // Katakana from U+30A1 to U+30F6 lie 0x60 past their hiragana, so one table serves both. + let shift = if script == Script::Katakana { 0x60 } else { 0 }; + let plain = unvoiced(base as u32 - shift); + let kana = if matches!(mark, 'ゞ' | 'ヾ') { voiced(plain).unwrap_or(plain) } else { plain }; + char::from_u32(kana + shift) +} + +/// The hiragana `h` (a code point) without its dakuten or handakuten. +fn unvoiced(h: u32) -> u32 { + match h { + 0x304C..=0x3062 if h.is_multiple_of(2) => h - 1, + 0x3065 | 0x3067 | 0x3069 => h - 1, + 0x3070..=0x307D => h - (h - 0x306F) % 3, + 0x3094 => 0x3046, + _ => h, + } +} + +/// The voiced form (with dakuten) of the plain hiragana `h`, if it has one. +fn voiced(h: u32) -> Option { + match h { + 0x304B..=0x3061 if !h.is_multiple_of(2) => Some(h + 1), + 0x3064 | 0x3066 | 0x3068 => Some(h + 1), + 0x306F..=0x307B if (h - 0x306F).is_multiple_of(3) => Some(h + 1), + 0x3046 => Some(0x3094), + _ => None, + } +} + /// Is `c` Hangul: a syllable, a jamo or a compatibility jamo (full or half width)? pub(crate) fn is_hangul(c: char) -> bool { c.script() == Script::Hangul diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d17ce78603..4a4297c33a 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -484,6 +484,59 @@ pub fn full_width_font() -> Option> { Some(builder.build()) } +/// The family of [`repeat_mark_font`]. +pub const REPEAT_MARK_FAMILY: &str = "Repeattest Sans"; + +/// The Japanese characters [`repeat_mark_font`] maps, each to the glyph of the Latin capital beside +/// it: an ideograph, the repeat marks, and kana with and without their voicing marks. +pub const REPEAT_MARK_CHARS: [(char, char); 11] = + [('時', 'A'), ('々', 'B'), ('す', 'C'), ('ず', 'D'), ('ゝ', 'E'), ('ゞ', 'F'), ('サ', 'G'), ('ザ', 'H'), ('ヽ', 'I'), ('ヾ', 'J'), ('あ', 'K')]; + +/// A test-only cmap over bundled Source Sans 3: each of [`REPEAT_MARK_CHARS`] uses the glyph of its +/// Latin capital, so the glyph drawn for a repeat mark tells which character was drawn; the space +/// keeps its own glyph. +pub fn repeat_mark_font() -> Option> { + repeat_font(REPEAT_MARK_FAMILY, &REPEAT_MARK_CHARS) +} + +/// The family of [`rare_repeat_mark_font`]. +pub const RARE_REPEAT_MARK_FAMILY: &str = "Raretest Sans"; + +/// [`repeat_mark_font`] for tests that add it to the shared [`crate::FontDb::global`]: it maps +/// only 龘 (to the glyph of A) and 々 (to the glyph of B), characters no other text in those tests +/// uses, so other tests' Japanese text does not fall back to it. +pub fn rare_repeat_mark_font() -> Option> { + repeat_font(RARE_REPEAT_MARK_FAMILY, &[('龘', 'A'), ('々', 'B')]) +} + +/// A font named `family` over bundled Source Sans 3 whose cmap maps each of `chars` to the glyph of +/// the Latin capital beside it, and the space to its own glyph. +fn repeat_font(family: &str, chars: &[(char, char)]) -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mut mappings: Vec<(char, write_fonts::types::GlyphId)> = Vec::new(); + for &(c, latin) in chars.iter().chain(&[(' ', ' ')]) { + mappings.push((c, write_fonts::types::GlyphId::new(charmap.map(latin)?.to_u32()))); + } + let cmap = Cmap::from_mappings(mappings).ok()?; + let full = format!("{family} Regular"); + let postscript = format!("{}-Regular", family.replace(' ', "")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GSUB") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`half_form_font`]. pub const HALF_FORM_FAMILY: &str = "Halftest Sans"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4bab8aa561..477c3e3392 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2693,6 +2693,123 @@ fn bunri_kinshi_keeps_two_em_dashes_on_one_line() { assert_eq!(ends(&t), [kept, text.len(), second + split, second + text.len()]); } +/// Kurikaeshi Moji Shori: the character a repeat mark stands for is the last one before it that is +/// not a repeat mark, in the mark's script; ゝ and ヽ give it without voicing marks, ゞ and ヾ give +/// its voiced form when it has one. +#[test] +fn repeat_marks_stand_for_the_character_before_them() { + use crate::shape::repeated_char; + for (before, mark, want) in [ + ("時", '々', Some('時')), + ("時々", '々', Some('時')), + ("時\u{2028}", '々', Some('時')), + ("す", 'ゝ', Some('す')), + ("ず", 'ゝ', Some('す')), + ("す", 'ゞ', Some('ず')), + ("ず", 'ゞ', Some('ず')), + ("ぱ", 'ゝ', Some('は')), + ("は", 'ゞ', Some('ば')), + ("ぽ", 'ゞ', Some('ぼ')), + ("つ", 'ゞ', Some('づ')), + ("う", 'ゞ', Some('ゔ')), + ("あ", 'ゞ', Some('あ')), + ("サ", 'ヽ', Some('サ')), + ("ザ", 'ヽ', Some('サ')), + ("サ", 'ヾ', Some('ザ')), + ("ウ", 'ヾ', Some('ヴ')), + ("ピ", 'ヾ', Some('ビ')), + ("サ", 'ゝ', None), + ("す", 'ヽ', None), + ("す", '々', None), + ("時", 'ゝ', None), + ("A", '々', None), + ("", '々', None), + ("々ゝ", '々', None), + ("時", 'x', None), + // A kana followed by a combining voicing mark is that kana. + ("か\u{3099}\u{2028}", 'ゝ', Some('か')), + ("か\u{3099}", 'ゞ', Some('が')), + ("ハ\u{309A}", 'ヽ', Some('ハ')), + ] { + assert_eq!(repeated_char(None, before, mark), want, "{before:?} {mark}"); + } + // The character before a paragraph that continues from the frame before stands in when the text + // before the mark in this frame has none. + assert_eq!(repeated_char(Some('時'), "", '々'), Some('時')); + assert_eq!(repeated_char(Some('時'), "\u{2028}々", '々'), Some('時')); + assert_eq!(repeated_char(Some('時'), "日", '々'), Some('日')); + assert_eq!(repeated_char(Some('す'), "", '々'), None); +} + +/// Kurikaeshi Moji Shori (a paragraph attribute): on, a repeat mark that starts a line is drawn as +/// the character it repeats, in point and area type, horizontal and vertical, at a soft return or +/// where a line wraps; a mark inside a line, one starting a paragraph and every mark with the +/// setting off keep their own glyph. The line breaks and the glyphs' bytes do not change. Uses a test +/// font that draws each character with a different Latin glyph. +#[test] +fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let glyph = |c: char| Some(face.glyph_for(c)); + let gid_of = |l: &TextLayout, b: usize| l.glyphs.iter().find(|g| g.byte == b).map(|g| g.gid); + let ends = |l: &TextLayout| l.lines.iter().map(|line| line.end).collect::>(); + // 時 | 々す | ゞ時々ザ | ヽ, then a paragraph that starts with 々. + let text = "時\u{2028}々す\u{2028}ゞ時々ザ\u{2028}ヽ\n々"; + let at = |s: &str| text.find(s).unwrap(); + let (first_mark, voiced, inner, katakana, para_start) = (at("々す"), at("ゞ"), at("時々ザ") + "時".len(), at("ヽ"), text.len() - "々".len()); + for vertical in [false, true] { + let mut t = TextObject::point(Point::ZERO, text, st.clone()); + t.vertical = vertical; + let off = layout(&db, &t); + t.set_paragraph_styles(vec![ + vectorcraft_doc::ParaStyle { kurikaeshi_moji_shori: true, ..t.para.clone() }, + vectorcraft_doc::ParaStyle { kurikaeshi_moji_shori: true, ..t.para.clone() }, + ]); + let on = layout(&db, &t); + assert_eq!(ends(&on), ends(&off), "vertical {vertical}"); + let bytes = |l: &TextLayout| l.glyphs.iter().map(|g| g.byte).collect::>(); + assert_eq!(bytes(&on), bytes(&off), "vertical {vertical}"); + // Off, each mark has its own glyph. + for (b, mark) in [(first_mark, '々'), (voiced, 'ゞ'), (inner, '々'), (katakana, 'ヽ'), (para_start, '々')] { + assert_eq!(gid_of(&off, b), glyph(mark), "vertical {vertical}: off, {mark} at {b}"); + } + assert_eq!(gid_of(&on, first_mark), glyph('時'), "vertical {vertical}: 々 drawn as 時"); + assert_eq!(gid_of(&on, voiced), glyph('ず'), "vertical {vertical}: ゞ after す drawn as ず"); + assert_eq!(gid_of(&on, katakana), glyph('サ'), "vertical {vertical}: ヽ after ザ drawn as サ"); + assert_eq!(gid_of(&on, inner), glyph('々'), "vertical {vertical}: a mark inside a line keeps its glyph"); + assert_eq!(gid_of(&on, para_start), glyph('々'), "vertical {vertical}: a paragraph's first mark keeps its glyph"); + assert!(off.repeat_marks.is_empty()); + assert_eq!(on.repeat_marks, [(first_mark, '時'), (voiced, 'ず'), (katakana, 'サ')], "vertical {vertical}"); + } + // Where area type wraps: each line holds one character, so 々 starts the second line. + let mut t = TextObject::point(Point::ZERO, "時々", st.clone()); + let both: f64 = layout(&db, &t).glyphs.iter().map(|g| g.advance).sum(); + t.xf = Affine::IDENTITY; + // The Soft set lets 々 start a line. + t.para.kinsoku = vectorcraft_doc::Kinsoku::Soft; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, both - 1.0, 200.0).to_path(0.1)) }; + let off = layout(&db, &t); + assert_eq!(ends(&off), ["時".len(), "時々".len()]); + t.para.kurikaeshi_moji_shori = true; + let on = layout(&db, &t); + assert_eq!(ends(&on), ends(&off)); + assert_eq!(gid_of(&off, "時".len()), glyph('々')); + assert_eq!(gid_of(&on, "時".len()), glyph('時'), "a wrapped line's 々 is drawn as 時"); + // A threaded frame whose first paragraph continues: a mark that starts the frame is drawn as the + // character before it in the frame before, only while the paragraph continues. + let mut t = TextObject::point(Point::ZERO, "々す\n々", st.clone()); + t.para.kurikaeshi_moji_shori = true; + t.first_para_lead = Some('時'); + assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "a frame that does not continue"); + t.first_para_continues = true; + let on = layout(&db, &t); + assert_eq!(gid_of(&on, 0), glyph('時'), "the frame's first 々 is drawn as 時"); + assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..466bf21b1b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2978,6 +2978,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Латинска висяща пунктуация Korean Line Break Anywhere Пренасяне на корейски текст навсякъде Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Настройки за източноазиатска композиция Korean Composition Settings Настройки за корейска композиция Rotate Завъртане diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..b0d3668edf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2076,6 +2076,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Latinična viseća interpunkcija Korean Line Break Anywhere Prelom korejskog reda bilo gdje Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Postavke istočnoazijske kompozicije Korean Composition Settings Postavke korejske kompozicije Select a text object to edit its paragraph attributes. Odaberite tekstualni objekat da uredite njegove atribute pasusa. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..e9c8189f1e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3810,6 +3810,7 @@ digits Malayalam Malaiàlam Roman Hanging Punctuation Puntuació penjant romana Korean Line Break Anywhere Salt de línia coreà a qualsevol lloc Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Configuració de composició de l’Àsia oriental Korean Composition Settings Configuració de composició coreana Rotate Gira diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..7cac30c893 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2147,6 +2147,7 @@ digits Malayalam Malajálamské Roman Hanging Punctuation Visící latinková interpunkce Korean Line Break Anywhere Zalomení korejského řádku kdekoli Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Nastavení východoasijské sazby Korean Composition Settings Nastavení korejské sazby Select a text object to edit its paragraph attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho odstavce. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..6b97db1903 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2565,6 +2565,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Romersk hængende tegnsætning Korean Line Break Anywhere Koreansk linjeskift hvor som helst Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Indstillinger for østasiatisk komposition Korean Composition Settings Indstillinger for koreansk komposition Select a text object to edit its paragraph attributes. Markér et tekstobjekt for at redigere dets afsnitsattributter. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..fbb09e5340 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3021,6 +3021,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Hängende Interpunktion (lateinisch) Korean Line Break Anywhere Koreanischer Zeilenumbruch überall Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Einstellungen für ostasiatischen Satz Korean Composition Settings Einstellungen für koreanischen Satz Rotate Drehen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..b71d14db76 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2073,6 +2073,7 @@ font-technology Variable Μεταβλητές Roman Hanging Punctuation Κρεμαστή στίξη όρθιας γραφής Korean Line Break Anywhere Αλλαγή γραμμής κορεατικών οπουδήποτε Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ρυθμίσεις σύνθεσης ανατολικής Ασίας Korean Composition Settings Ρυθμίσεις κορεατικής σύνθεσης Rotate Περιστροφή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..eb281bb92e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3057,6 +3057,7 @@ digits Malayalam Malayálam Roman Hanging Punctuation Puntuación colgante romana Korean Line Break Anywhere Salto de línea coreano en cualquier lugar Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ajustes de composición de Asia oriental Korean Composition Settings Ajustes de composición coreana Rotate Rotar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..d50fbf4ad3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2110,6 +2110,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Latinalaiset riippuvat välimerkit Korean Line Break Anywhere Korean rivinvaihto missä tahansa Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Itäaasialaisen ladonnan asetukset Korean Composition Settings Korean ladonnan asetukset Select a text object to edit its paragraph attributes. Valitse tekstiobjekti, jonka kappalemääritteitä haluat muokata. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..d04586aa05 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3049,6 +3049,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Ponctuation romaine hors justification Korean Line Break Anywhere Saut de ligne coréen n’importe où Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Paramètres de composition d’Asie orientale Korean Composition Settings Paramètres de composition coréenne Rotate Rotation diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..108352cc12 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4465,6 +4465,7 @@ antiAlias Sharp શાર્પ Save Prominent Colors મુખ્ય રંગો સાચવો Korean Line Break Anywhere કોરિયન લાઇન ગમે ત્યાં તોડો Bunri-Kinshi બુનરી-કિન્શી + Kurikaeshi Moji Shori કુરિકાએશી મોજી શોરી East Asian Composition Settings પૂર્વ એશિયાઈ કમ્પોઝિશન સેટિંગ્સ Korean Composition Settings કોરિયન કમ્પોઝિશન સેટિંગ્સ Show Bounding Box While Moving and Drawing ખસેડતી અને દોરતી વખતે બાઉન્ડિંગ બોક્સ બતાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..0d5de80b4e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4187,6 +4187,7 @@ antiAlias Sharp शार्प Roman Hanging Punctuation रोमन हैंगिंग विराम चिह्न Korean Line Break Anywhere कोरियाई लाइन ब्रेक कहीं भी Bunri-Kinshi बुनरी-किंशी + Kurikaeshi Moji Shori कुरिकाएशी मोजी शोरी East Asian Composition Settings पूर्वी एशियाई संरचना सेटिंग्स Korean Composition Settings कोरियाई संरचना सेटिंग्स Rotate घुमाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..f94014cb6f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3645,6 +3645,7 @@ mark-style Japanese Japán Roman Hanging Punctuation Latin függő írásjelek Korean Line Break Anywhere Koreai sortörés bárhol Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Kelet-ázsiai szedési beállítások Korean Composition Settings Koreai szedési beállítások Rotate Elforgatás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..0d369293a0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1899,6 +1899,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Tanda baca gantung Romawi Korean Line Break Anywhere Putus baris Korea di mana saja Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Pengaturan komposisi Asia Timur Korean Composition Settings Pengaturan komposisi Korea Select a text object to edit its paragraph attributes. Pilih objek teks untuk mengedit atribut paragrafnya. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..70d3026e6a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3098,6 +3098,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Punteggiatura sporgente romana Korean Line Break Anywhere Interruzione di riga coreana ovunque Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Impostazioni di composizione dell’Asia orientale Korean Composition Settings Impostazioni di composizione coreana Rotate Ruota diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..563a2b1966 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3064,6 +3064,7 @@ mark-style Japanese 日本式 Roman Hanging Punctuation 欧文ぶら下がり Korean Line Break Anywhere 韓国語の任意位置での改行 Bunri-Kinshi 分離禁止 + Kurikaeshi Moji Shori 繰り返し文字処理 East Asian Composition Settings 東アジア言語の組版設定 Korean Composition Settings 韓国語の組版設定 Rotate 回転 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..12be5345a9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3955,6 +3955,7 @@ digits Malayalam მალაიალამური Roman Hanging Punctuation რომაული გამოწეული პუნქტუაცია Korean Line Break Anywhere კორეული სტრიქონის გადატანა ნებისმიერ ადგილას Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings აღმოსავლეთ აზიური აწყობის პარამეტრები Korean Composition Settings კორეული აწყობის პარამეტრები Select a text object to edit its paragraph attributes. აბზაცის ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..ca1687819b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3053,6 +3053,7 @@ mark-style Japanese 일본식 Roman Hanging Punctuation 로마자 걸림 문장 부호 Korean Line Break Anywhere 한글 어디서나 줄 바꿈 Bunri-Kinshi 분리 금지 + Kurikaeshi Moji Shori 반복 문자 처리 East Asian Composition Settings 동아시아 조판 설정 Korean Composition Settings 한글 조판 설정 Rotate 회전 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..513cb35895 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2461,6 +2461,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Romeinse hangende leestekens Korean Line Break Anywhere Koreaans regeleinde overal Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Instellingen voor Oost-Aziatische zetting Korean Composition Settings Instellingen voor Koreaanse zetting Select a text object to edit its paragraph attributes. Selecteer een tekstobject om de alineakenmerken ervan te bewerken. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..61b9465dec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2065,6 +2065,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Wysunięta interpunkcja łacińska Korean Line Break Anywhere Koreański podział wiersza w dowolnym miejscu Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ustawienia składu wschodnioazjatyckiego Korean Composition Settings Ustawienia składu koreańskiego Select a text object to edit its paragraph attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty akapitu. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..460e581b15 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2544,6 +2544,7 @@ digits Malayalam Malaiala Roman Hanging Punctuation Pontuação Pendurada Romana Korean Line Break Anywhere Quebra de Linha Coreana em Qualquer Lugar Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Configurações de Composição do Leste Asiático Korean Composition Settings Configurações de Composição Coreana Rotate Girar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..dca47d1e4c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3087,6 +3087,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Римская висячая пунктуация Korean Line Break Anywhere Перенос корейского текста в любом месте Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Параметры восточноазиатского набора Korean Composition Settings Параметры корейского набора Rotate Повернуть diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..e7f7555c6a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2991,6 +2991,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Hängande interpunktion (roman) Korean Line Break Anywhere Koreansk radbrytning var som helst Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Inställningar för östasiatisk sättning Korean Composition Settings Inställningar för koreansk sättning Rotate Rotera diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..4aca424124 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2826,6 +2826,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Roma Asılı Noktalama İşaretleri Korean Line Break Anywhere Korece Satırı Her Yerde Kes Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Doğu Asya Dizgi Ayarları Korean Composition Settings Korece Dizgi Ayarları Rotate Döndür diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..704309b261 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3090,6 +3090,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Римська висяча пунктуація Korean Line Break Anywhere Перенесення корейського тексту будь-де Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Параметри східноазійського набору Korean Composition Settings Параметри корейського набору Rotate Повернути diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..b2b5b8f0da 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3407,6 +3407,7 @@ mark-style Japanese Kiểu Nhật Roman Hanging Punctuation Dấu câu treo Roman Korean Line Break Anywhere Ngắt dòng tiếng Hàn ở bất kỳ đâu Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Cài đặt dàn trang Đông Á Korean Composition Settings Cài đặt dàn trang tiếng Hàn Rotate Xoay diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6105919a37 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2948,6 +2948,7 @@ digits Malayalam 马拉雅拉姆数字 Roman Hanging Punctuation 西文悬挂标点 Korean Line Break Anywhere 韩文任意位置换行 Bunri-Kinshi 分离禁止 + Kurikaeshi Moji Shori 重复字符处理 East Asian Composition Settings 东亚排版设置 Korean Composition Settings 韩文排版设置 Rotate 旋转 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..cae679bd47 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4176,6 +4176,7 @@ digits Malayalam 馬來亞拉姆數字 Roman Hanging Punctuation 羅馬懸掛標點 Korean Line Break Anywhere 韓文任意位置換行 Bunri-Kinshi 分離禁止 + Kurikaeshi Moji Shori 重複字元處理 East Asian Composition Settings 東亞排版設定 Korean Composition Settings 韓文排版設定 Rotate 旋轉 diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 3f1a56cee5..52b3135cc2 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -859,6 +859,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + // A repeat mark starting a line is drawn as the character it repeats. + let repeat = shared_para(app, |p| p.kurikaeshi_moji_shori) == Some(true); + if menu_item(ui, tl!("Kurikaeshi Moji Shori"), has, repeat) { + toggle_kurikaeshi_moji_shori(app); + } // How a line keeps the kinsoku characters off its ends: the selected paragraphs' type is // checked, and none is when they differ. let kinsoku_type = shared_para(app, |p| p.kinsoku_type); @@ -937,6 +942,14 @@ fn toggle_bunri_kinshi(app: &mut VectorcraftApp) { format(app, json!({"bunriKinshi": !on})); } +/// Kurikaeshi Moji Shori (Paragraph panel menu): the menu item is checked when every paragraph the +/// panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for all +/// of them otherwise, in one undo step. +fn toggle_kurikaeshi_moji_shori(app: &mut VectorcraftApp) { + let on = shared_para(app, |p| p.kurikaeshi_moji_shori) == Some(true); + format(app, json!({"kurikaeshiMojiShori": !on})); +} + /// Korean Line Break Anywhere (Paragraph panel menu): the menu item is checked when every paragraph /// the panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for /// all of them otherwise, in one undo step. @@ -949,7 +962,7 @@ fn toggle_korean_line_break_anywhere(app: &mut VectorcraftApp) { /// indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification /// options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi /// Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, -/// Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo +/// Kurikaeshi Moji Shori, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo /// step named Reset Panel (inside an undo group that is already open, as part of its step). fn reset_panel(app: &mut VectorcraftApp) { let h = HyphenationOptions::default(); @@ -971,7 +984,7 @@ fn reset_panel(app: &mut VectorcraftApp) { "autoLeading": j.auto_leading, "singleWordJustification": "fullJustify", "direction": "auto", "leadingModel": "romanBaseline", "mojikumi": "lineEndHalf", "burasagari": "standard", "kinsoku": "hard", "kinsokuType": "pushOutOnly", "composer": "everyLine", "romanHangingPunctuation": false, "koreanLineBreakAnywhere": false, - "bunriKinshi": false + "bunriKinshi": false, "kurikaeshiMojiShori": false }), ); para_cmd(app, "text.tabs.clear", json!({})); diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 11fd7fbafc..aebdbbf1cf 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -324,6 +324,37 @@ fn bunri_kinshi_toggle_follows_kinsoku_and_the_selected_paragraphs() { assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); } +/// Kurikaeshi Moji Shori: new type has it off; the menu item turns it on for the paragraphs the Type +/// tool's selection touches in one undo step, a click while the selected paragraphs differ turns it +/// on for all of them, and a click while all have it turns it off. Reset Panel turns it off. +#[test] +fn kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs() { + let (mut app, id) = editing_text("時々\nすゝ\n"); + app.session.prefs.show_east_asian_options = true; + let flags = |app: &VectorcraftApp| { + let node = app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("text") }; + (text.para_at(0).kurikaeshi_moji_shori, text.para_at(1).kurikaeshi_moji_shori) + }; + assert_eq!(flags(&app), (false, false), "new type has it off"); + select_range(&mut app, 0, 3); + let history = app.session.active().unwrap().history.undo.len(); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (true, false)); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (true, true), "mixed: a click turns it on for all"); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (false, false), "all on: a click turns it off"); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + app.session.set_tool_option("selectAll", &json!(true)); + reset_panel(&mut app); + assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); +} + #[test] fn paragraph_mixed_indent_fields_show_blank() { let (mut app, id) = editing_text("A\nB\n"); diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..ba9e16985d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9451,6 +9451,30 @@ https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html {"name":"run_command","arguments":{"command":"text.setFormat","params":{"bunriKinshi":true}}} ``` +## Kurikaeshi Moji Shori + +`text.setFormat {kurikaeshiMojiShori: bool}` (Paragraph panel menu › Kurikaeshi Moji Shori, shown with the East Asian +options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / `end` +range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, is drawn as the +character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, +searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. +SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. +VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the +repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a +combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph +from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the +plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a +paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph +(`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph +style's attributes), and Reset Panel turns it off. A value that is not true or false is refused, and a call that gives +the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a +save reports a paragraph with it on as left out. The help page: +https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"kurikaeshiMojiShori":true}}} +``` + ## Korean Line Break Anywhere `text.setFormat {koreanLineBreakAnywhere: bool}` (Paragraph panel menu › Korean Line Break Anywhere, shown with the diff --git a/docs/type-parity.md b/docs/type-parity.md index 5b332efd5e..419ccc7717 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -67,6 +67,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: input methods (marked text, candidate window) | done | | | CJK: kinsoku (Hard, Soft, None), the predefined mojikumi sets (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku, YakumonoZenkaku, with VectorCraft's own spacing for each) and Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, custom mojikumi sets and the Mojikumi Settings dialog missing | | CJK: Kinsoku Shori Type (Push In First, Push Out First, Push Out Only) | done | Paragraph panel menu › Kinsoku Shori Type (`text.setFormat {kinsokuType}`), with the East Asian options ([Formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); Push Out Only is the default, and a push-in closes the line's gaps next to CJK characters by at most a tenth of an em each (VectorCraft's own limit). Evidence: `layout::wrapping_tests::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `tests::vertical::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `typecmd::area_tests::kinsoku_shori_type_is_set_per_paragraph_and_saved_only_when_not_push_out_only` | +| CJK: Kurikaeshi Moji Shori | done | Paragraph panel menu › Kurikaeshi Moji Shori (`text.setFormat {kurikaeshiMojiShori}`), with the East Asian options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, and the text keeps the mark; SVG export with live type writes the drawn character. The set of marks and the voicing rules are VectorCraft's own. Off by default, saved natively only when on, carried by paragraph styles. Evidence: `tests::repeat_marks_stand_for_the_character_before_them`, `tests::kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start`, `typecmd::area_tests::kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on`, `threads::tests::a_continued_frame_carries_the_character_a_repeat_mark_stands_for`, `panels::paragraph::tests::kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs`, `text_layout::a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws` | | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` | From 411310a75789182880028044d808e461f5e44da3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:28:29 -0800 Subject: [PATCH 02/26] PDF export: Preserve Numbers converts tagged images from their profile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Output › Convert to Destination (Preserve Numbers), and in PDF/X-1a, which converts the same way, a gray or RGB image that carries an ICC profile had its numbers read as sRGB: converted as sRGB to a CMYK destination, and kept as they were in an RGB one. Preserve Numbers keeps the numbers of untagged content only, so such an image is now converted from its profile to sRGB with the color settings' intent, and then to a CMYK or other RGB destination, the document's own RGB profile included. - An untagged RGB image keeps its numbers in an RGB destination and converts from sRGB to a CMYK one, as before. - A gray image is converted to sRGB grays in an sRGB destination and keeps its profile in the others. - With RGB colors ICC-tagged as sRGB, the image is written as sRGB. - A profile the color engine can't read leaves the image as it is in an RGB destination, and its numbers read as sRGB in a CMYK one, with a warning each. - The table for an RGB destination is built only when the first tagged image needs it. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/pdf/src/export/images.rs | 3 +- crates/pdf/src/images.rs | 32 ++++--- crates/pdf/src/output.rs | 50 +++++++++-- crates/pdf/src/tests/compression.rs | 124 +++++++++++++++++++++++++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 7 files changed, 199 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 77902b4a15..90b3401821 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 04a3a811f3..70cc868c23 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -139,7 +139,8 @@ impl Exporter<'_> { let doc = self.doc; let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); + let then = out.converts_tagged_pixels().then_some(&*out); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index ac1d77f372..2f81d84571 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -12,7 +12,9 @@ //! conversion leaves unchanged (an sRGB profile) keeps its JPEG data. A black-and-white image whose //! converted levels are grey is compressed as greyscale. A colour image the Output settings also //! convert to their destination ([`Pixels`]) goes from its profile to sRGB, then to the -//! destination; a grey one keeps its profile there, as grey pixels are not converted. +//! destination, and so does one converted from its profile to an RGB destination whose untagged +//! images keep their numbers (Preserve Numbers); a grey one keeps its profile there, as grey +//! pixels are not converted. //! //! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is //! when its numbers are kept; the others' ink amounts are resampled, converted when the Output @@ -319,15 +321,20 @@ pub(crate) struct Recoded { pub note: Option<&'static str>, } -/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to -/// Destination, [`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, -/// else the step before the image's [`Pixels`] conversion. -#[derive(Clone, Copy, Debug)] -pub(crate) struct ToSrgb { +/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB +/// ([`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, else the +/// step before the image's [`Pixels`] conversion. +#[derive(Clone, Copy)] +pub(crate) struct ToSrgb<'a> { /// The rendering intent of the conversion. pub intent: Intent, /// 16-bit samples may be written (PDF 1.5 and later). pub sixteen_bit: bool, + /// The colour output whose [`crate::output::ColorOut::tagged_pixels`] then convert a colour + /// image converted from its profile, when other colour images are not converted (`recode`'s + /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve + /// Numbers). Its table is built when the first such image needs it. + pub then: Option<&'a crate::output::ColorOut>, } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -476,8 +483,8 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile /// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces); /// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB -/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as -/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be +/// instead ([`ToSrgb`]), and colour ones then by `convert`, or without it by the conversion +/// `to_srgb` gives ([`ToSrgb::then`]); grey ones that either leaves as they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be /// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. pub(crate) fn recode( bytes: &[u8], @@ -497,7 +504,8 @@ pub(crate) fn recode( let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. - let to_srgb = to_srgb.filter(|_| !(grey && convert.is_some())); + let then = to_srgb.and_then(|t| t.then); + let to_srgb = to_srgb.filter(|_| !(grey && (convert.is_some() || then.is_some()))); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { @@ -533,6 +541,8 @@ pub(crate) fn recode( return Recoded { image: None, warning: rule.instead, note: None }; } let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Converted from its profile: then by `convert`, else by the conversion `to_srgb` gives. + let mut from_profile = false; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -550,8 +560,9 @@ pub(crate) fn recode( if kind == Kind::Mono && !bilevel(&srgb) { (kind, rule) = (Kind::Gray, self::rule(c, Kind::Gray)); } + from_profile = true; // Written as it is only when nothing converts it further. - let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); + let as_is = kept(&rule, dims, size, jpeg) && convert.is_none() && then.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB // profile): its JPEG data, without the profile. if !changed && as_is && jpeg { @@ -570,6 +581,7 @@ pub(crate) fn recode( } }; } + let convert = if from_profile { convert.or_else(|| then.and_then(crate::output::ColorOut::tagged_pixels)) } else { convert }; // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 92381e1628..dce763e9d6 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -14,7 +14,10 @@ //! that carries an ICC profile is converted from it to sRGB with the same intent and written //! without it ([`ColorOut::image_srgb_intent`]); with `destination` and a destination its //! pixels are converted to (CMYK, another RGB space), a colour image is converted from its -//! profile to sRGB and then to the destination. Without conversion it keeps its profile. The +//! profile to sRGB and then to the destination. With `preserveNumbers` (and PDF/X-1a), which +//! keeps the numbers of untagged colours only, such an image is converted from its profile +//! whatever the destination: to sRGB, and then to a CMYK or other RGB destination +//! ([`ColorOut::tagged_pixels`]). Without conversion it keeps its profile. The //! destination is a profile name; empty, the document's profile for its colour mode. //! - Profiles ([`ProfileInclusion`]): with `all`, with `destination`, and with `taggedSource` on a //! document that was assigned profiles, colours are written in ICC-based colour spaces: CMYK @@ -77,6 +80,9 @@ pub(crate) struct ColorOut { pub srgb_note: Option, /// The image transform, built when the first image needs it. pixels: OnceLock>, + /// The transform of images converted from their profile, when it isn't `pixels` + /// ([`Self::tagged_pixels`]). + tagged_pixels: OnceLock>, /// The CMYK image transform, built when the first CMYK image needs it. cmyk_pixels: OnceLock>, intent: Intent, @@ -120,6 +126,7 @@ impl Default for ColorOut { cmyk_profile, srgb_note: None, pixels: OnceLock::new(), + tagged_pixels: OnceLock::new(), cmyk_pixels: OnceLock::new(), intent, catalog: None, @@ -348,13 +355,42 @@ impl ColorOut { /// The intent a gray or RGB image that carries an ICC profile is converted from it to sRGB /// with ([`crate::images::recode`]): the colour settings' intent, with Convert to Destination /// and an sRGB destination, also when the document's RGB space is sRGB, or a destination - /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space). - /// `None` otherwise, Preserve Numbers and an RGB destination that is the document's own RGB - /// profile (which leaves RGB colours and RGB images as they are) included: such an image - /// keeps its profile, or its numbers are converted as sRGB ones. + /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space); + /// and with Preserve Numbers (and PDF/X-1a's own conversion), whatever the destination, as + /// only untagged colours of the destination's model keep their numbers. The pixels are then + /// converted by [`Self::tagged_pixels`]. `None` otherwise, an RGB destination that is the + /// document's own RGB profile with Convert to Destination (which leaves RGB colours and RGB + /// images as they are) included: such an image keeps its profile. pub(crate) fn image_srgb_intent(&self) -> Option { - let d = self.dest.as_ref().filter(|d| d.destination)?; - ((d.model == Model::Rgb && d.srgb) || self.pixels().is_some()).then_some(self.intent) + let d = self.dest.as_ref()?; + let rgb = d.model == Model::Rgb && (d.srgb || !d.destination); + (rgb || self.pixels().is_some()).then_some(self.intent) + } + + /// The destination a colour image converted from its ICC profile to sRGB + /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not + /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose + /// untagged RGB images keep their numbers (unless RGB is tagged as sRGB). + fn tagged_rgb_dest(&self) -> Option<&Dest> { + self.dest.as_ref().filter(|d| !d.destination && d.model == Model::Rgb && !d.srgb && !self.tagged) + } + + /// Are colour images converted from their ICC profile then converted by + /// [`Self::tagged_pixels`]? + pub(crate) fn converts_tagged_pixels(&self) -> bool { + self.tagged_rgb_dest().is_some() + } + + /// How a colour image converted from its ICC profile to sRGB is then converted into that + /// destination's RGB space ([`Self::converts_tagged_pixels`]), built when the first such image + /// needs it; `None` when there is no such destination. + pub(crate) fn tagged_pixels(&self) -> Option<&Pixels> { + self.tagged_pixels + .get_or_init(|| { + let d = self.tagged_rgb_dest()?; + Some(Pixels::Rgb(Box::new(ProofLut::build(|rgb| d.cms.srgb_to_rgb(rgb))))) + }) + .as_ref() } /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index f36cb88e4b..8ad11de270 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -776,7 +776,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); @@ -980,3 +980,125 @@ fn convert_to_destination_converts_tagged_images_from_their_profile() { let as_srgb = converted_samples(&img, to_cmyk); assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile: converted as sRGB"); } + +/// With Preserve Numbers, an RGB image that carries an ICC profile is converted from that profile +/// whatever the destination, while an untagged one keeps its numbers in an RGB destination (and +/// converts from sRGB to a CMYK one, as before): to Generic CMYK, sRGB, Wide Gamut RGB, and Wide +/// Gamut RGB that is also the document's RGB profile, and in PDF/X-1a, which converts the same way. +/// A gray image keeps its profile, except in an sRGB destination, where it is converted to sRGB +/// grays. An RGB profile the CMS can't read leaves the image as it is in an RGB destination, and +/// its numbers converted as sRGB ones to a CMYK destination, with a warning. +#[test] +fn preserve_numbers_converts_tagged_images_from_their_profile() { + use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, GENERIC_CMYK, Intent, SRGB, WIDE_GAMUT_RGB, icc_bytes}; + let intent = Intent::RelativeColorimetric; + let settings_with = + |rgb: &str| std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, rgb: rgb.into(), ..ColorSettings::default() }).unwrap()); + let (active, own) = (settings_with(SRGB), settings_with(WIDE_GAMUT_RGB)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + let p3_profile = cms::IccProfile::from_bytes(None, &p3).unwrap(); + let from_p3 = |rgb: [u8; 3]| p3_profile.to_srgb(&rgb.map(|v| f32::from(v) / 255.0), intent).unwrap().map(|v| (v * 255.0).round() as u8); + let img = colour_blocks(); + let tagged_png = doc(tagged(&img, &p3, ImageFormat::Png), "image/png"); + let untagged_png = doc(encoded(img.clone(), ImageFormat::Png), "image/png"); + let device = |space: &str| vec![Written { space: space.into(), icc: None, bits: 8, filter: "FlateDecode".into(), smask: false }]; + let cmyk = cms::Cms::new(&ColorSettings { intent, cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let cmy = cms::ProofLut::build(|rgb| { + let v = cmyk.srgb_to_cmyk(rgb, intent); + [v[0], v[1], v[2]] + }); + let black = cms::ProofLut::build(|rgb| [cmyk.srgb_to_cmyk(rgb, intent)[3], 0.0, 0.0]); + let wide_lut = cms::ProofLut::build(|rgb| own.srgb_to_rgb(rgb)); + let to_cmyk = |rgb: [u8; 3]| [cmy.apply8(rgb).as_slice(), &black.apply8(rgb)[..1]].concat(); + let to_wide = |rgb: [u8; 3]| wide_lut.apply8(rgb).to_vec(); + let to_srgb = |rgb: [u8; 3]| rgb.to_vec(); + type ToDest<'a> = &'a dyn Fn([u8; 3]) -> Vec; + // Each case: what, the color settings, the export settings, the space images are written in, + // how an sRGB pixel converts to the destination, and whether untagged images keep their numbers. + type Case<'a> = (&'a str, &'a std::sync::Arc, Value, &'a str, ToDest<'a>, bool); + let cases: [Case<'_>; 5] = [ + ("CMYK", &active, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}}), "DeviceCMYK", &to_cmyk, false), + ("sRGB", &active, json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}), "DeviceRGB", &to_srgb, true), + ("Wide Gamut", &active, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ("own RGB", &own, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ( + "PDF/X-1a", + &active, + json!({"standard": "pdfX1a", "compatibility": "1.3", "output": {"destination": GENERIC_CMYK}}), + "DeviceCMYK", + &to_cmyk, + false, + ), + ]; + for (what, color, settings, space, to_dest, keeps) in cases { + let export = |d: &Document| { + let mut s: PdfSettings = serde_json::from_value(settings.clone()).unwrap(); + s.compression.compress_text = false; + let r = cms::with_active((*color).clone(), || export_with_report(d, &PdfOptions { settings: s, ..Default::default() })).unwrap(); + assert!(r.warnings.is_empty(), "{what}: {:?}", r.warnings); + if what == "PDF/X-1a" { + crate::pdfx::verify(&r.bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{what}: {e}")); + } + (image_spaces(&r.bytes), image_samples(&r.bytes)) + }; + let (spaces, samples) = export(&tagged_png); + assert_eq!(spaces, device(space), "{what}: tagged"); + let want = converted_samples(&img, |rgb| to_dest(from_p3(rgb))); + let as_numbers = converted_samples(&img, to_dest); + assert!( + samples.len() == 1 && samples_close(&samples[0], &want, false, 1), + "{what}: converted from the profile, {}", + max_diff(&samples[0], &want) + ); + assert!(!samples_close(&samples[0], &as_numbers, false, 8), "{what}: not converted as its numbers"); + let (spaces, samples) = export(&untagged_png); + assert_eq!(spaces, device(space), "{what}: untagged"); + let untagged = if keeps { img.to_rgb8().into_raw() } else { as_numbers }; + assert!(samples.len() == 1 && samples_close(&samples[0], &untagged, false, 1), "{what}: untagged, {}", max_diff(&samples[0], &untagged)); + } + // With RGB colours ICC-tagged as sRGB, the tagged image is written as its sRGB samples, in an + // ICC-based colour space with the sRGB profile. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}}); + let (spaces, pdf) = cms::with_active(active.clone(), || export_images(&tagged_png, settings)); + let is_srgb = |icc: &[u8]| { + let p = cms::IccProfile::from_bytes(None, icc).unwrap(); + [[0.2, 0.5, 0.9], [0.9, 0.1, 0.4]].iter().all(|v| p.to_srgb(v, intent).unwrap().iter().zip(v).all(|(a, b)| (a - b).abs() < 0.01)) + }; + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref().is_some_and(is_srgb), "tagged as sRGB: {spaces:?}"); + let samples = image_samples(&pdf); + let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); + assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); + // A gray image keeps its gray profile, in a CMYK and in an RGB destination. + let gray = gray_profile(&[0x01CD]); + let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); + for destination in [GENERIC_CMYK, WIDE_GAMUT_RGB] { + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": destination}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!( + spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), + "gray, {destination}: {spaces:?}" + ); + } + // In an sRGB destination it is converted to sRGB grays and written without it. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(), "gray, sRGB: {spaces:?}"); + // A profile the CMS can't read: the image keeps it and its numbers in an RGB destination, and + // its numbers are converted as sRGB ones to a CMYK destination, with a warning each. + let unread = icc_profile(b"RGB ", 600); + let unread_doc = doc(tagged(&img, &unread, ImageFormat::Png), "image/png"); + let unread_export = |destination: &str| { + let mut s: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "preserveNumbers", "destination": destination}})).unwrap(); + s.compression.compress_text = false; + cms::with_active(active.clone(), || export_with_report(&unread_doc, &PdfOptions { settings: s, ..Default::default() })).unwrap() + }; + let r = unread_export(WIDE_GAMUT_RGB); + assert!(r.warnings.iter().any(|w| w.contains("the image keeps it")), "{:?}", r.warnings); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(unread.as_slice()), "unread profile: {spaces:?}"); + let r = unread_export(GENERIC_CMYK); + assert!(r.warnings.iter().any(|w| w.contains("converted to the destination as sRGB")), "{:?}", r.warnings); + let as_srgb = converted_samples(&img, to_cmyk); + assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile, CMYK: converted as sRGB"); +} diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..6cdd88a9e1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5911,7 +5911,13 @@ and then to the destination, instead of having its numbers read as sRGB (a profi them read as sRGB, with a warning); a gray image keeps its profile, as gray is not converted. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there. -`preserveNumbers` still reads an image's numbers as sRGB. The destination is any profile `edit.colorSettings` lists (default: the document's +`preserveNumbers` (and PDF/X-1a, which converts the same way) keeps the numbers of untagged content only: an RGB image +that carries an ICC profile is converted from that profile to sRGB with the same intent, and then to a CMYK or other +RGB destination, the document's own RGB profile included (written as sRGB when colours are ICC-tagged), while an untagged RGB image keeps its numbers in an RGB +destination and converts from sRGB to a CMYK one. A gray image that carries one is converted to sRGB grays in an +sRGB destination and keeps its profile in the others, and a profile the color engine can't +read leaves the image as it is in an RGB destination, with a warning, and its numbers read as sRGB in a CMYK one. +The destination is any profile `edit.colorSettings` lists (default: the document's for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..35bce4927e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1935,6 +1935,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - PDF export with Output › Convert to Destination and an sRGB destination converts a gray or RGB image that carries an ICC profile from that profile to sRGB, with the color settings' rendering intent, and writes it without the profile, as the conversion applies to every color ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): 8-bit and 16-bit TIFFs (16 bits a sample from PDF 1.5 on when not resampled or recompressed), PNGs, JPEGs (kept as JPEG) and resampled images. A JPEG in an sRGB profile keeps its JPEG data, a black-and-white image whose converted levels are gray is written as grayscale, and without conversion every image keeps its profile. An image whose profile the color engine can't read, or whose pixels can't be decoded, is not converted: it keeps its profile, with a warning (`crates/pdf/src/tests/compression.rs`). - PDF export with Output › Convert to Destination and a CMYK destination, or an RGB destination other than sRGB that images are converted to, converts an RGB image that carries an ICC profile from that profile to sRGB and then to the destination, with the color settings' rendering intent, instead of reading its numbers as sRGB ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). An untagged image converts from sRGB as before, a gray image keeps its profile, and a profile the color engine can't read leaves the numbers read as sRGB, with a warning. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there (`convert_to_destination_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). + - PDF export with Output › Convert to Destination (Preserve Numbers), and PDF/X-1a, keeps the numbers of untagged content only, as the option describes ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): an RGB image that carries an ICC profile is converted from that profile to sRGB with the color settings' rendering intent, and then to a CMYK or other RGB destination, the document's own RGB profile included, while an untagged RGB image keeps its numbers in an RGB destination. A gray image is converted to sRGB grays in an sRGB destination and keeps its profile in the others, and a profile the color engine can't read leaves the image as it is in an RGB destination, with a warning (`preserve_numbers_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`). - An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk () or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). From a230ea470d5ea96b358238d8a5f06fee532d49c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:31:15 -0800 Subject: [PATCH 03/26] 3D (Classic): the Black Overprint shading color shades with overprinting black over the fill Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) take shadingColor blackOverprint. Each face keeps its paint unchanged, and a face that darkens gets black over it, as strong as the darkening of the shading color Black: a fill multiplied and overprinting, and a seam stroke overprinting with Darken. The black is on the black plate in Separations Preview and is written to PDF as overprinting fills. The Plastic highlight is not drawn with it. Preserve Spot Colors draws its black with the same helper, so its seam stroke no longer multiplies the black a second time along face edges. The dialogs list the choice, with catalog rows next to Shading Color. Params text, docs/mcp.md, docs/three-d.md and docs/effects-parity.md describe it. --- crates/effects/src/catalog.rs | 6 +- crates/effects/src/revolve/classic.rs | 35 +++++++++++ crates/effects/src/solids/classic.rs | 69 ++++++++++++++------ crates/effects/src/solids/tests.rs | 91 ++++++++++++++++++++++++++- crates/engine/src/tests/overprint.rs | 58 +++++++++++++++++ crates/ui-egui/src/dialogs/effect.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/effects-parity.md | 2 +- docs/mcp.md | 16 +++-- docs/three-d.md | 6 +- 37 files changed, 282 insertions(+), 31 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 8e0d63e9d0..7a93ab079e 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,21 +210,21 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( CLASSIC_ROTATE, "Rotate (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 8dc013e9dc..4aefb13eef 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -164,6 +164,41 @@ mod tests { } } + /// With Black Overprint every face keeps the blue, and the faces that darken get black over it, + /// overprinting, as strong as the darkening of the shading color Black. + #[test] + fn black_overprint_keeps_the_blue_under_overprinting_black() { + let darkened = revolved(json!({"surface": "diffuse"})); + let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"})); + let (darkened, drawn) = (faces(&darkened), faces(&art)); + assert_eq!(darkened.len(), drawn.len()); + let mut shaded = 0; + for (face, black) in drawn.iter().zip(&darkened) { + let fills: Vec<&vectorcraft_doc::FillLayer> = face + .appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f), + AppearanceItem::Stroke(_) => None, + }) + .collect(); + assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false)); + let k = match fills.get(1) { + Some(shadow) => { + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true)); + shaded += 1; + k + } + None => 0.0, + }; + let b = fill(black).unwrap().to_rgb()[2]; + assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}"); + } + assert!(shaded > 0, "faces turned from the light get black"); + } + #[test] fn angle_offset_edge_and_cap_shape_the_surface() { let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..e2c3347efa 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; -/// The Shading Color choices: black, a custom color, or none. -pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"]; +/// The Shading Color choices: black, a custom color, none, or black overprinting the paint. +pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"]; /// The surface settings of Extrude & Bevel (Classic)'s parameters. pub fn classic_shading(p: &Value) -> ClassicShading { @@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { } } -/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only -/// the highlight lightens them). +/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces +/// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { match text(p, "shadingColor", "black") { "none" => None, @@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool { /// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower /// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where -/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`, -/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam +/// tone `tone` is below full light and the faces darken (`shade`), black over it as +/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam /// stroke each layer draws around the face. fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option, seam: f64) -> Vec { let Paint::Solid { color, swatch, tint } = paint else { return vec![] }; let keep = (1.0 - spec).clamp(0.0, 1.0) as f32; let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep }; let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]; - if shade.is_some() && tone < 1.0 { - let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); - let mut layer = FillLayer::new(black.clone()); - layer.blend = BlendMode::Multiply; - layer.overprint = true; - let mut edge = crate::lighting::seam_stroke(black, seam); - edge.blend = BlendMode::Multiply; - edge.overprint = true; - items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]); + if shade.is_some() { + items.extend(overprinting_black(tone, seam)); } items } +/// The black that shades a face at tone `tone` on the black plate, when the tone is below full +/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam` +/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a +/// neighbor's, the face is not darkened twice. +fn overprinting_black(tone: f64, seam: f64) -> Vec { + if tone >= 1.0 { + return vec![]; + } + let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); + let mut layer = FillLayer::new(black.clone()); + layer.blend = BlendMode::Multiply; + layer.overprint = true; + let mut edge = crate::lighting::seam_stroke(black, seam); + edge.blend = BlendMode::Darken; + edge.overprint = true; + vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)] +} + +/// Whether the shading color of parameters `p` is Black Overprint. +fn black_overprint(p: &Value) -> bool { + text(p, "shadingColor", "black") == "blackOverprint" +} + +/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full +/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they +/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of +/// the seam stroke each layer draws around the face. +fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + items.extend(overprinting_black(tone, seam)); + items +} + /// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on /// Wireframe, else the seam between faces. pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { @@ -229,14 +256,16 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by -/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] -/// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage. +/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot +/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops +/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's +/// coverage. pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); + let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; let paint = &paint; @@ -251,6 +280,10 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let (tone, spec) = shading.tone(face.normal, &lights); // A narrow stroke of the face's own paint closes the hairline seams between faces. let seam = super::seam_width(&face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); + } let items = match paint.color() { // Unshaded (No Shading, no shading color, or a face in full light) with no // highlight: the paint itself, its color space and swatch kept. diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index de1ec75de3..17e746d1aa 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1902,6 +1902,89 @@ fn classic_shading_color_blend_steps_and_lights() { assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6); } +/// The fills, then the strokes, of face `face`. +fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) { + let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect(); + (fills, strokes) +} + +/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in +/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice); +/// `None` when the face has none. +fn overprinted_black(face: &Node) -> Option { + let (fills, strokes) = layers_of(face); + assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke"); + let shadow = fills.get(1)?; + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0)); + assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true)); + assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out"); + Some(k) +} + +/// Black Overprint keeps the paint on every face and draws the shading over it as black, +/// overprinting, as strong as the darkening of the shading color Black; the +/// highlight is not drawn, and No Shading adds no black. +#[test] +fn classic_black_overprint_keeps_the_paint_under_overprinting_black() { + let diffuse = json!({"surface": "diffuse", "ambient": 20}); + let mut over = diffuse.clone(); + over["shadingColor"] = json!("blackOverprint"); + let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect(); + let faces = classic_faces(over); + assert_eq!(faces.len(), darkened.len()); + let mut shaded = 0; + for (face, rgb) in faces.iter().zip(&darkened) { + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept"); + let k = overprinted_black(face).unwrap_or(0.0); + assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}"); + shaded += usize::from(k > 0.0); + } + assert!(shaded > 0, "faces turned from the light get black"); + // Plastic: no white layer for the highlight. + let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60}); + for face in classic_faces(shiny) { + let (fills, _) = layers_of(&face); + assert_eq!(fills[0].paint, Paint::solid(RED)); + assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}"); + } + // No Shading: the paint alone. + for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) { + assert_eq!(overprinted_black(&face), None); + assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED)); + } +} + +/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate +/// (Classic) draws its plane the same way. +#[test] +fn classic_black_overprint_keeps_gradients_and_shades_rotate() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)], + )))); + let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = gradient.clone(); + } + let art = solid_art(&n).unwrap(); + let mut shaded = 0; + for face in faces(&art) { + assert_eq!(layers_of(face).0[0].paint, gradient); + shaded += usize::from(overprinted_black(face).is_some()); + } + assert!(shaded > 0); + // Rotate (Classic), turned from the light: red with black over it; facing it: red alone. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + let face = &turned[0].children().unwrap()[0]; + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED)); + assert!(overprinted_black(face).is_some_and(|k| k > 0.05)); + let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None); +} + #[test] fn classic_bevel_height_extent_and_cap_shape_the_solid() { let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap(); @@ -2077,9 +2160,12 @@ fn classic_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), + (json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"), + (json!({"shadingColor": true}), "`shadingColor` must be one of"), (json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"), @@ -2156,11 +2242,12 @@ fn classic_rotate_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), (json!({"surface": 2}), "`surface` must be one of"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 15fbb721e2..3f18ddf644 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -276,3 +276,61 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { s.execute("edit.colors.overprintBlack", &json!({"includeCmyBlacks": true, "includeSpotBlacks": true})).unwrap(); assert!(fill(&s, g) && fill(&s, spot)); } + +/// The plate `plate` of `doc`, drawn as Separations Preview draws one plate, as one gray value per +/// pixel (0 full ink, 255 none). +fn plate(doc: &Document, plate: &str) -> Vec { + let mut r = Renderer::new(); + r.threads = 0; + let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; + let image = r.render(doc, 100, 100, Affine::IDENTITY, &opts); + (0..100 * 100).map(|i| image.pixel(i % 100, i / 100)[0]).collect() +} + +/// 3D (Classic) with the shading color Black Overprint puts the shading on the black plate, shows +/// it as the cyan darkened, and writes it to PDF as overprinting fills. +#[test] +fn classic_3d_black_overprint_shades_on_the_black_plate() { + let doc = |params: Value| { + let mut s = session(); + rect(&mut s, [30.0, 30.0, 40.0, 40.0], cyan_ink(), None, 0.0); + s.execute("effect.apply", &json!({"effect": "threeD.classicExtrude", "item": null, "params": params})).unwrap(); + s + }; + let over = doc(json!({"surface": "diffuse", "depth": 20, "shadingColor": "blackOverprint"})); + let flat = doc(json!({"surface": "none", "depth": 20, "shadingColor": "blackOverprint"})); + let black = doc(json!({"surface": "diffuse", "depth": 20})); + let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); + let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); + assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); + assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. + let image = |d: &Document| { + let mut r = Renderer::new(); + r.threads = 0; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let (shaded, unshaded) = (image(over_doc), image(flat_doc)); + let mut darker = 0; + for (x, y) in (0..100u32).flat_map(|y| (0..100u32).map(move |x| (x, y))) { + let (s, u) = (shaded.pixel(x, y), unshaded.pixel(x, y)); + // Inside the solid (no white mixed in at an antialiased edge) where the shading darkens it. + if u[0] < 30 && (s[1] as i32) + 20 < u[1] as i32 { + darker += 1; + assert!(s[2] as i32 > s[0] as i32 + 20, "a shaded face keeps its cyan at ({x}, {y}): {s:?}"); + } + } + assert!(darker > 100, "the faces turned from the light are darker"); + + let pdf_overprints = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"compression": {"compressText": false}, "preserveEditing": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + String::from_utf8_lossy(&bytes).matches("/OP true/op true/OPM 1").count() + }; + let (mut over, mut black) = (over, black); + assert!(pdf_overprints(&mut over) > 0, "the black is written overprinting"); + assert_eq!(pdf_overprints(&mut black), 0); +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index cd089e04bd..82309cf1a0 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -542,7 +542,7 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option vec![(tl!("No Shading"), "none"), (tl!("Diffuse"), "diffuse")], (vectorcraft_effects::CLASSIC_EXTRUDE | vectorcraft_effects::CLASSIC_REVOLVE | vectorcraft_effects::CLASSIC_ROTATE, "shadingColor") => { - vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none")] + vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none"), (tl!("Black Overprint"), "blackOverprint")] } (vectorcraft_effects::EXTRUDE | vectorcraft_effects::CLASSIC_EXTRUDE, "bevel") => vec![ (tl!("None"), "none"), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..79c9b2230c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1162,6 +1162,7 @@ font-technology Variable Променливи Highlight Size Размер на отблясъка Blend Steps Стъпки на преливане Shading Color Цвят на засенчването + Black Overprint Черно с напечатване Draw Hidden Faces Изчертаване на скритите страни Eyedropper Пипета Eyedropper Applies: Пипетата прилага: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..c328ae9a05 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -520,6 +520,7 @@ Highlight Size Veličina odsjaja Blend Steps Koraci prelaza Shading Color Boja sjenčenja + Black Overprint Crni pretisak Draw Hidden Faces Crtaj skrivene strane Revolve… Rotaciono tijelo… Inflate… Napuhni… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..221fde4557 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1642,6 +1642,7 @@ antiAlias Sharp Nítid Highlight Size Mida de la brillantor Blend Steps Passos de fusió Shading Color Color de l’ombra + Black Overprint Negre en sobreimpressió Draw Hidden Faces Dibuixa les cares ocultes Eyedropper Comptagotes Eyedropper Applies: El comptagotes aplica: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..49255c036a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -533,6 +533,7 @@ Highlight Size Velikost odlesku Blend Steps Kroky prolnutí Shading Color Barva stínování + Black Overprint Přetisk černou Draw Hidden Faces Kreslit skryté stěny Revolve… Rotační těleso… Inflate… Nafouknutí… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..c84c49dfa0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1111,6 +1111,7 @@ Highlight Size Højlysstørrelse Blend Steps Overgangstrin Shading Color Skyggefarve + Black Overprint Sort overprint Draw Hidden Faces Tegn skjulte flader Revolve… Omdrej… Inflate… Pust op… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..e420257131 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variabel Highlight Size Glanzpunktgröße Blend Steps Angleichungsstufen Shading Color Schattierungsfarbe + Black Overprint Überdruckendes Schwarz Draw Hidden Faces Verdeckte Flächen zeichnen Eyedropper Pipette Sample Color from Screen Farbe vom Bildschirm aufnehmen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..f3fa7aea6b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1140,6 +1140,7 @@ font-technology Variable Μεταβλητές Highlight Size Μέγεθος ανταύγειας Blend Steps Βήματα ανάμειξης Shading Color Χρώμα σκίασης + Black Overprint Μαύρο με υπερεκτύπωση Draw Hidden Faces Σχεδίαση κρυφών εδρών Eyedropper Σταγονόμετρο (Eyedropper Tool) Eyedropper Applies: Το σταγονόμετρο εφαρμόζει: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..f0c90a60a0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1196,6 +1196,7 @@ font-technology Variable Variables Highlight Size Tamaño del brillo Blend Steps Pasos de fusión Shading Color Color de sombreado + Black Overprint Negro sobreimpreso Draw Hidden Faces Dibujar caras ocultas Eyedropper Cuentagotas Sample Color from Screen Tomar color de la pantalla diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..c42f5a9c3c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -530,6 +530,7 @@ Highlight Size Kiillon koko Blend Steps Sulautusvaiheet Shading Color Varjostusväri + Black Overprint Päällepainettu musta Draw Hidden Faces Piirrä piilotetut pinnat Revolve… Pyöräytä… Inflate… Täytä ilmalla… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..792514e69f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1191,6 +1191,7 @@ font-technology Variable Variables Highlight Size Taille de la brillance Blend Steps Étapes de transition Shading Color Couleur d’ombrage + Black Overprint Noir en surimpression Draw Hidden Faces Dessiner les faces cachées Eyedropper Pipette Sample Color from Screen Prélever une couleur à l’écran diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..b1d6b7e124 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3462,6 +3462,7 @@ Setup… સેટઅપ… Shading શેડિંગ Shading Color શેડિંગ રંગ + Black Overprint કાળો ઓવરપ્રિન્ટ Shadows and Glows પડછાયા અને ગ્લો Shape શેપ Shape Builder શેપ બિલ્ડર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..79781c16dd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1840,6 +1840,7 @@ antiAlias Sharp शार्प Highlight Size हाइलाइट आकार Blend Steps ब्लेंड चरण Shading Color शेडिंग रंग + Black Overprint काला ओवरप्रिंट Draw Hidden Faces छिपे हुए फलक बनाएँ Eyedropper आईड्रॉपर Eyedropper Applies: आईड्रॉपपर लागू होता है: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..e126652d26 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1495,6 +1495,7 @@ font-technology Variable Változó Highlight Size Csillanás mérete Blend Steps Átmenetlépések Shading Color Árnyékolás színe + Black Overprint Felülnyomó fekete Draw Hidden Faces Rejtett lapok rajzolása Eyedropper Pipetta Sample Color from Screen Szín mintavétele a képernyőről diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..88a5d92366 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -487,6 +487,7 @@ Highlight Size Ukuran kilau Blend Steps Langkah campuran Shading Color Warna pengarsiran + Black Overprint Hitam overprint Draw Hidden Faces Gambar sisi tersembunyi Revolve… Revolusi… Inflate… Gelembungkan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..186a7181ee 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1203,6 +1203,7 @@ font-technology Variable Variabili Highlight Size Dimensione lucentezza Blend Steps Passaggi di fusione Shading Color Colore ombreggiatura + Black Overprint Nero in sovrastampa Draw Hidden Faces Disegna facce nascoste Eyedropper Contagocce Sample Color from Screen Campiona colore dallo schermo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..73c3670166 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -577,6 +577,7 @@ digits Malayalam マラヤーラム数字 Highlight Size ハイライトのサイズ Blend Steps ブレンドの階調 Shading Color 陰影のカラー + Black Overprint ブラックオーバープリント Draw Hidden Faces 隠れた面を描画 Revolve… 回転体… Inflate… 膨張… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..6e904cdb61 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2544,6 +2544,7 @@ Highlight Size ელვარების ზომა Blend Steps შერევის საფეხურები Shading Color დაჩრდილვის ფერი + Black Overprint ზედდაბეჭდილი შავი Draw Hidden Faces დამალული წახნაგების დახატვა Revolve… ბრუნვა… Inflate… გაბერვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..b8116ec6d8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -570,6 +570,7 @@ digits Malayalam 말라얄람어 Highlight Size 하이라이트 크기 Blend Steps 혼합 단계 Shading Color 셰이딩 색상 + Black Overprint 검정 겹쳐찍기 Draw Hidden Faces 숨겨진 면 그리기 Revolve… 회전체… Inflate… 부풀리기… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..18484b6c1b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1007,6 +1007,7 @@ Highlight Size Glansgrootte Blend Steps Overvloeistappen Shading Color Arceringskleur + Black Overprint Zwart overprinten Draw Hidden Faces Verborgen vlakken tekenen Revolve… Draaien… Inflate… Opblazen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..10d07baad9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -492,6 +492,7 @@ Highlight Size Rozmiar połysku Blend Steps Kroki przejścia Shading Color Kolor cieniowania + Black Overprint Czarny nadruk Draw Hidden Faces Rysuj ukryte ściany Revolve… Obrót… Inflate… Nadmuchanie… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..a8f5051c4e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1085,6 +1085,7 @@ antiAlias Sharp Nítido Highlight Size Tamanho do Realce Blend Steps Etapas de Mesclagem Shading Color Cor do Sombreamento + Black Overprint Preto em Sobreimpressão Draw Hidden Faces Desenhar Faces Ocultas Eyedropper Conta-gotas Eyedropper Applies: O Conta-gotas Aplica: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..5a83489ac0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1194,6 +1194,7 @@ font-technology Variable Вариативные Highlight Size Размер блика Blend Steps Шаги перехода Shading Color Цвет затенения + Black Overprint Чёрный с наложением Draw Hidden Faces Рисовать скрытые грани Eyedropper Пипетка Sample Color from Screen Взять цвет с экрана diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..c7c9cc79ca 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variabla Highlight Size Högdagerstorlek Blend Steps Övergångssteg Shading Color Skuggningsfärg + Black Overprint Svart övertryck Draw Hidden Faces Rita dolda ytor Eyedropper Pipett Eyedropper Applies: Pipetten tillämpar: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..7eac71007e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1167,6 +1167,7 @@ font-technology Variable Değişken Highlight Size Parlama Boyutu Blend Steps Karışım Adımları Shading Color Gölgeleme Rengi + Black Overprint Siyah Üst Baskı Draw Hidden Faces Gizli Yüzleri Çiz Eyedropper Damlalık Sample Color from Screen Ekrandan Örnek Renk diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..ba601bde45 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1197,6 +1197,7 @@ font-technology Variable Варіативні Highlight Size Розмір відблиску Blend Steps Кроки переходу Shading Color Колір затінення + Black Overprint Чорний із накладенням Draw Hidden Faces Малювати приховані грані Eyedropper Піпетка Sample Color from Screen Взяти колір з екрана diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..3042ae2089 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1380,6 +1380,7 @@ font-technology Variable Biến thiên Highlight Size Kích thước điểm sáng Blend Steps Số bước hòa trộn Shading Color Màu tô bóng + Black Overprint Đen in chồng Draw Hidden Faces Vẽ các mặt ẩn Eyedropper Ống hút màu Sample Color from Screen Lấy mẫu màu từ màn hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6494b6b557 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1134,6 +1134,7 @@ antiAlias Sharp 锐利 Highlight Size 高光大小 Blend Steps 混合步骤 Shading Color 底纹颜色 + Black Overprint 黑色叠印 Draw Hidden Faces 绘制隐藏表面 Eyedropper 吸管 Sample Color from Screen 从屏幕取样颜色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..b4f286d3bf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1167,6 +1167,7 @@ font-technology Variable 可變 Highlight Size 亮部大小 Blend Steps 漸變階數 Shading Color 網底顏色 + Black Overprint 黑色疊印 Draw Hidden Faces 繪製隱藏表面 Eyedropper 滴管 Sample Color from Screen 從螢幕取樣顏色 diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 290148b89d..e84973de83 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,7 +181,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); Map Art: none | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..670b693021 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4359,16 +4359,24 @@ is tall), `bevelInside` (false adds the bevel around the shape, true carves it i `softness` are not used). `ambient` (0..100%, default 50) lights every face. - `highlightIntensity` (0..100%, default 60) and `highlightSize` (0..100%, default 90; 100 is broad) shape the Plastic highlight. `blendSteps` (whole number, 1..256, default 25) is how many levels the shading is rounded to. -- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color) or `none` (the - paint is kept and only the highlight lightens it). `drawHiddenFaces` also draws the faces turned away from the - viewer, behind the others. +- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color), `none` (the + paint is kept and only the highlight lightens it) or `blackOverprint`. With `blackOverprint` every face keeps the + paint unchanged, and each face that darkens gets overprinting black over it, as strong as `black` would darken it. + The paint's own inks print as they are and the shading prints on the black plate. On screen the black is multiplied + over the paint, Separations Preview shows it on the Black plate, and `document.exportPdf` writes it as overprinting + fills + ([Shading Color options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)). + The highlight is not drawn with `blackOverprint`; that rule is VectorCraft's own. On a pattern face the black covers + the whole face, transparent pattern cells included, as the shading of the other shading colors does. + `drawHiddenFaces` also draws the faces turned away from the viewer, behind the others. - `preserveSpotColors` (default false) is the Lighting tab's Preserve Spot Colors checkbox. When it is on, a fill or stroke linked to a spot or global swatch stays linked on every face, so a spot color prints on its own plate in separations and PDF. The highlight lowers the swatch's tint, and a face that darkens gets black at the shade's strength over the swatch, multiplied and overprinting. These rules for drawing the shading are VectorCraft's own. The option does nothing while `shadingColor` is `custom`, since a custom shading color cannot keep a spot color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)). - Unlinked colors, gradients, patterns and the Wireframe surface draw as they do with it off. + Unlinked colors, gradients, patterns and the Wireframe surface draw as they do with it off. With `blackOverprint` + every face keeps its paint, swatch link included, whether the option is on or off. The defaults are VectorCraft's own. An unknown parameter, a number out of range, a flag that is not true or false, or an unknown surface or shading color is refused with an error and the document is not changed. diff --git a/docs/three-d.md b/docs/three-d.md index 2861bee0b7..461bd2352f 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -553,8 +553,10 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. face that darkens gets black over it, multiplied and overprinting, so a spot color stays on its own plate. The checkbox is unavailable while Shading Color is Custom ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); how - the faces are shaded with it is VectorCraft's own. The track cube, map art, Turntable and 3D export are separate, - unbuilt items. + the faces are shaded with it is VectorCraft's own. The Black Overprint shading color keeps each face's paint and + draws the shading over it as overprinting black, without the highlight. The shading is on the black plate in + Separations Preview and PDF output. The track cube, map art, Turntable and 3D export are + separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). From c08b4d932f341fb7b2dd1e6cd127e5db693c9acf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:52:00 -0800 Subject: [PATCH 04/26] MCP docs: Kurikaeshi Moji Shori says null leaves the setting as it is --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 7a8396740c..b0bdf2972e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9466,8 +9466,8 @@ from one frame into the next; ゝ and ヽ draw it without its voicing marks, and plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph -style's attributes), and Reset Panel turns it off. A value that is not true or false is refused, and a call that gives -the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a +style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the +setting as it is, and a call that gives the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a save reports a paragraph with it on as left out. The help page: https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html From be2f993c4b27b9010529a25622f9f384f70acde4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:56:03 -0800 Subject: [PATCH 05/26] PDF export: Preserve Numbers keeps a gray image's profile when RGB is tagged as sRGB With Preserve Numbers, a non-sRGB RGB destination and RGB colors ICC-tagged as sRGB (the `all` profiles setting, PDF/A-2b, PDF/X-3 and PDF/X-4), a gray image that carries an ICC profile was converted to sRGB grays and lost its profile. It now keeps its profile there, as in the other destinations other than sRGB. --- crates/pdf/src/export/images.rs | 3 ++- crates/pdf/src/images.rs | 12 ++++++++---- crates/pdf/src/output.rs | 7 +++++++ crates/pdf/src/tests/compression.rs | 18 ++++++++++-------- 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 70cc868c23..a91e6f8a0f 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -140,7 +140,8 @@ impl Exporter<'_> { let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); let then = out.converts_tagged_pixels().then_some(&*out); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then }); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then, grey }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 2f81d84571..c578c23176 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -335,6 +335,9 @@ pub(crate) struct ToSrgb<'a> { /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve /// Numbers). Its table is built when the first such image needs it. pub then: Option<&'a crate::output::ColorOut>, + /// Gray images are converted too: with an sRGB destination + /// ([`crate::output::ColorOut::converts_grey_images`]). In the others they keep their profile. + pub grey: bool, } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -484,8 +487,9 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces); /// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB /// instead ([`ToSrgb`]), and colour ones then by `convert`, or without it by the conversion -/// `to_srgb` gives ([`ToSrgb::then`]); grey ones that either leaves as they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be -/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. +/// `to_srgb` gives ([`ToSrgb::then`]); grey ones keep their profile unless the destination is +/// sRGB ([`ToSrgb::grey`]). `interpolate` lets viewers smooth it. An image that can't be decoded +/// is kept as it is, with a warning when its pixels were to be converted to sRGB. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -503,9 +507,9 @@ pub(crate) fn recode( use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. - // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. + // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); - let to_srgb = to_srgb.filter(|_| !(grey && (convert.is_some() || then.is_some()))); + let to_srgb = to_srgb.filter(|t| !grey || t.grey); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index dce763e9d6..d1365dc8d9 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -367,6 +367,13 @@ impl ColorOut { (rgb || self.pixels().is_some()).then_some(self.intent) } + /// Are gray images that carry an ICC profile converted from it to sRGB grays too + /// ([`Self::image_srgb_intent`])? Only with an sRGB destination; in the others, RGB tagged as + /// sRGB included, grey pixels are not converted and keep their profile. + pub(crate) fn converts_grey_images(&self) -> bool { + self.dest.as_ref().is_some_and(|d| d.model == Model::Rgb && d.srgb) + } + /// The destination a colour image converted from its ICC profile to sRGB /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 8ad11de270..871ab42bcb 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -776,7 +776,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None, grey: true }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); @@ -1069,16 +1069,18 @@ fn preserve_numbers_converts_tagged_images_from_their_profile() { let samples = image_samples(&pdf); let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); - // A gray image keeps its gray profile, in a CMYK and in an RGB destination. + // A gray image keeps its gray profile, in a CMYK and in an RGB destination, and in an RGB one + // with RGB colours ICC-tagged as sRGB (`all` profiles, PDF/A-2b). let gray = gray_profile(&[0x01CD]); let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); - for destination in [GENERIC_CMYK, WIDE_GAMUT_RGB] { - let settings = json!({"output": {"conversion": "preserveNumbers", "destination": destination}}); + for (what, settings) in [ + (GENERIC_CMYK, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}})), + (WIDE_GAMUT_RGB, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ("all profiles", json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}})), + ("PDF/A-2b", json!({"standard": "pdfA2b", "output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ] { let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); - assert!( - spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), - "gray, {destination}: {spaces:?}" - ); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), "gray, {what}: {spaces:?}"); } // In an sRGB destination it is converted to sRGB grays and written without it. let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); From b6463e53cc6c2a026a172866d6d7979048f43924 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:13:16 -0800 Subject: [PATCH 06/26] Paragraph: threaded Kurikaeshi Moji Shori leads come from one pass over the frames A thread of frames that hold only repeat marks or soft returns made each frame look back through every frame before it, so opening or flowing such a story took quadratic time, with the setting off as well. The leads are now carried forward in one pass. --- crates/engine/src/cmd/threads.rs | 39 +++++++++++++++----------- crates/engine/src/cmd/threads/tests.rs | 18 ++++++++++++ 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 7ccf26d3de..f4f807cb15 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -404,23 +404,22 @@ pub(crate) fn mark_continued(doc: &mut Document) { /// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and /// whether each one's first paragraph `continues` from the frame before: the last character of -/// that paragraph in the frames before that a repeat mark could stand for, or None. +/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over +/// the frames: each frame's lead is carried forward to the next. fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { - (0..texts.len()) - .map(|k| { - let mut j = k; - while continues.get(j) == Some(&true) && j > 0 { - j -= 1; - let text = texts.get(j)?; - let tail = text.rfind('\n').map_or(Some(text.as_str()), |at| text.get(at + 1..))?; - if let Some(c) = vectorcraft_text::repeat_base(tail) { - return Some(c); - } - if tail.len() != text.len() { - return None; - } - } - None + // The lead the next frame takes when its first paragraph continues from this one. + let mut carry = None; + texts + .iter() + .enumerate() + .map(|(k, text)| { + #[cfg(test)] + LEAD_SCANS.with(|c| c.set(c.get() + 1)); + let lead = carry.filter(|_| continues.get(k) == Some(&true)); + let tail = text.rsplit('\n').next().unwrap_or(text); + // A paragraph break in this frame ends the paragraph the lead came from. + carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len())); + lead }) .collect() } @@ -432,6 +431,8 @@ thread_local! { static THREAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`story_in`] went through a thread's frames on this thread. static STORY_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many frame texts [`first_para_leads`] went through on this thread. + static LEAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's @@ -447,6 +448,12 @@ pub(crate) fn story_builds() -> usize { STORY_BUILDS.with(std::cell::Cell::get) } +/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread. +#[cfg(test)] +pub(crate) fn lead_scans() -> usize { + LEAD_SCANS.with(std::cell::Cell::get) +} + /// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a /// path; empty when `id` is in no thread or the thread has fewer than two such frames. pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index ba2cbaa1d4..82ac2f9f76 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2262,3 +2262,21 @@ fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { assert!(tb.first_para_continues); assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); } + +/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one +/// pass over the frames, each frame's text gone through once, not once for every frame after it. +#[test] +fn continued_frame_leads_go_through_each_frame_once() { + let n = 2000; + let mut texts = vec!["時".to_string()]; + texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1)); + let continues: Vec = (0..n).map(|k| k > 0).collect(); + let before = lead_scans(); + let leads = first_para_leads(&texts, &continues); + assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before); + assert_eq!(leads.first(), Some(&None)); + assert!(leads.iter().skip(1).all(|l| *l == Some('時'))); + // A paragraph break stops the carry, and a frame that starts a paragraph carries nothing. + let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]); + assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]); +} From 74f139062b468992fb79d76d2e0277a46702861c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:31:23 -0800 Subject: [PATCH 07/26] Paragraph: Kurikaeshi Moji Shori scans a paragraph once while laying it out Each line that started with a repeat mark scanned the paragraph's text from its start for the character the mark stands for, so a paragraph with marks at the start of many lines took quadratic time to lay out. The scan now goes on from the line before. --- crates/text/src/layout/flow.rs | 47 ++++++++++++++++++++++++---------- crates/text/src/shape.rs | 14 ++++++++++ crates/text/src/tests.rs | 22 ++++++++++++++++ 3 files changed, 70 insertions(+), 13 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index f028d47898..3999401a05 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -13,7 +13,8 @@ use super::{ is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeated_char, shape_range}; +use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range}; +use std::cell::Cell; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -216,6 +217,9 @@ struct ParagraphData<'a, 'text> { /// Kurikaeshi Moji Shori: the character before a `continued` paragraph in the frames before /// ([`TextObject::first_para_lead`]). lead: Option, + /// Kurikaeshi Moji Shori: the byte the paragraph's text has been scanned to for the character a + /// repeat mark could stand for, and that character so far ([`ParagraphData::repeat_base_before`]). + repeat_scan: Cell<(usize, Option)>, sg: Vec, compressed: Vec, wakan: Vec, @@ -234,6 +238,21 @@ struct ParagraphData<'a, 'text> { regions: Option<&'a [Region]>, } +impl ParagraphData<'_, '_> { + /// Kurikaeshi Moji Shori: the character a repeat mark at byte `at` of `text` could stand for, + /// the last one before it in the paragraph that [`repeat_base`] takes, or else the paragraph's + /// `lead`. Lines are laid out in order, so each call scans on from where the call before it + /// stopped; a byte before that starts the scan again at the paragraph's start. None when `at` + /// does not fall on a character boundary after the paragraph's start. + fn repeat_base_before(&self, text: &str, at: usize) -> Option> { + let (from, base) = self.repeat_scan.get(); + let (from, base) = if from <= at { (from, base) } else { (self.pr.start, self.lead) }; + let base = repeat_base(text.get(from..at)?).or(base); + self.repeat_scan.set((at, base)); + Some(base) + } +} + fn prepare_paragraph<'a, 'text>( cx: &mut Ctx<'text>, pen: &mut Pen<'_>, @@ -327,14 +346,16 @@ fn prepare_paragraph<'a, 'text>( let zone = if cx.opts.composer.unwrap_or(para.composer).is_single_line() { para.hyphenation.zone } else { 0.0 }; let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX); let mirror = mirrors_indents(para, rtl, cx.vertical); + let lead = t.first_para_lead.filter(|_| continued); ParagraphData { para, + repeat_scan: Cell::new((pr.start, lead)), pr, marker_text, bidi, rtl, continued, - lead: t.first_para_lead.filter(|_| continued), + lead, sg, compressed, wakan, @@ -1277,18 +1298,18 @@ fn emit_line_glyph( } /// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of -/// a line of the paragraph starting at byte `para_start`, when `g` is a repeat mark, and the -/// character it shows: the character [`repeated_char`] gives, shaped in the mark's style with the -/// type's features (so vertical type gets the font's vertical forms), from the same face, with the -/// mark's advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, -/// belongs to a tate-chu-yoko or warichu block, nothing before it in the paragraph fits, or the face -/// draws the character with no glyph or with more than one. `lead` stands before a paragraph that -/// continues from the frame before ([`TextObject::first_para_lead`]). -fn repeat_mark_glyph(cx: &Ctx<'_>, para_start: usize, lead: Option, g: &SGlyph) -> Option<(SGlyph, char)> { - if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() { +/// a line of `paragraph`, when `g` is a repeat mark, and the character it shows: the character +/// [`repeated_char`] gives, shaped in the mark's style with the type's features (so vertical type +/// gets the font's vertical forms), from the same face, with the mark's advance and place, so the +/// line breaks stay as they are. None when `g` is no repeat mark, belongs to a tate-chu-yoko or +/// warichu block, nothing before it in the paragraph fits, or the face draws the character with no +/// glyph or with more than one. The paragraph's `lead` stands before a paragraph that continues +/// from the frame before ([`TextObject::first_para_lead`]). +fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph) -> Option<(SGlyph, char)> { + if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(lead, cx.text.get(para_start..g.byte)?, g.ch)?; + let c = repeated_char(paragraph.repeat_base_before(cx.text, g.byte)?, "", g.ch)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1305,7 +1326,7 @@ fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: return None; } let g = paragraph.sg.get(first)?; - let (glyph, c) = repeat_mark_glyph(cx, paragraph.pr.start, paragraph.lead, g)?; + let (glyph, c) = repeat_mark_glyph(cx, paragraph, g)?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 9d09ce076e..097b056d7d 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -456,9 +456,23 @@ pub fn inseparable(a: char, b: char) -> bool { /// paragraph continues from the frame before the result for the text before it /// (`TextObject::first_para_lead`). pub fn repeat_base(text: &str) -> Option { + #[cfg(test)] + REPEAT_SCANNED.with(|c| c.set(c.get() + text.len())); text.chars().rev().find(|&c| !matches!(c, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '\u{2028}' | '\u{3099}' | '\u{309A}')) } +#[cfg(test)] +thread_local! { + /// Tests: how many bytes of text [`repeat_base`] was given on this thread. + static REPEAT_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Tests: how many bytes of text [`repeat_base`] has been given on this thread. +#[cfg(test)] +pub(crate) fn repeat_scanned() -> usize { + REPEAT_SCANNED.get() +} + /// Kurikaeshi Moji Shori: the character the repeat mark `mark` stands for after the text `before` /// it, or None when `mark` is not a repeat mark or nothing before it fits. `lead` stands before /// `before` (the text of a threaded paragraph in the frames before). VectorCraft's rules: the diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 477c3e3392..b15b0757be 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2810,6 +2810,28 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); } +/// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid +/// out in one scan of its text, not one scan of everything before each line. +#[test] +fn kurikaeshi_moji_shori_scans_a_paragraph_once() { + use crate::shape::repeat_scanned; + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let text = format!("時{}", "\u{2028}々".repeat(2000)); + let mut t = TextObject::point(Point::ZERO, &text, st); + t.para.kurikaeshi_moji_shori = true; + let before = repeat_scanned(); + let l = layout(&db, &t); + let scanned = repeat_scanned() - before; + assert!(scanned <= 2 * text.len(), "{scanned} bytes scanned for a paragraph of {}", text.len()); + // Every line's 々 is still drawn as 時. + assert_eq!(l.repeat_marks.len(), 2000); + assert!(l.glyphs.iter().filter(|g| g.byte > 0 && text.get(g.byte..).is_some_and(|s| s.starts_with('々'))).all(|g| g.gid == face.glyph_for('時'))); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] From a5b84d8e2ae997a1059ce4ce22573de0e1d13ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:38:15 -0800 Subject: [PATCH 08/26] Paragraph: Kurikaeshi Moji Shori keeps one record per mark when area type flows again Vertically aligned area type in a frame that is not a rectangle flows its text again until it settles, and each pass added the line-start repeat marks to the layout's records once more, so SVG export could look up the wrong character. Each pass now starts from empty records, and an undone pass restores the ones before it. --- crates/text/src/layout/vertical.rs | 3 ++- crates/text/src/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 30f12139a2..3262362fae 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -529,13 +529,14 @@ pub(super) fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range], t: &Tex std::mem::take(&mut cx.out.lines), std::mem::take(&mut cx.out.inlines), std::mem::take(&mut cx.out.markers), + std::mem::take(&mut cx.out.repeat_marks), std::mem::replace(&mut cx.out.overflow, false), ); flow(cx, paras, t, Some(regions)); if laid_out(&cx.out) < before { // Text no longer fits (lines got narrower, or flow around a wrap object): undo the // pass and try a smaller step. - (cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.markers, cx.out.overflow) = prev; + (cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.markers, cx.out.repeat_marks, cx.out.overflow) = prev; for (r, (shift, gap)) in regions.iter_mut().zip(saved) { r.shift = shift; r.gap = gap; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index b15b0757be..d2940f83b5 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2832,6 +2832,29 @@ fn kurikaeshi_moji_shori_scans_a_paragraph_once() { assert!(l.glyphs.iter().filter(|g| g.byte > 0 && text.get(g.byte..).is_some_and(|s| s.starts_with('々'))).all(|g| g.gid == face.glyph_for('時'))); } +/// Kurikaeshi Moji Shori: area type in a frame that isn't a rectangle, centered vertically, flows +/// again until it settles, and keeps one record for each repeat mark it draws as another character. +#[test] +fn vertically_centered_repeat_marks_in_a_round_frame_are_recorded_once() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + use vectorcraft_doc::VerticalAlign; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let text = format!("時{}", "\u{2028}々".repeat(5)); + let frame = kurbo::Ellipse::new((150.0, 150.0), (150.0, 150.0), 0.0).to_path(0.1); + let mut t = area(&text, st, Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) }; + t.para.kurikaeshi_moji_shori = true; + let top = layout(&db, &t); + let marks: Vec<(usize, char)> = text.match_indices('々').map(|(b, _)| (b, '時')).collect(); + assert_eq!(top.repeat_marks, marks); + t.area.vertical_align = VerticalAlign::Center; + let lay = layout(&db, &t); + assert!(lay.lines[0].baseline > top.lines[0].baseline + 1.0, "the text moves down"); + assert_eq!(lay.repeat_marks, marks); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] From fcaed952fb9825420cbc99d6b7848f47e4092cef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:50:38 -0800 Subject: [PATCH 09/26] Paragraph: Kurikaeshi Moji Shori draws a threaded type-on-path frame's first repeat mark A frame of type on a path whose first paragraph continues from the frame before now draws a repeat mark at its start as the character before it in the frames before, as area and point type do. The mark keeps its advance, so the glyphs stay where they were, and live SVG text writes the character drawn. --- crates/text/src/layout/flow.rs | 24 +++++++++++++----------- crates/text/src/layout/on_path.rs | 22 +++++++++++++++++++++- crates/text/src/tests.rs | 18 ++++++++++++++++++ 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 3999401a05..50f0cef433 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1298,18 +1298,17 @@ fn emit_line_glyph( } /// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of -/// a line of `paragraph`, when `g` is a repeat mark, and the character it shows: the character -/// [`repeated_char`] gives, shaped in the mark's style with the type's features (so vertical type -/// gets the font's vertical forms), from the same face, with the mark's advance and place, so the -/// line breaks stay as they are. None when `g` is no repeat mark, belongs to a tate-chu-yoko or -/// warichu block, nothing before it in the paragraph fits, or the face draws the character with no -/// glyph or with more than one. The paragraph's `lead` stands before a paragraph that continues -/// from the frame before ([`TextObject::first_para_lead`]). -fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph) -> Option<(SGlyph, char)> { +/// a line, when `g` is a repeat mark, and the character it shows: the character [`repeated_char`] +/// gives for the character `base` finds before the mark, shaped in the mark's style with the type's +/// features (so vertical type gets the font's vertical forms), from the same face, with the mark's +/// advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, belongs +/// to a tate-chu-yoko or warichu block, `base` gives None, nothing before it fits, or the face draws +/// the character with no glyph or with more than one. `base` runs only for a repeat mark. +pub(super) fn repeat_mark_glyph(cx: &Ctx<'_>, g: &SGlyph, base: impl FnOnce() -> Option>) -> Option<(SGlyph, char)> { if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(paragraph.repeat_base_before(cx.text, g.byte)?, "", g.ch)?; + let c = repeated_char(base()?, "", g.ch)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1320,13 +1319,16 @@ fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph /// Kurikaeshi Moji Shori: the glyph drawn in place of glyph `first` of `paragraph`, the first /// character of a line that ends before glyph `end`, when the paragraph has the setting on and -/// [`repeat_mark_glyph`] gives one; it is recorded in [`crate::TextLayout::repeat_marks`]. +/// [`repeat_mark_glyph`] gives one for the character before it in the paragraph, or the paragraph's +/// `lead` before a paragraph that continues from the frame before ([`TextObject::first_para_lead`]); +/// it is recorded in [`crate::TextLayout::repeat_marks`]. fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: usize, end: usize) -> Option { if !paragraph.para.kurikaeshi_moji_shori || first >= end { return None; } let g = paragraph.sg.get(first)?; - let (glyph, c) = repeat_mark_glyph(cx, paragraph, g)?; + let text = cx.text; + let (glyph, c) = repeat_mark_glyph(cx, g, || paragraph.repeat_base_before(text, g.byte))?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index ecb1377d10..80aaa5ea9a 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -1,6 +1,6 @@ use super::bidi::{is_rtl, para_bidi_with, visual_order}; use super::breaking::{Metrics, optical_hangs, optical_hangs_rtl, optical_share, roman_share}; -use super::flow::list_markers; +use super::flow::{list_markers, repeat_mark_glyph}; use super::region::in_range; use super::{ Affine, ArcPath, BezPath, Ctx, GlyphBend, Justify, LineInfo, ListMarker, ParamCurve, PathAlign, PathData, PathEffect, PathEl, Point, Range, @@ -409,6 +409,21 @@ fn hide_before_open_path(cx: &mut Ctx<'_>, ap: &ArcPath, lead: bool, at: usize, true } +/// Kurikaeshi Moji Shori: type on a path is one line, which starts with the first character of its +/// first paragraph `pr` (shaped as `glyphs`). When that paragraph continues from the frame before +/// and has the setting on, a repeat mark there is drawn as the character before it in the frames +/// before ([`TextObject::first_para_lead`]): its glyph in `glyphs` is replaced, and the mark's byte +/// and the character drawn are returned. +fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range, glyphs: &mut [SGlyph]) -> Option<(usize, char)> { + if !t.first_para_continues || !t.para_at(0).kurikaeshi_moji_shori { + return None; + } + let g = glyphs.iter_mut().find(|g| g.len > 0 && g.byte == pr.start)?; + let (glyph, c) = repeat_mark_glyph(cx, g, || Some(t.first_para_lead))?; + *g = glyph; + Some((g.byte, c)) +} + /// Lay type on a path out along `path` (text space), between its brackets. pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, path: &PathData) { cx.out.on_path = true; @@ -431,6 +446,8 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, } shaped.push((pr.clone(), bidi.filter(|b| b.has_rtl() && !cx.vertical), glyphs)); } + // Kurikaeshi Moji Shori: the repeat mark that starts the line, recorded when its glyph is drawn. + let mut repeat = shaped.first_mut().and_then(|(pr, _, glyphs)| line_start_repeat(cx, t, pr, glyphs)); let rtl = rtl.unwrap_or(false); // The text before byte `cut` in visual order, as area type reorders each line it breaks. let visual = |cut: usize| { @@ -710,6 +727,9 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, let at = cx.out.glyphs.len(); cx.emit(g, pre, origin, angle, g.adv, 0); let hidden = hide_before_open_path(cx, &ap, lead, at, s + step * 0.5, rise); + if !hidden && let Some(mark) = repeat.take_if(|&mut (byte, _)| g.len > 0 && g.byte == byte) { + cx.out.repeat_marks.push(mark); + } // A glyph of a script whose letters join is bent along a curved path (Rainbow), so its // joining strokes meet its neighbours' instead of standing off the curve. if !hidden && t.path_effect == PathEffect::Rainbow && g.cursive && !cx.vertical && g.inline.is_none() { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index d2940f83b5..147b6a4818 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2808,6 +2808,24 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { let on = layout(&db, &t); assert_eq!(gid_of(&on, 0), glyph('時'), "the frame's first 々 is drawn as 時"); assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); + assert_eq!(on.repeat_marks, [(0, '時')]); + // Type on a path is one line: a threaded frame on a path starts it the same way. + let mut line = BezPath::new(); + line.move_to((0.0, 50.0)); + line.line_to((500.0, 50.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let on = layout(&db, &t); + assert!(on.on_path); + assert_eq!(gid_of(&on, 0), glyph('時'), "type on a path: the frame's first 々 is drawn as 時"); + assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "type on a path: the next paragraph's first mark keeps its glyph"); + assert_eq!(on.repeat_marks, [(0, '時')]); + t.para.kurikaeshi_moji_shori = false; + let off = layout(&db, &t); + assert_eq!(gid_of(&off, 0), glyph('々'), "type on a path with the setting off"); + assert!(off.repeat_marks.is_empty()); + t.para.kurikaeshi_moji_shori = true; + t.first_para_continues = false; + assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "type on a path in a frame that does not continue"); } /// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid From 7d7c5918f3966364c21e29953138929686e9ee69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:52:57 -0800 Subject: [PATCH 10/26] MCP docs: Kurikaeshi Moji Shori covers the first repeat mark of a frame of type on a path --- docs/mcp.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b0bdf2972e..0769d0a97e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9455,8 +9455,8 @@ https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html `text.setFormat {kurikaeshiMojiShori: bool}` (Paragraph panel menu › Kurikaeshi Moji Shori, shown with the East Asian options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / `end` -range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, is drawn as the -character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, +range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, or starts a frame +of type on a path (which holds one line), is drawn as the character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the @@ -9464,7 +9464,7 @@ repeated character is the last one before the mark in the paragraph that is not combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a -paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph +paragraph, and inside tate-chu-yoko or warichu. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the setting as it is, and a call that gives the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a From 3ca38f2237e73d24a87fbe7e13d3c6e12374df0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:01:43 -0800 Subject: [PATCH 11/26] =?UTF-8?q?Paragraph:=20Kurikaeshi=20Moji=20Shori=20?= =?UTF-8?q?draws=20=E3=82=9D=20or=20=E3=83=BD=20with=20a=20combining=20voi?= =?UTF-8?q?cing=20mark=20as=20voiced?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ゝ or ヽ followed by U+3099, which a font draws as one glyph, is now drawn at a line start as ゞ or ヾ would be, instead of as the plain kana. A mark that shares its cluster with other glyphs, or with any other combining character, keeps its own glyphs. --- crates/text/src/layout/flow.rs | 28 ++++++++++++++++++++++------ crates/text/src/layout/on_path.rs | 5 +++-- crates/text/src/tests.rs | 23 +++++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 50 insertions(+), 9 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 50f0cef433..36881e20d8 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1301,14 +1301,30 @@ fn emit_line_glyph( /// a line, when `g` is a repeat mark, and the character it shows: the character [`repeated_char`] /// gives for the character `base` finds before the mark, shaped in the mark's style with the type's /// features (so vertical type gets the font's vertical forms), from the same face, with the mark's -/// advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, belongs -/// to a tate-chu-yoko or warichu block, `base` gives None, nothing before it fits, or the face draws -/// the character with no glyph or with more than one. `base` runs only for a repeat mark. -pub(super) fn repeat_mark_glyph(cx: &Ctx<'_>, g: &SGlyph, base: impl FnOnce() -> Option>) -> Option<(SGlyph, char)> { +/// advance and place, so the line breaks stay as they are. ゝ or ヽ followed by a combining voicing +/// mark (U+3099) in one glyph counts as ゞ or ヾ. None when `g` is no repeat mark, belongs to a +/// tate-chu-yoko or warichu block, holds other characters with the mark, shares its cluster with the +/// glyph after it (`next`), `base` gives None, nothing before it fits, or the face draws the +/// character with no glyph or with more than one. `base` runs only for a repeat mark. +pub(super) fn repeat_mark_glyph( + cx: &Ctx<'_>, + g: &SGlyph, + next: Option<&SGlyph>, + base: impl FnOnce() -> Option>, +) -> Option<(SGlyph, char)> { if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(base()?, "", g.ch)?; + if next.is_some_and(|n| n.byte == g.byte) { + return None; + } + let mark = match cx.text.get(g.byte..g.byte + g.len)? { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + cluster if cluster.len() == g.ch.len_utf8() => g.ch, + _ => return None, + }; + let c = repeated_char(base()?, "", mark)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1328,7 +1344,7 @@ fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: } let g = paragraph.sg.get(first)?; let text = cx.text; - let (glyph, c) = repeat_mark_glyph(cx, g, || paragraph.repeat_base_before(text, g.byte))?; + let (glyph, c) = repeat_mark_glyph(cx, g, paragraph.sg.get(first + 1), || paragraph.repeat_base_before(text, g.byte))?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 80aaa5ea9a..b69470b9d9 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -418,8 +418,9 @@ fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range, glyphs: &m if !t.first_para_continues || !t.para_at(0).kurikaeshi_moji_shori { return None; } - let g = glyphs.iter_mut().find(|g| g.len > 0 && g.byte == pr.start)?; - let (glyph, c) = repeat_mark_glyph(cx, g, || Some(t.first_para_lead))?; + let at = glyphs.iter().position(|g| g.len > 0 && g.byte == pr.start)?; + let (glyph, c) = repeat_mark_glyph(cx, glyphs.get(at)?, glyphs.get(at + 1), || Some(t.first_para_lead))?; + let g = glyphs.get_mut(at)?; *g = glyph; Some((g.byte, c)) } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 147b6a4818..c04200a94f 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2828,6 +2828,29 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "type on a path in a frame that does not continue"); } +/// Kurikaeshi Moji Shori: ゝ or ヽ typed with a combining voicing mark (U+3099) after it, which the +/// font draws as one glyph, is drawn as the voiced character at a line start, as ゞ and ヾ are. +#[test] +fn kurikaeshi_moji_shori_draws_a_decomposed_voiced_mark_voiced() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let glyph = |c: char| Some(face.glyph_for(c)); + let gid_of = |l: &TextLayout, b: usize| l.glyphs.iter().find(|g| g.byte == b).map(|g| g.gid); + for (text, mark, want) in [("す\u{2028}ゝ\u{3099}", 'ゞ', 'ず'), ("サ\u{2028}ヽ\u{3099}", 'ヾ', 'ザ')] { + let at = text.find(['ゝ', 'ヽ']).expect("mark"); + let mut t = TextObject::point(Point::ZERO, text, st.clone()); + let off = layout(&db, &t); + assert_eq!(gid_of(&off, at), glyph(mark), "{text:?}: off, the font draws the voiced mark"); + t.para.kurikaeshi_moji_shori = true; + let on = layout(&db, &t); + assert_eq!(gid_of(&on, at), glyph(want), "{text:?}"); + assert_eq!(on.repeat_marks, [(at, want)], "{text:?}"); + } +} + /// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid /// out in one scan of its text, not one scan of everything before each line. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0769d0a97e..9dadf1c1d2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9463,7 +9463,8 @@ VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the -plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a +plain kana when it has none; ゝ or ヽ followed by a combining voicing mark (U+3099) counts as ゞ or ヾ when the font draws the +pair as one glyph, and is drawn as it is when the font draws two. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a paragraph, and inside tate-chu-yoko or warichu. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the From 9548a669a0e3c89435f4730a07cae2a0a2e3e7ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:17:36 -0800 Subject: [PATCH 12/26] SVG export: type on a path that starts with a drawn repeat mark is outlined Type on a path whose frame starts with a repeat mark drawn as the character it repeats is now written as outlines with a warning, as other type on a path that a cannot reproduce is. With Kurikaeshi Moji Shori off it stays live text. --- crates/svg/src/export/text.rs | 5 +++++ crates/svg/tests/it/text_layout.rs | 31 ++++++++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 5a1e811062..907068c56d 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -294,6 +294,11 @@ impl Writer<'_> { self.warn("type on a path with bullets or numbers is outlined to keep its look"); return self.text_outlines(n, t); } + // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). + if !lay.repeat_marks.is_empty() { + self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); + return self.text_outlines(n, t); + } return self.text_on_path(n, t, path, *start); } self.note_fonts(t, &lay); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index a190f21dea..ff27c96955 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -941,3 +941,34 @@ fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { } } } + +/// Kurikaeshi Moji Shori: a `` cannot draw a character in another character's width, so +/// type on a path whose threaded frame starts with a repeat mark drawn as the character it repeats +/// is outlined, with a warning; with the setting off it stays live text. +#[test] +fn a_repeat_mark_starting_a_frame_on_a_path_is_outlined() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), ..style(12.0) }; + let mut line = BezPath::new(); + line.move_to((20.0, 40.0)); + line.line_to((280.0, 40.0)); + for on in [false, true] { + let mut t = TextObject::point(Point::ZERO, "々龘々", st.clone()); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t.para.kurikaeshi_moji_shori = on; + t.first_para_continues = true; + t.first_para_lead = Some('龘'); + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = vectorcraft_svg::export_full(&d, &ExportOptions::default(), None); + let warned = out.warnings.iter().any(|w| w.contains("repeat mark")); + if on { + assert!(!out.svg.contains("々龘々<") && !warned, "{:?}: {}", out.warnings, out.svg); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 9dadf1c1d2..89393a9ae6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9458,7 +9458,8 @@ options) turns it on or off for the paragraphs of the selected type (or `ids`, o range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, or starts a frame of type on a path (which holds one line), is drawn as the character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. -SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. +SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded; it writes type on a +path that starts with such a mark as outlines, with a warning. VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph From 831e539ecc2455171bb1558f1e5f0a12a231da96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:54:05 -0800 Subject: [PATCH 13/26] SVG export: a drawn repeat mark in scaled type keeps its character's width In horizontally scaled type, live SVG text stretched the character a repeat mark is drawn as (Kurikaeshi Moji Shori) to the mark's advance with textLength, so a reader narrowed or widened it whenever the two glyphs' widths differ. Its textLength now takes the width the canvas draws that character at; the text after it is still placed anew. --- crates/svg/src/export/text.rs | 36 +++++++++++++++++++++++++++--- crates/svg/tests/it/text_layout.rs | 30 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 907068c56d..b341a62c0c 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -439,7 +439,8 @@ impl Writer<'_> { // reader would draw elsewhere, the next segment is placed. place = seg.brk || (!fewer && !base.anchored && positioned); if (st.h_scale - st.v_scale).abs() > 1e-9 || seg.scale != 1.0 { - attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(seg.advance * seg.scale))); + let length = seg.advance * seg.scale + seg.repeat_widen; + attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(length))); } if st.rotation != 0.0 { attrs.push_str(&format!(" rotate=\"{}\"", self.num(-st.rotation))); @@ -716,6 +717,9 @@ struct Segment { /// Glyph Scaling of the segment's one glyph (Justification…), which a reader stretches it to /// (`textLength`); 1 for other segments. scale: f64, + /// How much wider than the repeat mark the canvas draws the character the mark is drawn as + /// (Kurikaeshi Moji Shori), which a reader stretches it to (`textLength`); 0 for other segments. + repeat_widen: f64, /// A list marker's characters and tab, written in /// [`vectorcraft_doc::text::ParaList::marker_style`] of the run's style. marker: bool, @@ -736,6 +740,30 @@ fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_te lay.repeat_marks.get(at).map(|&(_, c)| c) } +/// Kurikaeshi Moji Shori: how much wider than repeat mark `cluster` the canvas draws glyph `g`, the +/// character the mark is drawn as in the mark's place (text space), or 0 when the face or the +/// mark's glyph is not found. +fn repeat_widen(g: &vectorcraft_text::PositionedGlyph, cluster: &str) -> f64 { + let Some(face) = FontDb::global().face_by_id(g.font_id) else { return 0.0 }; + // ゝ or ヽ with a combining voicing mark is drawn as one glyph, the voiced mark's. + let mark = match cluster { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + _ => match cluster.chars().next() { + Some(c) => c, + None => return 0.0, + }, + }; + let mark_gid = face.glyph_for(mark); + if mark_gid == 0 { + return 0.0; + } + // Font units along the baseline → text space (size, Horizontal Scale and Glyph Scaling). + let [a, b, ..] = g.xf.as_coeffs(); + let widen = (face.advance(g.gid) - face.advance(mark_gid)) * a.hypot(b); + if widen.is_finite() { widen } else { 0.0 } +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -829,6 +857,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - Some(c) => c.to_string(), None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), }; + let widen = if repeat.is_some() { repeat_widen(g, source(line.glyph_start + k, g)) } else { 0.0 }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; // The character a repeat mark is drawn as takes the mark's width on the canvas, which a // reader does not know: the text after it is placed anew. @@ -846,7 +875,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let marker = lay.marker_of(line.glyph_start + k).is_some(); let tab_apart = piece == "\t" && (run.style.h_scale - run.style.v_scale).abs() > 1e-9; match segs.last_mut() { - Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart => { + // The character a repeat mark is drawn as is a segment of its own, stretched to its width. + Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart && repeat.is_none() => { last.text.push_str(&piece); last.advance += advance; last.brk = brk; @@ -856,7 +886,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - last.brk |= moved || last.marker != marker; end_segment(last, tail, t, lay, &mut unkerned); } - segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, marker }); + segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, repeat_widen: widen, marker }); } } tail = set.map(|_| (g.byte, advance)); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index ff27c96955..95d2fd0b24 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -942,6 +942,36 @@ fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { } } +/// Kurikaeshi Moji Shori in horizontally scaled type: the character a repeat mark is drawn as is +/// stretched (`textLength`) to the width the canvas draws that character at, not to the mark's +/// advance, so a reader does not distort it when the two characters' widths differ. +#[test] +fn a_drawn_repeat_mark_in_scaled_type_keeps_the_width_of_its_character() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + // The test font draws 龘 and 々 with glyphs of different widths. + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), h_scale: 50.0, ..style(12.0) }; + let mut t = TextObject::point(Point::new(20.0, 40.0), "龘\u{2028}々", st); + t.para.kurikaeshi_moji_shori = true; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let svg = export(&d, &ExportOptions::default()); + // The textLength of each `` that holds 龘 alone: the one on the first line and the one + // the mark is drawn as on the second. + let lengths: Vec<&str> = svg + .match_indices(">龘<") + .map(|(at, _)| { + let tag = &svg[svg[..at].rfind('<').unwrap_or(0)..at]; + let from = tag.find("textLength=\"").unwrap_or_else(|| panic!("{tag}: {svg}")) + "textLength=\"".len(); + &tag[from..from + tag[from..].find('"').unwrap_or(0)] + }) + .collect(); + assert_eq!(lengths.len(), 2, "{svg}"); + assert_eq!(lengths[0], lengths[1], "{svg}"); +} + /// Kurikaeshi Moji Shori: a `` cannot draw a character in another character's width, so /// type on a path whose threaded frame starts with a repeat mark drawn as the character it repeats /// is outlined, with a warning; with the setting off it stays live text. From d4bbacc3ebb4bfac4b83eff349f483768abccfd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:57:09 -0800 Subject: [PATCH 14/26] Export: live effects in symbol art apply in EMF, WMF and SVG EMF, WMF and SVG wrote a symbol instance from its symbol's art as stored, so live effects inside that art were missing: a square moved 100 pt by a Transform effect stayed in place in the file while the canvas drew it moved. Art whose own place is off the artboard was left out even when the effect moved it onto it. These exports now call bake_document_placing_symbols, as PDF, print, EPS and DXF do: each instance of a symbol whose art needs baking is written as that art placed by the instance and then baked, so an instance that scales or turns its art does not scale what its effects do. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances are written as groups; instances of symbols without such effects still share one . Preserve Editing still embeds the document with its live effects. WrittenLayers gains hidden_objects. SVG sets it with Hidden Layers on, since it then writes hidden objects too, so a hidden instance is written hidden with its effects applied. The other exporters leave it off. An SVG instance nested in another instance's art was shared through when the def allowed its own transform, while the writes that transform after the outer instances'. A stroked symbol nested in a scaled instance then drew its stroke at double weight. The check now uses the transform the writes. --- crates/cad/src/lib.rs | 4 +- crates/effects/src/bake.rs | 24 ++++---- crates/effects/src/bake/tests.rs | 14 ++++- crates/eps/src/lib.rs | 4 +- crates/metafile/src/lib.rs | 11 ++-- crates/metafile/src/tests/import.rs | 37 +++++++++++++ crates/pdf/src/export/entry.rs | 1 + crates/pdf/src/print.rs | 2 +- crates/svg/src/export.rs | 8 ++- crates/svg/src/export/nodes.rs | 7 ++- crates/svg/tests/it/symbols_layers.rs | 79 +++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 12 files changed, 167 insertions(+), 25 deletions(-) diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index bb752267aa..6ab16c61e3 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -429,8 +429,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result { return Err("the export region is not finite".into()); } // Symbols' art is placed without clipping, as the scene places it. - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); let doc = baked.as_ref().unwrap_or(doc); Ok(scene::Scene::new(doc, opts).run()) } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d8f3ae0fe4..ec63c28707 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -162,7 +162,7 @@ struct Placing { layers: WrittenLayers, } -/// The layers an exporter writes besides the shown, printing ones +/// The layers and objects an exporter writes besides the shown, printing ones /// ([`bake_document_placing_symbols`]). Template layers are never written. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WrittenLayers { @@ -170,16 +170,19 @@ pub struct WrittenLayers { pub hidden: bool, /// Layers that do not print. pub non_printing: bool, + /// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden + /// layers). + pub hidden_objects: bool, } /// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`] -/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer +/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer /// that does not print when the export leaves those out ([`WrittenLayers`]). fn unwritten(n: &Node) -> bool { PLACING.with(|p| { p.borrow().as_ref().is_some_and(|p| match n.kind { NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden), - _ => !n.visible, + _ => !(n.visible || p.layers.hidden_objects), }) }) } @@ -1014,13 +1017,14 @@ pub fn bake_document(doc: &Document) -> Option { /// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or /// in the art of the symbols it places) replaced by that art as the instance places it, baked /// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For -/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than -/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped -/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the -/// exporter places other instances. `layers`: the hidden layers and layers that do not print -/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden -/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The -/// symbols' own art is left as it is. +/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and +/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`: +/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not +/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`: +/// the hidden layers, layers that do not print and hidden objects that the exporter writes. +/// Instances the export does not write (template layers, and the hidden objects and layers +/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as +/// it is. pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option { bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers))) } diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index fba4f75e5f..292d9461d6 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() { } /// Every layer written, as DXF writes them (template layers are never written). -const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true }; +const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; fn is_instance(d: &Document, id: u64) -> bool { d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) @@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() { } // An export that writes the layers that do not print, or the hidden layers, places that // layer's instance first; the template layer's instance is never placed. - for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] { + for (layers, first) in + [(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)] + { let out = bake(&d, Some((true, each, layers))).unwrap(); assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}"); } + // An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance + // first, and the instance in the hidden group would come next; the hidden layer's instance + // stays, since that layer is still left out. + let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap(); + assert!(!is_instance(&out, 901), "the hidden instance is placed"); + for id in [900, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } } /// `leaf` in `levels` groups, with ids from `id` up. diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index e36422b759..39737dae3a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -232,8 +232,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb } // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); let mut setting_notes = vec![]; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 86d268cee1..61126ef228 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -74,15 +74,18 @@ pub struct Output { } /// Write the visible art of `doc` over `region` (document space: its top-left corner is the -/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first; -/// template layers, hidden objects and guides are left out. Raster effects should be turned into -/// images before (the engine does); the ones left are reported and left out. +/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first, +/// in symbols' art too, where each instance places that art (EMF clips 9-slice cells, WMF does +/// not); template layers, hidden objects and guides are left out. Raster effects should be turned +/// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { let r = region.abs(); if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { return Err("the export region is empty".into()); } - let baked = vectorcraft_effects::bake_document(doc); + // The scene writes layers that do not print and leaves hidden layers and objects out. + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); let bytes = match kind { diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index f5870c5f95..622a800414 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -85,6 +85,43 @@ fn wmf_output_round_trips() { assert!(near(ellipse.geometric_bounds().unwrap(), Rect::new(100.0, 20.0, 180.0, 80.0), 0.1)); } +/// A symbol's square that a Transform effect moves 100 pt right is written where the canvas draws +/// it, in EMF and in WMF, read back: art whose own place is off the artboard is written where the +/// effect moves it onto it, and an instance that doubles the art's width places it first, so the +/// effect still moves it 100 pt (to x = 120, not 220). A stained instance keeps its stain. +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + let moved = |rect: Rect| { + let mut art = path(shapes::rectangle(rect), red(), Paint::None, 0.0); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: [("moveH", 100.0)].into_iter().collect(), + visible: true, + }); + art + }; + // The art's square, the instance's transform and fill, and the square and color it draws. + let cases = [ + (Rect::new(-90.0, 10.0, -80.0, 20.0), Affine::IDENTITY, None, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]), + (Rect::new(10.0, 30.0, 20.0, 40.0), Affine::scale_non_uniform(2.0, 1.0), Some(blue()), Rect::new(120.0, 30.0, 140.0, 40.0), [0, 0, 255]), + ]; + for (square, xf, stain, want, rgb) in cases { + let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf }); + if let Some(p) = stain { + inst.appearance = vectorcraft_doc::Appearance::basic(p, Paint::None, 0.0).into(); + } + let mut d = doc_with(200.0, 100.0, vec![inst]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: std::sync::Arc::new(moved(square)) }); + for kind in [Kind::Emf, Kind::Wmf] { + let back = import(&export(&d, d.artboards[0].rect, kind).unwrap().bytes).unwrap(); + let drawn: Vec<(Option, Option<[u8; 3]>)> = paths(&back.document).iter().map(|n| (n.geometric_bounds(), fill_rgb(n))).collect(); + assert_eq!(drawn.len(), 1, "{kind:?} {xf:?}: {drawn:?}"); + assert!(drawn[0].0.is_some_and(|b| near(b, want, 0.1)), "{kind:?} {xf:?}: {drawn:?}"); + assert_eq!(drawn[0].1, Some(rgb), "{kind:?} {xf:?}"); + } + } +} + #[test] fn freeform_points_that_share_a_model_are_written_as_their_mix() { use vectorcraft_color::{Color, Freeform, FreeformPoint, GradientKind}; diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 00ac16a3fe..fcdcd01f63 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -57,6 +57,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let layers = vectorcraft_effects::WrittenLayers { hidden: set.writes_layers() && !doc.page_knockout, non_printing: set.include_non_printing || set.create_layers, + hidden_objects: false, }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); // Baking stops early when cancelled, leaving a half-baked copy that must not be written. diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 2a3cbf98af..54e85f44b4 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -187,7 +187,7 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D // the art that prints; the layers kept are shown. let mut kept = doc.clone(); keep_layers(&mut kept.layers, set.print_layers); - let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); composite_overprints(&mut d, set); Cow::Owned(d) diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 05107bfb65..4c1f8f0ec2 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -38,7 +38,13 @@ const UNIQUE_PLACEHOLDER: &str = "u_vc_unique_-"; pub(crate) fn export(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>) -> Output { // Live geometry effects (Roughen, Warp, Offset Path, Effect → Pathfinder…) export as their result. - let baked = vectorcraft_effects::bake_document(doc); + // An instance of a symbol whose art has such effects is written as that art placed by the + // instance and then baked, as the canvas draws it; other symbols keep one `` def. + // Hidden layers and objects are written when the options keep them; layers that do not print + // always are. `native` (Preserve Editing) is the document as it is, with its live effects. + let hidden = opts.hidden_layers; + let layers = vectorcraft_effects::WrittenLayers { hidden, non_printing: true, hidden_objects: hidden }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); if opts.object_ids != ObjectIds::Unique { return write(doc, opts, native, ""); diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index ea1d5ab95b..b9af2a6c06 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1061,8 +1061,8 @@ impl Writer<'_> { (self.xf, self.instance_xf) = saved; return; } - if let Some(def) = self.symbol_use(sym, n, *xf) { - let m = self.xf * *xf; + let m = self.xf * *xf; + if let Some(def) = self.symbol_use(sym, n, m) { let tr = if m == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(m)) }; self.line(&format!("")); return; @@ -1103,7 +1103,8 @@ impl Writer<'_> { } } - /// The id of the `` def instance `inst` (transform `xf`) can ``, written on first + /// The id of the `` def instance `inst` can `` with transform `xf` (the ``'s + /// own: the instance's transform after those of the instances it sits in), written on first /// use. `None` when the instance needs its own copy of the art: stained by its fill, or moved /// by a transform under which the def would not look as the canvas paints it ([`Reuse`]). fn symbol_use(&mut self, sym: &vectorcraft_doc::Symbol, inst: &Node, xf: Affine) -> Option { diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 005a03e0fa..63b9136424 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -299,6 +299,85 @@ fn a_stained_instance_with_a_geometry_effect_keeps_its_stain() { } } +/// Symbol "Moved": a red square whose Transform effect moves it `dx` pt right. +fn add_moved_symbol(d: &mut Document, square: Rect, dx: f64) { + let mut art = Node::path(d.alloc_id(), shapes::rectangle(square), Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 0.0)); + art.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": dx}), visible: true }); + d.symbols.push(Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); +} + +/// Instances of a symbol whose art has a geometry effect are written as their art placed by the +/// instance and then baked, where the canvas draws it: moved by the instance, doubled in width +/// (the effect still moves it 100 pt, not 200 pt) and turned. They use no ``, while the +/// instances of a symbol without effects still share one. +#[test] +fn symbol_art_effects_are_written_where_the_canvas_draws_them() { + let mut d = symbol_doc(0.0, &[Affine::translate((30.0, 100.0)), Affine::translate((60.0, 100.0))]); + add_moved_symbol(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), 100.0); + instance(&mut d, "Moved", Affine::IDENTITY); + instance(&mut d, "Moved", Affine::translate((0.0, 20.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Moved", Affine::translate((-60.0, 40.0)) * Affine::rotate(0.5)); + let svg = export(&d, &ExportOptions::default()); + assert_eq!((svg.matches("