Files
vectorcraft/crates/engine/src/cmd/compositefonts.rs
T
dotCooCoo b8e11fb2c7 Place: a placed dimension reuses an equal composite font of the same name
When the document defined a composite font with the same name and the same
definition as one a placed dimension used, but spelled in more than the 256
bytes a dimension's family keeps (a case-insensitive match such as Kelvin
signs for k), placement copied the incoming font under a new name instead of
reusing the document's. The byte limit now applies only to an alias under
another name; a same-name reuse keeps the dimension's own spelling.

Merging main had also left a second, unguarded rename of a dimension's
family next to the guarded one, so a renamed family that was too long or
only differed in case was still written. The unguarded rename is removed.

docs/mcp.md describes how file.place renames a placed dimension's family.
2026-12-04 16:00:35 -08:00

641 lines
31 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]),
//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a
//! font of its own, and the characters of each custom character set in the set's font. Type names
//! a composite font as its family, and the font menus list them first. The font database holds the
//! active document's composite fonts ([`sync`]); a file exported here carries them to another
//! document.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
//! custom character sets:
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind};
use vectorcraft_text::FontDb;
use super::fileio::{read_file_head, write_file};
use super::textstyles::each_text_mut;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param};
/// The extension of the files Export writes and Import reads.
pub const EXTS: &[&str] = &["vccomposite"];
/// The id of the export command.
const EXPORT: &str = "type.compositeFonts.export";
/// The largest file Import reads, in bytes.
pub const MAX_FILE_BYTES: usize = 4 << 20;
/// The keys a part may give.
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
/// The keys a custom character set may give: its name and characters, then its part's values
/// (a set is never scaled at the center).
const SET_KEYS: [&str; 8] = ["name", "characters", "font", "style", "size", "baseline", "hScale", "vScale"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "type.compositeFonts.list",
"Composite Fonts",
[],
None,
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}, custom?: [{name, characters, font, style, size, baseline, hScale, vScale}]}]}",
has_doc,
list
),
cmd!(
"type.compositeFonts.set",
"Composite Fonts…",
["Type"],
None,
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}, custom?: [{name, characters?: string = \"\", font?, style?, size?, baseline?, hScale?, vScale?}]}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. custom lists custom character sets: each sets the characters it lists in its own font, style, size, baseline and scales (values left out are the kanji part's), ahead of their class; a character two sets list is set by the later one. A set's name is trimmed and unique in the font in any case; its characters are each listed once, at most 8192, none a control character or past U+FFFF; at most 64 sets. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
has_doc,
set
),
cmd!(
query "type.compositeFonts.export",
"Export Composite Fonts",
[],
None,
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads (a file over 4 MB is refused); without path the file's text comes back as data → {path, count} | {data, count}",
has_doc,
export
),
cmd!(
"type.compositeFonts.import",
"Import Composite Fonts",
[],
None,
"{path: .vccomposite file | data: its text | dataBase64: its bytes (at most 4 MB), apply?: bool = true} read the composite fonts a file holds (type.compositeFonts.export writes them); with apply they join the active document's, a font of the same name (any case) replaced, as one undo step, none when nothing changes; apply false only reads them → {fonts, imported: [name]}",
has_doc,
import
),
]
}
/// Every stored family name, including regeneration settings and retained style defaults.
/// Planning reads a private clone so gathering names never changes the destination.
fn family_names(d: &Document) -> Result<BTreeSet<String>> {
let mut view = d.clone();
let mut names = BTreeSet::new();
let mut note = |family: &mut String| {
names.insert(family.to_lowercase());
};
super::textstyles::each_text_mut(&mut view, &mut |text| {
for run in &mut text.runs {
note(&mut run.style.font_family);
}
Ok(())
})?;
for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) {
if let Some(Value::String(family)) = style.attrs.get_mut("font_family") {
note(family);
}
}
let (mut graphs, mut dimensions) = (Vec::new(), Vec::new());
view.visit_stored(|node, _| {
// A dimension's options name the family its label is redrawn in.
if let Some(dimension) = &node.extras().dimension {
dimensions.push(dimension.options.font_family.clone());
}
if node.extras().graph.is_some() {
graphs.push(node.id);
}
});
for mut family in dimensions {
note(&mut family);
}
for id in graphs {
if let Some(node) = view.stored_node_mut(id) {
graph_families(node, &mut note);
}
}
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
graph_families(node, note);
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
note(&mut dimension.options.font_family);
}
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
brush_graphs(Arc::make_mut(&mut mask.art), note);
}
for child in node.children_mut().into_iter().flatten() {
brush_graphs(Arc::make_mut(child), note);
}
}
for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) {
brush_graphs(art, &mut note);
}
Ok(names)
}
fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) {
let labels = &mut graph.label_styles;
for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() {
visit(&mut style.font_family);
}
}
}
/// Family fields held directly by one node; the adoption walker owns tree/resource traversal.
pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
if let NodeKind::Text(text) = &mut node.kind {
for run in &mut text.runs {
visit(&mut run.style.font_family);
}
// The fonts the file carried for this type are found by the family its runs name.
for font in text.file_fonts.iter_mut().flat_map(|fonts| fonts.fonts.iter_mut()) {
visit(&mut font.family);
}
}
// A dimension redraws its label from its own options, so they follow the label's family.
// A spelling that already names the same font, or one too long for the options, is kept.
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
let family = &mut dimension.options.font_family;
let mut renamed = family.clone();
visit(&mut renamed);
if !CompositeFont::same_name(&renamed, family) && renamed.len() <= ALIAS_BYTES_MAX {
*family = renamed;
}
}
graph_families(node, visit);
}
/// A fully checked incoming-only rename map and the destination's prospective definitions.
pub(super) struct CompositeImport {
names: BTreeMap<String, String>,
pub(super) combined: Vec<CompositeFont>,
}
impl CompositeImport {
pub(super) fn rename(&self, family: &mut String) -> bool {
if let Some(name) = self.names.get(&family.to_lowercase()) {
let changed = family.as_str() != name.as_str();
*family = name.clone();
changed
} else {
false
}
}
}
/// The longest family name in bytes that a dimension's options keep (`DimensionOptions::validate`).
const ALIAS_BYTES_MAX: usize = 256;
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
let db = FontDb::global();
let mut number = 2_u64;
loop {
let suffix = format!(" {number}");
let bytes = ALIAS_BYTES_MAX.saturating_sub(suffix.len());
let mut stem = String::new();
for c in base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())) {
if stem.len() + c.len_utf8() > bytes {
break;
}
stem.push(c);
}
let name = format!("{}{suffix}", stem.trim_end());
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
&& !reserved.contains(&name.to_lowercase())
&& !db.has_installed_family(&name)
{
return Ok(name);
}
number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?;
}
}
/// Plan used incoming definitions before changing either document or the font database.
/// Keep existing meanings even for an uninstalled family that destination art still names.
pub(super) fn plan_import(
source: Vec<CompositeFont>,
source_families: BTreeSet<String>,
dimension_families: BTreeSet<String>,
target: &Document,
cmd: &str,
) -> Result<CompositeImport> {
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
let mut source_names = BTreeSet::new();
for font in &source {
font.check().map_err(|why| bad(cmd, why))?;
if !source_names.insert(font.name.to_lowercase()) {
return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name)));
}
}
let target_families = family_names(target)?;
let mut target_taken = target_families.clone();
for font in target.composite_fonts.iter() {
target_taken.insert(font.name.to_lowercase());
target_taken.extend(font.part_fonts().map(str::to_lowercase));
}
// Families the source names without defining them as composite fonts, which the target does
// define: they stay undefined under a free name instead of taking the target's meaning.
let undefined: Vec<String> = source_families
.iter()
.filter(|family| !source_names.contains(*family) && !FontDb::global().has_installed_family(family))
.filter_map(|family| CompositeFont::named(&target.composite_fonts, family).map(|font| font.name.clone()))
.collect();
// Their alias may be a family the target's art already names without defining it, as an
// earlier placement of the same art left it, so that placement and this one share resources.
let mut alias_reserved = source_families.clone();
for font in source.iter().chain(target.composite_fonts.iter()) {
alias_reserved.insert(font.name.to_lowercase());
alias_reserved.extend(font.part_fonts().map(str::to_lowercase));
}
let mut reserved = source_families;
reserved.extend(target_families);
for font in source.iter().chain(target.composite_fonts.iter()) {
reserved.insert(font.name.to_lowercase());
reserved.extend(font.part_fonts().map(str::to_lowercase));
}
let db = FontDb::global();
let mut names = BTreeMap::new();
let mut combined = target.composite_fonts.to_vec();
for font in source {
let dimension = dimension_families.contains(&font.name.to_lowercase());
let equal = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
// A dimension keeps its own spelling of a reused name of the same font, so only an alias
// under another name has to fit the bytes its options keep.
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equal);
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
if needs_alias {
// A repeated import reuses its already-installed equal alias.
reused = target.composite_fonts.iter().find(|other| equal(other) && (!dimension || other.name.len() <= ALIAS_BYTES_MAX));
}
let name = match reused {
Some(other) => other.name.clone(),
None if needs_alias => composite_alias(&font.name, &reserved, cmd)?,
None => font.name.clone(),
};
reserved.insert(name.to_lowercase());
names.insert(font.name.to_lowercase(), name.clone());
if reused.is_none() {
combined.push(CompositeFont { name, ..font });
}
}
alias_reserved.extend(names.values().map(|name| name.to_lowercase()));
for family in undefined {
let name = composite_alias(&family, &alias_reserved, cmd)?;
alias_reserved.insert(name.to_lowercase());
names.insert(family.to_lowercase(), name);
}
// A source document may currently lend fonts to the database. Validate the prospective
// document, not composite names temporarily registered by a different document.
if combined.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
if let Some(font) = combined.iter().skip(target.composite_fonts.len()).find(|font| db.has_installed_family(&font.name)) {
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
}
if CompositeFont::usable(&combined).is_some() {
return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together"));
}
Ok(CompositeImport { names, combined })
}
/// Register the active document's composite fonts in the font database, and remove the ones the
/// other open documents (or an earlier active document) defined. Run after each command and when
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
/// switch draws type in the active document's own composite fonts, and type naming one it does
/// not define shows as missing. The lowercased names of the composite fonts added, changed or
/// removed.
pub(crate) fn sync(s: &mut Session) -> Vec<String> {
let db = FontDb::global();
let mut names = Vec::new();
let mut changed = Vec::new();
for f in s.active().map(|d| d.doc.composite_fonts.to_vec()).unwrap_or_default() {
let name = f.name.to_lowercase();
if db.set_composite_font(&f) {
changed.push(name.clone());
}
names.push(name);
}
let others = s.docs.iter().flat_map(|d| d.doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
let stale: Vec<String> = s.composite_names.iter().cloned().chain(others).filter(|n| !names.contains(n)).collect();
for gone in stale {
if db.remove_composite_font(&gone) {
changed.push(gone);
}
}
s.composite_names_registered.extend(names.iter().chain(&changed).cloned());
s.composite_names = names;
changed
}
/// The lowercased names of the composite fonts the open documents define, the font database holds
/// and the session has registered before: the names type may have been laid out in.
pub(crate) fn names_in_use(s: &Session) -> std::collections::HashSet<String> {
let defined = s.docs.iter().flat_map(|d| d.doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
let held = FontDb::global().composite_font_names().into_iter().map(|n| n.to_lowercase());
defined.chain(held).chain(s.composite_names_registered.iter().cloned()).collect()
}
/// Leave out a file's unusable composite fonts before registering and measuring its type.
pub(crate) fn filter_loaded(doc: &mut vectorcraft_doc::Document) {
let db = FontDb::global();
if let Some(kept) = CompositeFont::usable(&doc.composite_fonts) {
*doc.composite_fonts = kept;
}
doc.composite_fonts.retain(|f| !db.has_installed_family(&f.name));
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "fonts": *s.doc()?.doc.composite_fonts }))
}
/// Composite font `v` from command parameters or a file: its name trimmed, each part left out a
/// copy of the Kanji part, and keys or values a part can't take refused.
fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?;
if let Some(k) = o.keys().find(|k| !["name", "parts", "custom"].contains(&k.as_str())) {
return Err(bad(c, format!("unknown key `{k}`; a font takes name, parts and custom")));
}
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?;
let name = CompositeFont::clean_name(raw)
.ok_or_else(|| bad(c, format!("`{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
let parts = o.get("parts").and_then(Value::as_object).ok_or_else(|| bad(c, format!("`{name}`: parts must be an object")))?;
if let Some(k) = parts.keys().find(|k| !CharClass::ALL.iter().any(|c| c.key() == k.as_str())) {
return Err(bad(c, format!("`{name}`: unknown class `{k}`; the classes are kanji, kana, punctuation, symbols, roman and numerals")));
}
let part = |class: CharClass| -> Result<Option<CompositePart>> {
let Some(p) = parts.get(class.key()) else { return Ok(None) };
let po = p.as_object().ok_or_else(|| bad(c, format!("`{name}`: {} must be an object", class.key())))?;
if let Some(k) = po.keys().find(|k| !PART_KEYS.contains(&k.as_str())) {
return Err(bad(c, format!("`{name}`: unknown key `{k}` in {}", class.key())));
}
serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key())))
};
let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?;
let custom = match o.get("custom") {
None => Vec::new(),
Some(Value::Array(sets)) => {
if sets.len() > CUSTOM_SETS_MAX {
return Err(bad(c, format!("`{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets")));
}
sets.iter().map(|s| parse_set(s, &name, &kanji, c)).collect::<Result<Vec<_>>>()?
}
Some(_) => return Err(bad(c, format!("`{name}`: custom must be a list of character sets"))),
};
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji), custom };
for class in CharClass::ALL.into_iter().skip(1) {
if let Some(p) = part(class)? {
*f.parts.get_mut(class) = p;
}
}
f.check().map_err(|e| bad(c, format!("`{}`: {e}", f.name)))?;
Ok(f)
}
/// Custom character set `v` of composite font `font` from command parameters or a file: its name
/// trimmed, the part values it leaves out those of `kanji`, and keys or values it can't take
/// refused. [`CompositeFont::check`] checks its characters and values.
fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<CustomCharSet> {
let o = v.as_object().ok_or_else(|| bad(c, format!("`{font}`: each character set must be {{name, characters, font…}}")))?;
if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) {
return Err(bad(c, format!("`{font}`: unknown key `{k}` in a character set")));
}
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, format!("`{font}`: each character set needs a name")))?;
let name = CompositeFont::clean_name(raw)
.ok_or_else(|| bad(c, format!("`{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
let characters = match o.get("characters") {
None => String::new(),
Some(Value::String(s)) => s.clone(),
Some(_) => return Err(bad(c, format!("`{font}`: `{name}`: characters must be a string"))),
};
// Checked here as well as by `check`, so a huge list is refused before it is copied again.
if characters.chars().nth(CUSTOM_CHARS_MAX).is_some() {
return Err(bad(c, format!("`{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters")));
}
let mut part = serde_json::to_value(kanji).map_err(|e| bad(c, e.to_string()))?;
if let Some(p) = part.as_object_mut() {
for k in &SET_KEYS[2..] {
if let Some(given) = o.get(*k) {
p.insert(k.to_string(), given.clone());
}
}
}
let part: CompositePart = serde_json::from_value(part).map_err(|e| bad(c, format!("`{font}`: `{name}`: {e}")))?;
Ok(CustomCharSet { name, characters, part })
}
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
if fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
let db = FontDb::global();
let mut names = std::collections::HashSet::new();
for f in fonts {
if !names.insert(f.name.to_lowercase()) {
return Err(bad(c, format!("two composite fonts are named `{}`", f.name)));
}
if db.has_installed_family(&f.name) {
return Err(bad(c, format!("`{}` is the name of an installed font", f.name)));
}
}
for f in fonts {
let classes = CharClass::ALL.into_iter().map(|class| (class.key(), &f.parts.get(class).font));
for (part, font) in classes.chain(f.custom.iter().map(|s| (s.name.as_str(), &s.part.font))) {
if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() {
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, part)));
}
}
}
Ok(())
}
/// Make `after` the active document's composite fonts, as one undo step named `label` (none when
/// they are what it has). The font database forgets the ones taken out, and type set in a font
/// that changed is measured again.
fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()> {
let before = s.doc()?.doc.composite_fonts.to_vec();
if before == after {
return Ok(());
}
let changed = register(s, &before, &after);
let r = s.edit(label, |d, _| set_fonts(d, &after, &changed));
sync(s);
r
}
/// Before an edit makes `after` the active document's composite fonts (it has `before`), register
/// them in the font database and forget the ones taken out → the lowercased names of the fonts that
/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not.
pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec<String> {
let changed: Vec<String> =
before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect();
// A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name
// listed here that the document doesn't define.
s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase()));
let db = FontDb::global();
for f in before {
if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) {
db.remove_composite_font(&f.name);
}
}
for f in after {
db.set_composite_font(f);
}
changed
}
/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again.
pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> {
*d.composite_fonts = after.to_vec();
each_text_mut(d, &mut |t| {
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
refresh_bounds(t);
}
Ok(())
})
}
/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts
/// adds a font.
pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec<CompositeFont> {
let mut after = fonts.to_vec();
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
Some(a) => *a = f.clone(),
None => after.push(f.clone()),
}
after
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.set";
let list = p.get("fonts").and_then(Value::as_array).ok_or_else(|| bad(C, "give fonts: [{name, parts}…]"))?;
let fonts = list.iter().map(|v| parse_font(v, C)).collect::<Result<Vec<_>>>()?;
check_set(&fonts, C)?;
replace(s, "Composite Fonts", fonts.clone())?;
Ok(json!({ "fonts": fonts }))
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = EXPORT;
let path = text_param(p, "path", C)?;
if path.is_some_and(|p| p.trim().is_empty()) {
return Err(bad(C, "path is empty"));
}
let all = match p.get("fonts") {
None | Some(Value::Null) => s.doc()?.doc.composite_fonts.to_vec(),
Some(Value::Array(list)) => {
let fonts = list.iter().map(|v| parse_font(v, C)).collect::<Result<Vec<_>>>()?;
check_set(&fonts, C)?;
fonts
}
Some(_) => return Err(bad(C, "fonts must be a list of composite fonts")),
};
let fonts = match p.get("names") {
None | Some(Value::Null) => all,
Some(Value::Array(names)) => {
let mut out = Vec::with_capacity(names.len());
for n in names {
let n = n.as_str().ok_or_else(|| bad(C, "names must be strings"))?;
let f = all
.iter()
.find(|f| CompositeFont::same_name(&f.name, n.trim()))
.ok_or_else(|| bad(C, format!("no composite font named `{n}`")))?;
if !out.contains(f) {
out.push(f.clone());
}
}
out
}
Some(_) => return Err(bad(C, "names must be a list of names")),
};
if fonts.is_empty() {
return Err(bad(C, "no composite fonts to export"));
}
let bytes = file_bytes(&fonts)?;
match path {
Some(path) => {
write_file(path, &bytes)?;
Ok(json!({ "path": path, "count": fonts.len() }))
}
// The bytes are UTF-8 JSON text, so the lossy conversion changes nothing.
None => Ok(json!({ "data": String::from_utf8_lossy(&bytes), "count": fonts.len() })),
}
}
/// The bytes of an export file holding `fonts`: what [`import`] reads. Refused when they would make a
/// file larger than Import reads.
pub fn file_bytes(fonts: &[CompositeFont]) -> Result<Vec<u8>> {
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(EXPORT, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(EXPORT, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
Ok(text.into_bytes())
}
/// The composite fonts in the bytes of an exported file.
fn read_fonts(bytes: &[u8], c: &str) -> Result<Vec<CompositeFont>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| bad(c, format!("not a composite fonts file: {e}")))?;
let list = v.get("compositeFonts").and_then(Value::as_array).ok_or_else(|| bad(c, "not a composite fonts file: no compositeFonts list"))?;
if list.len() > COMPOSITE_FONTS_MAX {
return Err(bad(c, format!("the file holds more than {COMPOSITE_FONTS_MAX} composite fonts")));
}
list.iter().map(|f| parse_font(f, c)).collect()
}
fn import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.import";
let apply = switch_or(p, "apply", true, C)?;
let given = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
let too_large = || bad(C, "the file is larger than 4 MB");
let bytes = match given {
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
(None, Some(text), None) => {
if text.len() > MAX_FILE_BYTES {
return Err(too_large());
}
text.as_bytes().to_vec()
}
(None, None, Some(b64)) => {
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
return Err(too_large());
}
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(C, "dataBase64 is not base64"))?
}
_ => return Err(bad(C, "give one of path, data or dataBase64")),
};
if bytes.len() > MAX_FILE_BYTES {
return Err(too_large());
}
let fonts = read_fonts(&bytes, C)?;
if fonts.is_empty() {
return Err(bad(C, "the file holds no composite fonts"));
}
let mut names = std::collections::HashSet::new();
if let Some(f) = fonts.iter().find(|f| !names.insert(f.name.to_lowercase())) {
return Err(bad(C, format!("the file holds two composite fonts named `{}`", f.name)));
}
if apply {
let mut after = s.doc()?.doc.composite_fonts.to_vec();
for f in &fonts {
after = with_font(&after, f);
}
check_set(&after, C)?;
replace(s, "Import Composite Fonts", after)?;
} else {
check_set(&fonts, C)?;
}
let imported: Vec<&str> = fonts.iter().map(|f| f.name.as_str()).collect();
Ok(json!({ "fonts": fonts, "imported": imported }))
}
#[cfg(test)]
mod tests;