Merge main into feat/plugin-api-javascript-runtime

This commit is contained in:
dotCooCoo committed 2026-11-23 23:44:07 -08:00
commit 696bff8a42
1034 files changed
+156043 -265948

No files matched your search

+1
View File
@@ -94,6 +94,7 @@ pub(crate) mod slices;
pub mod spelling;
mod stroke;
mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
mod swatch;
@@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() {
#[test]
fn color_mask_refuses_previews_and_images_too_large() {
let preview = std::sync::Arc::new(framed());
let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
let (mut s, id) =
linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string();
assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}");
assert_eq!(mask_of(doc(&s), id), None);
+6 -1
View File
@@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
let preview = Arc::new(bytes);
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
let missing = place_linked(
&mut s,
"missing",
ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() },
(12, 10),
);
let before = (image_of(&s, missing), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
+1 -1
View File
@@ -135,7 +135,7 @@ impl Session {
/// Whether `name` is a built-in preset's, "Custom" (changed settings, as the panel and a traced
/// object show them), or a saved preset's other than the one at `except`.
fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
pub fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
tr::preset(name).is_some() || name.trim().eq_ignore_ascii_case("Custom") || self.trace_preset_index(name).is_some_and(|i| Some(i) != except)
}
+17 -2
View File
@@ -159,6 +159,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The fonts its file carried travel with it, as images do.
for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) {
f(Ref::Name(Res::Image, &ff.key));
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
@@ -807,6 +811,9 @@ impl Relink {
if relaid {
refresh_bounds(t);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| self.name(Res::Image, key));
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
@@ -1134,6 +1141,8 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// File-font resources refused while binding pasted type.
pub warnings: Vec<String>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
@@ -1158,13 +1167,18 @@ impl Imported {
}
}
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
if !self.warnings.contains(&note) {
self.warnings.push(note);
}
}
}
}
@@ -1462,6 +1476,7 @@ impl Clipboard {
&& out.relink.colors.is_empty()
&& out.relink.kinsoku.is_empty()
&& used.styles.is_empty());
out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d));
Ok(out)
}
+4 -4
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation};
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
use vectorcraft_color::{Color, Paint, keep_model};
use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
@@ -962,8 +962,8 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.harmony";
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
let rule = Harmony::parse(rule).ok_or_else(|| {
let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect();
let rule = harmony::parse(rule).ok_or_else(|| {
let ids: Vec<&str> = Harmony::ALL.iter().map(|h| h.id()).collect();
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
})?;
check_numbers(p, &["steps", "amount"], C)?;
@@ -972,7 +972,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
opts.steps = n.min(u32::MAX as u64) as u32;
}
if let Some(v) = text_param(p, "variation", C)? {
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
opts.variation = harmony::parse_variation(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
}
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
opts.amount = a as f32;
@@ -26,6 +26,7 @@ pub const MAX_FILE: usize = 64 << 10;
/// The most setups `view.proofSetup.list` lists.
pub const MAX_LISTED: usize = 100;
/// The most folder entries `view.proofSetup.list` looks at, setup files or not.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SCANNED: usize = 100_000;
/// The longest `name`, in characters.
const MAX_NAME: usize = 100;
+4 -4
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::{Harmony, THEME_SIZE};
use vectorcraft_color::harmony::{self, THEME_SIZE};
use vectorcraft_color::recolor::ColorKey;
use vectorcraft_tools::params::color_json;
@@ -98,7 +98,7 @@ fn next_name(s: &Session) -> String {
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "colorTheme.save";
let rule = match str_param(p, "rule") {
Some(r) => Some(Harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
Some(r) => Some(harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
None => None,
};
let colors: Vec<Color> = match (p.get("colors"), p.get("color")) {
@@ -107,7 +107,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
}
(None, Some(c)) => {
let base = color_value(c).ok_or_else(|| bad(C, "invalid `color`"))?;
rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?.theme(base)
harmony::theme(rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?, base)
}
_ => return Err(bad(C, "give `colors`, or `color` and `rule`")),
};
@@ -123,7 +123,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
if s.prefs.color_themes.iter().enumerate().any(|(i, t)| Some(i) != replace && t.name.eq_ignore_ascii_case(&name)) {
return Err(bad(C, format!("a theme is already called {name} (replace: \"{name}\" overwrites it)")));
}
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(Harmony::id) };
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(|h| h.id().to_owned()) };
match replace {
Some(i) => s.prefs.color_themes[i] = theme,
None => s.prefs.color_themes.push(theme),
+20 -9
View File
@@ -23,6 +23,9 @@ use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_par
/// 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.
const MAX_FILE_BYTES: usize = 4 << 20;
@@ -271,7 +274,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.export";
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"));
@@ -306,21 +309,29 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
if fonts.is_empty() {
return Err(bad(C, "no composite fonts to export"));
}
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
let bytes = file_bytes(&fonts)?;
match path {
Some(path) => {
write_file(path, text.as_bytes())?;
write_file(path, &bytes)?;
Ok(json!({ "path": path, "count": fonts.len() }))
}
None => Ok(json!({ "data": text, "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}")))?;
+3 -2
View File
@@ -1552,7 +1552,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
// Converted colors are compared with the document's resources, as another document's are
// (`Clipboard::import_into`); its images are still the document's own.
let imported = clip.import_into(d, choices, same_doc)?;
let mut imported = clip.import_into(d, choices, same_doc)?;
// Draw Inside: the clip group of the object drawn into, made on the first paste.
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
let artboards: Vec<usize> = boards
@@ -1570,7 +1570,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let mut c = d.reid(n);
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
imported.apply(&mut c, d);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
// A cross-document drag carries the graphic's appearance with it,
@@ -1698,6 +1698,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
"added": imported.added,
"merged": imported.merged,
"renamed": imported.renamed,
"warnings": imported.warnings,
}))
}
+1 -1
View File
@@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::native_file;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
+19 -11
View File
@@ -140,9 +140,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
// file or byte 10 of a bare picture (version 1 by its file's name), so a format whose
// signature starts the file is checked first.
// A PICT is known by its version opcodes after the picture's frame, at byte 522 of a file or
// byte 10 of a bare picture, so a format whose signature starts the file is checked first.
if vectorcraft_metafile::is_pict(bytes) {
return format("pict");
}
@@ -193,8 +192,11 @@ fn restore_or_import(
let mut fallback = None;
if let Some((intact, bytes)) = editing {
let native = if intact { bytes() } else { None };
match native.and_then(|b| native_file(&b).ok()) {
Some((doc, _, warnings)) => return Ok((doc, warnings, true)),
match native.and_then(|b| decode_native_file(&b).ok()) {
Some((mut doc, _, mut warnings)) => {
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
return Ok((doc, warnings, true));
}
None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }),
}
}
@@ -205,9 +207,9 @@ fn restore_or_import(
Ok((doc, warnings, false))
}
/// A native file's document and details, the colour profiles it carries installed where missing
/// (with a warning for each that can't be used).
pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
/// Decode a native file and install its colour profiles, preserving profile and depth warnings.
/// The caller must assemble any external resources and bind file fonts before layout.
pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
let f = vectorcraft_format::load_file(bytes).map_err(err)?;
let mut warnings = super::native::install_profiles(f.profiles);
warnings.extend(f.depth_notes);
@@ -424,7 +426,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
})?
}
"vectorcraft" | "template" => {
let (d, info, warnings) = native_file(bytes)?;
let (mut d, info, mut warnings) = decode_native_file(bytes)?;
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d));
native_pdf_compatible = Some(info.pdf_compatible);
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
(d, warnings, false)
@@ -688,7 +691,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
let update_links = s.prefs.update_links == "automatically";
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
let p = s.prefs.with_pdf_font_choice(p);
open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?)
}
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
@@ -860,7 +864,11 @@ impl ReadFile {
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut self.loaded.doc);
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
if !self.loaded.warnings.contains(&note) {
self.loaded.warnings.push(note);
}
}
}
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
+17 -16
View File
@@ -8,7 +8,10 @@ use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail};
use vectorcraft_pdf::{
APP, ActiveProfiles, Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail, default_preset_name,
leaves_out_bleed, page_bleed,
};
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
@@ -17,9 +20,6 @@ use crate::EngineError;
const C: &str = "document.exportPdf";
/// The built-in preset every PDF export starts from.
pub use vectorcraft_pdf::DEFAULT_PRESET;
/// The PDF options `document.formats` lists; `document.exportPdf` documents every field.
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
@@ -151,13 +151,13 @@ pub fn presets(s: &Session) -> Vec<String> {
/// The built-in preset names, then those of `saved`.
fn names(saved: &[PdfPreset]) -> Vec<String> {
vectorcraft_pdf::builtin_presets().into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
vectorcraft_pdf::builtin_presets(APP).into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
}
/// The preset `name` names: a built-in one (any case; `default` is the app default) or one of
/// `saved`.
pub fn find_preset(name: &str, saved: &[PdfPreset]) -> Option<PdfPreset> {
vectorcraft_pdf::builtin_preset(name).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
vectorcraft_pdf::builtin_preset(name, APP).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
}
fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
@@ -166,9 +166,10 @@ fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
.ok_or_else(|| bad(cmd, format!("unknown PDF preset `{name}` (presets: {})", names(saved).join(", "))))
}
/// The settings of the preset `p` names (default: [`DEFAULT_PRESET`]), before `p`'s options.
/// The settings of the preset `p` names (default: [`default_preset_name`]), before `p`'s options.
pub fn preset_settings(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
preset(cmd, str_param(p, "preset").unwrap_or(DEFAULT_PRESET), saved)
let default = default_preset_name(APP);
preset(cmd, str_param(p, "preset").unwrap_or(&default), saved)
}
/// Merge `over` into `base`: objects key by key (recursively), `null` keeps the base (the
@@ -194,7 +195,7 @@ pub(crate) fn pdf_error(cmd: &str, e: PdfError) -> EngineError {
}
/// The settings `p` asks for: its preset (built-in or one of `saved`; default
/// [`DEFAULT_PRESET`]) with `p`'s options applied over it. Choosing another standard turns
/// [`default_preset_name`]) with `p`'s options applied over it. Choosing another standard turns
/// Preserve Editing off, the layers off where it has none, and sets the latest compatibility it
/// allows, unless `p` asks for those. Checked as a preset is
/// ([`PdfSettings::check_values`]): profiles that aren't there pass. Keys that aren't PDF options
@@ -219,14 +220,14 @@ pub fn resolve(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings>
s.compatibility = s.standard.version();
}
}
s.check_values().map_err(|e| pdf_error(cmd, e))?;
s.check_values().map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
/// [`resolve`], refusing what the writer can't honour ([`PdfSettings::check`]).
pub fn settings_with(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
let s = resolve(cmd, p, saved)?;
s.check().map_err(|e| pdf_error(cmd, e))?;
s.check(&ActiveProfiles::default()).map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
@@ -240,7 +241,7 @@ pub fn settings(cmd: &str, p: &Value) -> Result<PdfSettings> {
/// built-in presets. Params naming none come back as they are.
pub fn expand_preset<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Value>> {
let expanded = match str_param(p, "preset") {
Some(name) if vectorcraft_pdf::builtin_preset(name).is_none() => {
Some(name) if vectorcraft_pdf::builtin_preset(name, APP).is_none() => {
let set = settings_with(cmd, p, &s.prefs.pdf_presets)?;
let mut q = p.clone();
merge(&mut q, &serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))?);
@@ -316,7 +317,7 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
/// ([`vectorcraft_pdf::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
@@ -579,7 +580,7 @@ fn encode_carrying_at(
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
// includeNonPrinting, which writes them as printing art.
let set = &opts.settings;
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
let short = if bleed_check { short_of_bleed(doc, page_bleed(&set.bleed, doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
@@ -592,7 +593,7 @@ fn encode_carrying_at(
let mut notes = vec![];
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
// Setup gives.
if opts.settings.leaves_out_bleed(doc) {
if leaves_out_bleed(&opts.settings, doc) {
notes.push(Note::loss(BLEED_LEFT_OUT));
}
// Art that reaches the trim edge but leaves part of the page's bleed empty.
@@ -760,7 +761,7 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
};
note_texts(&notes)
}
_ => set.warnings(),
_ => set.warnings(&ActiveProfiles::default()).into_iter().map(|w| w.message).collect(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(json!({ "settings": v, "presets": presets(s), "changed": diff, "warnings": warnings }))
+21 -2
View File
@@ -47,6 +47,10 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs
/// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in
/// imported PDFs for opens and places that give none).
pub embedded_fonts: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
@@ -74,6 +78,7 @@ impl Default for LoadOptions {
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
embedded_fonts: true,
native: true,
link_pages: false,
}
@@ -84,7 +89,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -135,6 +140,10 @@ impl LoadOptions {
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?,
};
Ok(Self {
pages,
crop,
@@ -148,6 +157,7 @@ impl LoadOptions {
dxf,
editing_data,
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
link_pages,
@@ -177,6 +187,7 @@ impl LoadOptions {
text_as: self.text_as,
layers: self.layers,
uncalibrated_rgb: editor_document,
embedded_fonts: self.embedded_fonts,
..Default::default()
})
}
@@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene
/// The import options of [`page_document`].
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
ImportOptions {
pages: Some(vec![page]),
crop: o.crop,
password: o.password.clone(),
text_as: o.text_as,
layers: false,
embedded_fonts: o.embedded_fonts,
..Default::default()
}
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
+5 -4
View File
@@ -2,7 +2,8 @@
use serde_json::{Value, json};
use super::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
use super::*;
fn session(artboards: usize) -> Session {
@@ -310,7 +311,7 @@ fn bad_options_are_refused() {
#[test]
fn options_apply_over_the_preset() {
let mut s = session(1);
let a = b64(&export(&mut s, json!({"preset": DEFAULT_PRESET, "compression": {"compressText": false}})));
let a = b64(&export(&mut s, json!({"preset": default_preset_name(APP), "compression": {"compressText": false}})));
let b = b64(&export(&mut s, json!({"preset": "default"})));
assert!(a.len() > b.len(), "content streams left uncompressed");
assert!(String::from_utf8_lossy(&a).contains(" re") || String::from_utf8_lossy(&a).contains(" l"));
@@ -499,7 +500,7 @@ fn pdf_settings_summarise_changes_and_warnings() {
let mut s = Session::new();
let v = s.execute("document.pdfSettings", &json!({})).unwrap();
assert_eq!(v["settings"]["compatibility"], "1.7");
assert_eq!(v["presets"][0], DEFAULT_PRESET);
assert_eq!(v["presets"][0], default_preset_name(APP));
assert_eq!(v["changed"], json!([]));
assert_eq!(v["warnings"], json!([]));
let p = json!({"compatibility": "1.5", "compression": {"compressText": false}, "createLayers": true, "security": {"copy": false, "openPassword": ""}});
@@ -544,5 +545,5 @@ fn formats_list_the_pdf_options() {
assert!(pdf["options"].get(k).is_some(), "{k}");
}
assert_eq!(pdf["options"]["compatibility"]["default"], "1.7");
assert_eq!(pdf["options"]["preset"]["default"], DEFAULT_PRESET);
assert_eq!(pdf["options"]["preset"]["default"], default_preset_name(APP));
}
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_pdf::TextAs;
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
use super::*;
@@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() {
#[test]
fn load_options_read_text_and_layers() {
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false));
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap();
assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false));
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
let d = LoadOptions::default();
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true));
let n = LoadOptions { native: false, ..Default::default() };
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
}
@@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap();
assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted");
}
/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a
/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's).
fn carried_font_pdf(content: &str, height: f64) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
widths.join(" "),
n + 1
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file], None)
}
/// The glyphs of the active document's type (document space origins) and how many come from fonts
/// files carried.
fn glyphs(s: &Session) -> (Vec<kurbo::Point>, usize) {
let db = vectorcraft_text::FontDb::global();
let (mut at, mut carried) = (vec![], 0);
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
at.push(t.xf * g.origin);
carried += usize::from(db.is_file_font(g.font_id));
}
}
});
(at, carried)
}
/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited:
/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited,
/// it takes the substitute, which exports then name.
#[test]
fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() {
let mut s = Session::new();
let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let family = fonts[0]["family"].as_str().unwrap().to_string();
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}");
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}");
let (at, carried) = glyphs(&s);
assert_eq!((at.len(), carried), (11, 11), "every glyph the file's");
let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family);
assert!(!warned(&mut s), "drawn as the file draws it: not substituted");
// Saved and opened again: the same.
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
assert_eq!(glyphs(&s), (at.clone(), carried));
// Edited: the substitute, which exports name, and the font still missing.
let mut id = None;
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
id = Some(n.id);
}
});
let id = id.unwrap();
let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone();
assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted");
s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap();
assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font");
assert!(warned(&mut s), "edited: substituted");
let findings = preflight(&mut s);
assert!(
findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont"
&& f["name"].as_str().is_some_and(|n| n.contains(&family))
&& f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))),
"preflight identifies the substituted text owner: {findings}"
);
assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family));
// Undone: the file's look again.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s), (at, carried));
assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font");
}
#[test]
fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() {
let db = vectorcraft_text::FontDb::global();
let serif = db.face("Source Serif 4", "Regular").unwrap();
let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap();
let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em();
assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute");
let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET";
let bytes = carried_font_pdf(content, 200.0);
let mut reference = Session::new();
open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap();
let want = glyph_ink(&reference, false);
assert_eq!(want.len(), 3);
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
let compare = |s: &Session| {
let mut areas = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area");
assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3);
areas += 1;
}
});
assert_eq!(areas, 1);
let got = glyph_ink(s, false);
assert_eq!(got.len(), want.len());
for (got, want) in got.iter().zip(&want) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{got:?} is {off} pt from {want:?}");
}
};
compare(&s);
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap();
compare(&s);
}
fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject};
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() };
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap());
let mut doc = Document::new(100.0, 100.0);
doc.images.insert("chosen".into(), blob.clone());
let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() });
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
(doc, blob, id)
}
/// No machine fonts are needed: the two native documents own different synthetic glyphs under
/// the same key. Paste must relink its own bytes, including after closing the source tab.
#[test]
fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Native Owned File Font Regression";
let open_native = |s: &mut Session, doc: &Document| {
let bytes = vectorcraft_format::save_file(doc);
s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap()
};
let face_of = |s: &Session, id| {
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0];
FontDb::global().face_by_id(g.font_id).unwrap()
};
let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0);
let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0);
let mut s = Session::new();
open_native(&mut s, &a);
let a_index = s.active_index().unwrap();
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
open_native(&mut s, &b);
let b_index = s.active_index().unwrap();
let carried = face_of(&s, b_id).id();
assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice());
s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
assert!(s.close_document(b_index));
assert!(s.set_active(a_index));
let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}");
assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen"));
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
assert_eq!(face_of(&s, id).id(), carried);
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] {
let svg = options["format"] == "svg";
let exported = s.execute("document.serialize", &options).unwrap();
if svg {
let text = exported["text"].as_str().unwrap();
assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded");
} else {
let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
}
// SVG may warn that the same CSS description cannot distinguish these two x glyphs.
assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}");
}
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
let mut unowned = b.clone();
unowned.images.clear();
let report = open_native(&mut s, &unowned);
assert!(report["warnings"].to_string().contains(FAMILY));
assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font");
}
/// Place owns its carried font even after the decoded source is dropped, whether the destination
/// reuses an equal unbound blob or renames a key occupied by another font.
#[test]
fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Placed Owned Font Regression";
let (source, expected, _) = owned_font_document(FAMILY, 200.0);
let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source));
for same_bytes in [true, false] {
let mut host = Document::new(100.0, 100.0);
let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 };
host.images.insert("chosen".into(), blob);
let mut s = Session::new();
s.add_document(host, None);
let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap();
assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}");
let check = |s: &Session| {
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font");
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice());
drawn += 1;
}
}
});
assert_eq!(drawn, 1);
};
check(&s);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s).1, 0);
s.execute("edit.redo", &json!({})).unwrap();
check(&s);
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
check(&s);
}
}
fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::Affine;
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument};
let (source, expected, _) = owned_font_document(family, 200.0);
let bytes = vectorcraft_format::save_file(&source);
let blob = ImageBlob::new("application/json", bytes);
let key = format!("placed-font-{}", blob.content_key());
let mut host = Document::new(100.0, 100.0);
host.images.insert("chosen".into(), owned_font_document(family, 800.0).1);
host.images.insert(key.clone(), blob);
let placed = PlacedDocument {
key,
link: LinkInfo::new("/font-placement-regression.vectorcraft"),
bounding: false,
page_box: Default::default(),
width: 100.0,
height: 100.0,
xf: Affine::IDENTITY,
placement: Default::default(),
};
let id = host.alloc_id();
host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap();
(host, expected, id)
}
/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind
/// text to the host's unrelated font under the same key when reopened.
#[test]
fn placed_carried_fonts_survive_break_link_and_older_version_save() {
use vectorcraft_text::FontDb;
for break_link in [true, false] {
let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" };
let (host, expected, id) = linked_owned_font_document(family);
let mut s = Session::new();
s.add_document(host, None);
if break_link {
let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
assert_eq!(glyphs(&s).1, 1);
}
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id));
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}");
drawn += 1;
}
}
});
assert_eq!(drawn, 1, "{family}");
assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source");
}
}
/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode.
fn two_glyphs_for_one_character_pdf(content: &str) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>",
widths.join(" "),
n + 1,
n + 3
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None)
}
/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines.
fn glyph_ink(s: &Session, across: bool) -> Vec<kurbo::Rect> {
use kurbo::Shape;
let db = vectorcraft_text::FontDb::global();
let mut lines: [Option<kurbo::Rect>; 3] = [None; 3];
let mut add = |path: &kurbo::BezPath| {
let els = path.elements();
let mut start = 0;
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
let line = if across {
usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0)
} else {
usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0)
};
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
start = end;
}
};
s.doc().unwrap().doc.walk(|n| match &n.kind {
NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))),
NodeKind::Path { path, .. } => add(&path.to_bezpath()),
_ => {}
});
lines.into_iter().flatten().collect()
}
/// Two different glyphs of a carried font for one character can't both go into the font kept with
/// the document, which has one glyph per character, so the line with the other glyph is outlines.
/// Opened, saved in the native format and opened again, each glyph is still the one the file draws,
/// where it draws it: the same page opened as outlines is the reference.
#[test]
fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() {
let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET";
assert_carried_glyph_roundtrip(content, false);
}
#[test]
fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() {
let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET";
assert_carried_glyph_roundtrip(content, true);
}
fn assert_carried_glyph_roundtrip(content: &str, across: bool) {
let bytes = two_glyphs_for_one_character_pdf(content);
let mut reference_session = Session::new();
open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap();
let reference = glyph_ink(&reference_session, across);
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}");
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
assert!(
live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3,
"some glyphs stay type, the other is outlines: {:?}",
live_texts(&s)
);
let close = |s: &Session, what: &str| {
let got = glyph_ink(s, across);
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
for (got, want) in got.iter().zip(&reference) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
}
};
close(&s, "opened");
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
close(&s, "saved and reopened");
}
@@ -405,9 +405,9 @@ fn zipped_and_32_bit_layers_read() {
/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman.
#[test]
fn names_without_a_unicode_name_read_as_mac_roman() {
let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({}));
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}");
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}");
}
#[test]
+29 -9
View File
@@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts_of(d, art, false)
}
/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font
/// their file carried ([`in_file_fonts`]).
fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
if let NodeKind::Text(t) = &n.kind {
fonts.extend(t.runs.iter().flat_map(run_fonts));
let file = if drawn { in_file_fonts(t) } else { vec![] };
fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts));
}
};
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
@@ -659,21 +666,25 @@ impl<'a> Printed<'a> {
}
}
match &n.kind {
NodeKind::Text(_) => {
NodeKind::Text(t) => {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
let file = in_file_fonts(t);
for r in runs {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
// Drawn in a font its file carried: printed as the file drew it.
if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
@@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
/// families that aren't available (their type is drawn in the fallback font, not the font it
/// names) or styles that its family doesn't have (the closest style is drawn).
/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a
/// font its file carried isn't substituted.
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
substitution_warning_of(used_fonts(d))
substitution_warning_of(fonts_of(d, &[], true))
}
/// The families and styles of the runs of `t` drawn in a font its file carried
/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute,
/// though the font they name isn't available.
fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> {
let faces = vectorcraft_text::FontDb::global().file_faces(t);
t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect()
}
/// [`substitution_warning`] for type set in `fonts`.
+1 -1
View File
@@ -447,7 +447,7 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.layers_reveal = Some(crate::LayersReveal::Row(row));
st.revision += 1;
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
+1 -1
View File
@@ -563,7 +563,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
_ => img.blob.mime.clone(),
};
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview });
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() });
}
let mut warnings = vec![];
match previews.len() {
+2 -1
View File
@@ -960,10 +960,11 @@ impl Session {
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
// The color profiles the file carries are installed where missing, as opening it installs
// them, so the new document's assigned profiles draw and are saved with it.
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
// Linked images in its symbols, patterns and brushes are read from their files, as placing
// a document reads them.
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
Ok(Some(ReadProfile { doc, file, warnings }))
}
}
+7 -7
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets};
use vectorcraft_pdf::{APP, ActiveProfiles, PdfPreset, builtin_preset, builtin_presets};
use super::fileio::pdf::{find_preset, resolve};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
impl Session {
/// Every PDF preset: the built-in ones, then the saved ones.
pub fn pdf_presets(&self) -> Vec<PdfPreset> {
let mut v = builtin_presets();
let mut v = builtin_presets(APP);
v.extend(self.prefs.pdf_presets.iter().cloned());
v
}
@@ -93,16 +93,16 @@ impl Session {
/// Whether `name` is taken by a built-in PDF preset or a saved one other than the one at
/// `except`.
fn pdf_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
builtin_preset(name).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
builtin_preset(name, APP).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
}
}
fn row(p: PdfPreset, built_in: bool) -> Value {
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check().is_ok(), "description": p.description, "settings": p.settings })
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check(&ActiveProfiles::default()).is_ok(), "description": p.description, "settings": p.settings })
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let rows = builtin_presets().into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
let rows = builtin_presets(APP).into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
Ok(json!({ "presets": rows.collect::<Vec<_>>() }))
}
@@ -113,7 +113,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(n) => n.to_string(),
None => s.new_pdf_preset_name(),
};
if builtin_preset(&name).is_some() {
if builtin_preset(&name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and is read-only: save it under another name")));
}
let at = s.pdf_saved_index(&name);
@@ -145,7 +145,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "pdf.preset.delete";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
if builtin_preset(name).is_some() {
if builtin_preset(name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and stays")));
}
let i = s.pdf_saved_index(name).ok_or_else(|| bad(C, format!("no saved PDF preset named `{name}`")))?;
+1 -1
View File
@@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
};
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
}
/// Place the file `read` holds in the active document.
+16
View File
@@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
paint_refs(&mut r.style.fill, f);
paint_refs(&mut r.style.stroke, f);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| f(Ref::Image(key)));
}
}
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
@@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
dst.images.insert(new.to_string(), blob.clone());
}
}
// Equal font bytes can reuse an existing image entry whose runtime lease is still empty.
// Transfer the validated source lease too: cached text nodes hold only weak references.
for (old, (new, copy)) in &images {
if *copy {
continue;
}
let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue };
let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue };
let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) {
*target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
}
}
for (old, new) in copies(&symbols) {
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
def.name = new.to_string();
+5 -2
View File
@@ -333,7 +333,7 @@ fn read_source(
}
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let Some(blob) = out.images.get(&p.key) else { continue };
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
Some(bytes) => {
out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() });
out.images.insert(
p.key.clone(),
ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() },
);
}
None => {
previews.insert(p.key);
+2 -2
View File
@@ -651,8 +651,8 @@ mod tests {
let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}"));
assert_eq!(text_of(&s), "café€ 😀 end“q”");
assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character");
let mac = read(r"{\rtf1\mac \'8e\'a5}");
assert_eq!(text_of(&mac), "é•", "Mac Roman");
let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}");
assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman");
}
#[test]
+2 -15
View File
@@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
/// Byte `b` of Mac Roman.
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
const HIGH: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', //
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', //
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', //
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', //
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', //
'\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
match b {
0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
_ => char::from(b),
}
craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b)
}
/// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says:
@@ -344,7 +331,7 @@ mod tests {
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}");
}
/// The other character sets decode by their Encoding Standard decoders: the platform matters
+1
View File
@@ -396,6 +396,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool),
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
p!(
"updateLinks",
+1 -1
View File
@@ -67,7 +67,7 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
/// nothing is drawn get none.
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<Document> {
let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?;
let bleed = set.bleed.of(doc);
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, doc);
let mut art = doc.clone();
drop_guides(&mut art.layers);
let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None };
+4 -2
View File
@@ -1458,7 +1458,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A frame whose first paragraph continues from the frame before draws it without the
// paragraph's first-line indent and list marker.
super::threads::mark_continued(&mut doc);
@@ -1473,7 +1473,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
};
match read {
Ok(data) => {
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if r.proxy {
blob.proxy = Some(blob.bytes.clone());
@@ -1510,6 +1510,8 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let links_from = meta.path.clone().or_else(|| meta.links_from.clone());
let base = super::links::LinkBase::file(links_from.as_deref());
let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
// Bind only after the copy's external resources and linked files have been restored.
warnings.extend(Session::refresh_text_bounds(&mut doc));
let index = s.add_document(doc, meta.path.clone());
let st = s.doc_mut()?;
st.recovered = true;
+1 -1
View File
@@ -121,7 +121,7 @@ fn two_words_keep_their_space() {
#[test]
fn craft_fonts_glyphs_retype_too() {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.has_script("Jpan")) else {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
};
+8 -7
View File
@@ -329,14 +329,15 @@ impl Session {
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it (Override Character
/// Color as set): the Graphic Styles panel's previews.
pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, self.prefs.override_char_color);
n
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it, type's characters too
/// with `override_char_color` (the preference Override Character Color): the Graphic Styles
/// panel's previews.
pub fn styled_node(n: &Node, g: &GraphicStyle, override_char_color: bool) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, override_char_color);
n
}
// ---------- commands ----------
+7 -1
View File
@@ -97,6 +97,8 @@ pub fn specs() -> Vec<CommandSpec> {
#[derive(Clone, Debug, Default)]
pub struct DesignLibraries {
libs: Vec<DesignLibrary>,
/// How many times a library was set; the next library's [`DesignLibrary::generation`].
loads: u64,
}
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
@@ -108,6 +110,9 @@ pub struct DesignLibrary {
pub name: String,
/// The designs and the resources their art uses.
pub doc: Arc<vectorcraft_doc::Document>,
/// Which load of the library this is: it differs from every other load's, so a picture of a design of
/// this library is stale once the library is loaded again.
pub generation: u64,
}
impl DesignLibraries {
@@ -125,8 +130,9 @@ impl DesignLibraries {
/// before; with no designs, `id` no longer has any.
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
self.libs.retain(|l| l.id != id);
self.loads += 1;
if let Some(doc) = doc {
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc), generation: self.loads });
}
}
}
+2
View File
@@ -1850,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -2158,6 +2159,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
system_layout: t.system_layout,
fractional_widths: t.fractional_widths,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
+98 -5
View File
@@ -25,10 +25,11 @@ pub struct DocState {
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
/// `layer.highlight`).
pub layer_rows: Vec<NodeId>,
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
/// when the row was already highlighted. Panel state: not saved, not undoable.
pub locate_reveal: Option<NodeId>,
/// What the Layers panel reveals at its next pass, until the panel takes it: the panel opens
/// the layers around the row and scrolls to it, also when the row was already highlighted.
/// Set by `layer.locate` and, for what a top-level command, an interaction's commit or a
/// selection changed, by [`DocState::request_reveal`]. Panel state: not saved, not undoable.
pub layers_reveal: Option<LayersReveal>,
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
@@ -179,6 +180,30 @@ thread_local! {
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// What the Layers panel is asked to reveal ([`DocState::layers_reveal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayersReveal {
/// Open the layers around this row and scroll to it: it was highlighted, located or isolated.
Row(NodeId),
/// The current layer changed with no row highlighted: reveal that layer.
Current(NodeId),
/// The last selected object changed: reveal its row when Panel Options › Locate Selected
/// Objects is on.
Selected(NodeId),
}
/// What decides a [`LayersReveal`], as of one moment: the isolation, the highlighted rows, the
/// current layer and the last selected object of one document, with the request pending then.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayersView {
uid: u64,
isolation: Option<NodeId>,
rows: Vec<NodeId>,
active_layer: Option<NodeId>,
last_selected: Option<NodeId>,
reveal: Option<LayersReveal>,
}
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
/// its top-level layers open (a `.ai` another app wrote opens with none open).
@@ -326,7 +351,7 @@ impl DocState {
revision: 1,
active_layer,
layer_rows: vec![],
locate_reveal: None,
layers_reveal: None,
variables_highlight: None,
variables_sort: Default::default(),
isolation: None,
@@ -657,6 +682,74 @@ impl DocState {
pub fn highlighted_rows(&self) -> Vec<NodeId> {
self.layer_rows.iter().copied().filter(|id| self.doc.node(*id).is_some()).collect()
}
/// What decides the Layers panel's reveal request now.
pub(crate) fn layers_view(&self) -> LayersView {
LayersView {
uid: self.uid,
isolation: self.isolation,
rows: self.layer_rows.clone(),
active_layer: self.active_layer,
last_selected: self.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// [`DocState::layers_view`] as it was when interaction `it` began: what a commit of the
/// interaction changed is compared with that, since the previews changed the state meanwhile.
pub(crate) fn layers_view_before(&self, it: &Interaction) -> LayersView {
LayersView {
uid: self.uid,
isolation: it.isolation,
rows: it.layer_rows.clone(),
active_layer: it.active_layer,
last_selected: it.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// Ask the Layers panel to reveal what changed since `before`, in this order: isolation entered
/// or left, the highlighted rows, the last selected object, the current layer. A request made
/// meanwhile (`layer.locate`) stands, and nothing is asked while an interaction is open, so a
/// drag's previews reveal nothing and its commit does.
pub(crate) fn request_reveal(&mut self, before: &LayersView) {
if self.uid != before.uid || self.layers_reveal != before.reveal || self.interaction.is_some() {
return;
}
let now = self.layers_view();
let mut request = None;
if now.isolation != before.isolation {
request = self.reveal_isolation(now.isolation, before.isolation);
}
if request.is_none() && now.rows != before.rows {
request = self.highlighted_rows().first().copied().map(LayersReveal::Row);
}
// A new selection asks for its object even when it changed the current layer too: the panel
// falls back to the current layer when it does not locate the object.
if request.is_none() && now.last_selected != before.last_selected {
request = now.last_selected.map(LayersReveal::Selected);
// An emptied selection leaves no object to locate.
if request.is_none() && matches!(self.layers_reveal, Some(LayersReveal::Selected(_))) {
self.layers_reveal = None;
}
}
if request.is_none() && now.active_layer != before.active_layer {
request = self.current_layer().map(LayersReveal::Current);
}
if request.is_some() {
self.layers_reveal = request;
}
}
/// The request for isolation moving from `before` to `now`: entering opens the isolated row,
/// leaving opens the layers around the row that was isolated.
fn reveal_isolation(&mut self, now: Option<NodeId>, before: Option<NodeId>) -> Option<LayersReveal> {
if let Some(root) = now.filter(|r| self.doc.node(*r).is_some()) {
self.layers_open.set(root, true);
return Some(LayersReveal::Row(root));
}
let former = before?;
for around in self.doc.ancestry(former)?.into_iter().filter(|a| *a != former) {
self.layers_open.set(around, true);
}
Some(LayersReveal::Row(former))
}
/// The object whose opacity mask View Opacity Mask shows ([`DocState::mask_view`]): only while
/// its mask is being edited, so leaving editing by any route (undo, deleting the object) ends it.
pub fn shown_mask(&self) -> Option<NodeId> {
+3
View File
@@ -33,6 +33,9 @@ pub struct Interaction {
/// The bounding box of `selection` in `doc`, measured once for a move drag
/// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move.
pub(crate) move_box: std::sync::OnceLock<Option<vectorcraft_doc::OrientedBox>>,
/// A switch to another document keeps the previews as one undo step in this one, as a panel field's scrub keeps
/// its edits; otherwise the switch cancels the interaction, as it does a drag.
pub keep_on_switch: bool,
}
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
+1 -1
View File
@@ -433,7 +433,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use doc_state::{DocState, OpenRows, RecalledSelection};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
+16
View File
@@ -281,6 +281,10 @@ pub struct Prefs {
pub recovery_off_for_complex: bool,
pub recent_files_count: u32,
pub low_res_proxy_eps: bool,
/// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
/// fallback font with the missing-font warning (#4568).
pub pdf_import_embedded_fonts: bool,
pub anti_aliased_bitmaps: bool,
pub update_links: String,
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
@@ -446,6 +450,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
impl Prefs {
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) {
return p.clone();
}
let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) };
out["embeddedFonts"] = serde_json::json!(false);
out
}
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
/// checked against the range, so a value outside it is brought inside, and one that is not a
/// number gives the default.
@@ -592,6 +607,7 @@ impl Default for Prefs {
recovery_off_for_complex: false,
recent_files_count: 20,
low_res_proxy_eps: false,
pdf_import_embedded_fonts: true,
anti_aliased_bitmaps: false,
update_links: s("askWhenModified"),
pdf_text_as: s("text"),
+13 -3
View File
@@ -218,9 +218,14 @@ impl Session {
let _ = self.give_back_tool(view);
let _ = self.deactivate_tool(view);
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
// the rest of the batch; anything else in progress (a drag) is cancelled.
// the rest of the batch; one that keeps on a switch is kept; anything else in progress (a
// drag) is cancelled.
if self.batch_stash.is_none() {
let _ = self.cancel_interaction();
let _ = if self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) {
self.commit_interaction()
} else {
self.cancel_interaction()
};
}
self.keep_tool_settings();
self.tool = self.make_tool(self.tool.id());
@@ -293,7 +298,9 @@ impl Session {
/// what is fitted to type's bounds (an envelope warping it) would come out differently. That
/// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too,
/// not only in the layers (#1738).
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec<String> {
// The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]).
let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc);
// Inline graphics in text take their size from their symbols' art (not saved either).
doc.resolve_inline_art();
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
@@ -303,6 +310,7 @@ impl Session {
// The symbols' type is measured now: the inline graphics showing those symbols take their
// art's measured size, a symbol's type before the type that shows that symbol inline.
doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame);
warnings
}
/// Measure the type in open document `index` that `stale` picks (in its trees as
@@ -344,6 +352,8 @@ impl Session {
// (importers and the native reader have seen to theirs already, with a warning).
doc.limit_depth();
cmd::compositefonts::filter_loaded(&mut doc);
// Importers report binding failures; programmatic additions still need owned resources.
let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc);
// Inline graphics in text take their size from their symbols' art (not saved).
doc.resolve_inline_art();
// Ruler guides a reader left in the saved list become nodes on their layers.
+20
View File
@@ -7,6 +7,10 @@ impl Session {
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
self.revealing(|s| s.edit_unwatched(label, f))
}
fn edit_unwatched<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
if self.script_running() {
return Err(EngineError::Busy);
}
@@ -197,6 +201,10 @@ impl Session {
/// Change only the selection (not an undo step).
pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.revealing(|s| s.select_unwatched(f))
}
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.active_appearance_item = None;
let menu = self.menu.clone();
let st = self.doc_mut()?;
@@ -312,6 +320,7 @@ impl Session {
plane_placed: false,
copies: None,
move_box: std::sync::OnceLock::new(),
keep_on_switch: false,
});
Ok(())
}
@@ -390,6 +399,17 @@ impl Session {
}
pub fn commit_interaction(&mut self) -> Result<()> {
// The interaction is taken below, so its starting state is read first: the commit is what
// the previews that came before it changed.
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
let r = self.commit_interaction_unwatched();
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
fn commit_interaction_unwatched(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
+24
View File
@@ -59,6 +59,30 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
self.revealing(|s| s.execute_unwatched(id, params))
}
/// Run `f`, a top-level entry that changes the active document's rows, current layer or
/// selection, then ask the Layers panel to reveal what it changed ([`DocState::request_reveal`]).
/// Nothing is asked inside a command, while an interaction is open or while a tool is busy: the
/// entry that ends them asks.
pub(super) fn revealing<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let before = (self.depth == 0 && !self.tool_busy()).then(|| self.active().map(crate::DocState::layers_view)).flatten();
let r = f(self);
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
/// Ask the Layers panel of the active document to reveal what changed since `before`.
pub(super) fn reveal_since(&mut self, before: &crate::doc_state::LayersView) {
if let Some(st) = self.active_mut() {
st.request_reveal(before);
}
}
fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
// A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
+2 -2
View File
@@ -42,7 +42,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;
use vectorcraft_pdf::{PdfPreset, builtin_preset};
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
use vectorcraft_plugins::permissions::GrantToken;
use vectorcraft_plugins::safe_mode;
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
@@ -1555,7 +1555,7 @@ fn load_presets(dir: &Path) -> Vec<PdfPreset> {
for mut preset in file.presets {
let name = preset.name.trim().to_string();
let usable = !name.is_empty()
&& builtin_preset(&name).is_none()
&& builtin_preset(&name, APP).is_none()
&& !presets.iter().any(|q| q.name.eq_ignore_ascii_case(&name))
&& preset.settings.check_values().is_ok()
&& presets.len() < MAX_STORE_FILES;
+3 -3
View File
@@ -1,7 +1,7 @@
//! The Color Guide: `color.harmony` and saving several colours as swatches at once.
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::{Color, harmony};
use crate::*;
@@ -38,9 +38,9 @@ fn harmony_query_returns_the_group_and_its_grid() {
assert_eq!(r2["rule"], "splitComplementary");
assert_eq!(r2["grid"][0].as_array().unwrap().len(), 9, "4 steps by default");
// Every rule answers, base first.
for h in vectorcraft_color::harmony::Harmony::ALL {
for h in harmony::Harmony::ALL {
let r = s.execute("color.harmony", &json!({"color": "#3366cc", "rule": h.id()})).unwrap();
assert_eq!(r["colors"][0], "#3366cc", "{}", h.label());
assert_eq!(r["colors"][0], "#3366cc", "{}", harmony::label(h));
}
assert!(s.execute("color.harmony", &json!({"color": "#ff0000", "rule": "square"})).is_err());
assert!(s.execute("color.harmony", &json!({"rule": "triad"})).is_err());
+3 -3
View File
@@ -481,7 +481,7 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
fn a_colorized_missing_link_placeholder_is_not_flattened() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -502,7 +502,7 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() {
fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -523,7 +523,7 @@ fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.edit("Colorize", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
+2 -2
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::Harmony;
use vectorcraft_color::harmony::{self, Harmony};
use crate::*;
@@ -31,7 +31,7 @@ fn themes_save_list_edit_and_delete() {
let r = run(&mut s, "colorTheme.save", json!({"color": "#3366cc", "rule": "Triad", "name": " Sea "}));
assert_eq!(r["name"], "Sea");
let t = &run(&mut s, "colorTheme.list", json!({}))["themes"][1];
let want: Vec<String> = Harmony::Triad.theme(Color::from_hex("#3366cc").unwrap()).iter().map(Color::to_hex).collect();
let want: Vec<String> = harmony::theme(Harmony::Triad, Color::from_hex("#3366cc").unwrap()).iter().map(Color::to_hex).collect();
assert_eq!(t["colors"], json!(want));
assert_eq!(t["rule"], "triad");
// Names stay unique (ignoring case); replace edits a theme in place, renaming it if asked.
-10
View File
@@ -238,16 +238,6 @@ fn a_typed_closing_double_quote_opens_where_a_quote_opens() {
// More than one character is pasted text, not a typed quote.
let id = type_at(&mut s, 50.0, 300.0, &["”a”"]);
assert_eq!(text(&s, id).plain_text(), "”a”");
// An IME commit of a lone `”` that will open is not verbatim (it is rewritten); from the Glyphs
// panel it would be inserted as it is.
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 50.0, 312.0), v).unwrap();
}
assert!(!s.tool_typed_text_is_verbatim("”", v));
assert!(s.tool_text_is_verbatim("”", v));
s.tool_key(ToolKey::Escape, Default::default(), v).unwrap();
// A `”` inserted from the Glyphs panel or pasted alone stays as inserted.
let id = enter_at(&mut s, 50.0, 325.0, &["”", "a"], false);
assert_eq!(text(&s, id).plain_text(), "”a");
+2 -4
View File
@@ -5107,10 +5107,8 @@ fn the_pen_continues_any_open_path_and_joins_another() {
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::PenJoin);
assert_eq!(s.cursor(Point::new(350.0, 200.0), none, v), Cursor::PenDrawing, "the middle of the other path");
// #1009: Use Precise Cursors makes the join pointer a crosshair too.
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::Crosshair);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
// #1009: Use Precise Cursors makes the join pointer a crosshair too (the canvas applies `Cursor::precise`).
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v).precise(), Cursor::Crosshair);
assert_eq!(gesture(&mut s, &[(300.0, 200.0)], none), 1);
let pts = |s: &Session, id| path(s, id).subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|x| (x.p.x, x.p.y))).collect::<Vec<_>>();
assert_eq!(pts(&s, a), [(100.0, 100.0), (200.0, 100.0), (300.0, 200.0), (400.0, 200.0)]);
-16
View File
@@ -302,19 +302,3 @@ fn ime_target_survives_edits_and_changes_with_the_document() {
let second = s.tool_ime_target(v).expect("the new document's type has a target");
assert_ne!(first.0, second.0, "a document replacement is a new IME owner");
}
/// The outgoing surrounding-text source excludes the pre-edit and reports UTF-8 byte offsets.
#[test]
fn ime_surrounding_excludes_the_preedit_and_remaps_offsets() {
let mut s = session();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
click(&mut s, 100.0, 100.0);
s.tool_text("Hé", v).unwrap();
s.tool_preedit("xy", None, v).unwrap();
let vectorcraft_tools::ImeSurrounding::Available { text, cursor, anchor } = s.tool_ime_surrounding(4000, v) else {
panic!("type editing has a context");
};
assert_eq!(text, "Hé");
assert_eq!((cursor, anchor), (3, 3), "the caret sits after the committed text, before the pre-edit");
}
+52 -4
View File
@@ -1326,11 +1326,11 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
s.doc_mut().unwrap().locate_reveal = None;
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "the Layers panel reveals the located row");
s.doc_mut().unwrap().layers_reveal = None;
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
@@ -1342,12 +1342,60 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(g)), "{p}");
}
run(&mut s, "select.none", json!({}));
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
}
/// The session asks the Layers panel to reveal what a top-level command changed: isolation, then
/// the highlighted rows, the last selected object and the current layer. An open interaction asks
/// for nothing, and a failed command changes nothing.
#[test]
fn the_layers_panel_is_asked_to_reveal_what_a_command_changed() {
use crate::LayersReveal::{Current, Row, Selected};
let mut s = session();
let (layer, sub, _, g, b, c) = tree(&mut s);
let take = |s: &mut Session| s.doc_mut().unwrap().layers_reveal.take();
take(&mut s);
run(&mut s, "layer.highlight", highlight_params([c], "set"));
take(&mut s);
run(&mut s, "layer.highlight", highlight_params([g], "set"));
assert_eq!(take(&mut s), Some(Row(g)), "a highlighted row");
// The current layer changes with the selection of art in another layer: the new selection asks
// for its object, and the panel falls back to the current layer when it does not locate it.
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(take(&mut s), Some(Selected(c)), "a new selection wins over a new current layer");
// A new current layer alone asks for it: the highlighted row made current again.
run(&mut s, "layer.highlight", highlight_params([c], "set"));
take(&mut s);
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "layer.setCurrent", json!({"id": c.0}));
assert_eq!(take(&mut s), Some(Current(layer)), "a new current layer alone");
// Within the current layer only the last selected object changes.
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "select.set", json!({"ids": [b.0]}));
take(&mut s);
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(take(&mut s), Some(Selected(g)), "the last selected object");
// Isolation entered and left reveals the isolated row.
run(&mut s, "object.isolate", json!({"id": g.0}));
assert_eq!(take(&mut s), Some(Row(g)), "isolation entered");
run(&mut s, "object.exitIsolation", json!({}));
assert_eq!(take(&mut s), Some(Row(g)), "isolation left");
// A failed command asks for nothing.
assert!(s.execute("layer.locate", &json!({"id": 999_999})).is_err());
assert_eq!(take(&mut s), None);
// A command inside an open interaction asks for nothing either.
run(&mut s, "select.set", json!({"ids": [g.0]}));
take(&mut s);
s.begin_interaction("Drag").unwrap();
run(&mut s, "select.set", json!({"ids": [b.0]}));
assert_eq!(take(&mut s), None, "a preview");
s.cancel_interaction().unwrap();
}
#[test]
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
let mut s = session();
+9 -2
View File
@@ -1019,8 +1019,15 @@ fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_n
im.link.as_mut().unwrap().path = logo_ai.clone();
im.link.as_mut().unwrap().relative = None;
let key = im.key.clone();
d.images
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
d.images.insert(
key,
vectorcraft_doc::ImageBlob {
mime: "application/postscript".into(),
bytes: std::sync::Arc::new(eps.to_vec()),
proxy: None,
file_font: Default::default(),
},
);
Ok(())
})
.unwrap();
+23 -17
View File
@@ -1667,21 +1667,31 @@ fn mirror_axis(s: &Session) -> vectorcraft_tools::mirror::MirrorAxis {
vectorcraft_tools::mirror::MirrorAxis::of(&st.doc, &st.selection, 1.0).unwrap()
}
/// A press on the mirror axis at `at`, as the canvas's selection widgets take it.
fn mirror_press(s: &mut Session, at: Point) -> vectorcraft_tools::mirror::MirrorDrag {
s.with_tool_context(ViewInfo::default(), |cx| vectorcraft_tools::mirror::MirrorDrag::hit(cx, at, Mods::default())).expect("a press on the axis")
}
/// The mirror axis drag `d` moved to `to`, its actions applied as the canvas's selection widgets apply them.
fn mirror_drag(s: &mut Session, d: &mut vectorcraft_tools::mirror::MirrorDrag, to: Point, mods: Mods) {
let acts = s.with_tool_context(ViewInfo::default(), |cx| d.drag(cx, to, mods));
s.apply_actions(acts).unwrap();
}
#[test]
fn mirror_axis_drag_previews_once_and_undo_redo_preserve_source() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut s = session();
rect(&mut s, 100.0, 100.0, 60.0, 80.0);
let id = id_of(&s.execute("object.repeat.mirror", &json!({})).unwrap());
let before = node(&s, id);
let axis = mirror_axis(&s);
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let h = crate::tests::history(&s);
for (kind, dx) in [(PointerKind::Down, 0.0), (PointerKind::Drag, 20.0), (PointerKind::Drag, 30.0), (PointerKind::Up, 40.0)] {
s.pointer(&PointerEvent::new(kind, axis.center.x + dx, axis.center.y), v).unwrap();
let mut d = mirror_press(&mut s, axis.center);
for dx in [20.0, 30.0, 40.0] {
mirror_drag(&mut s, &mut d, axis.center + vectorcraft_geom::Vec2::new(dx, 0.0), Mods::default());
assert!(close(mirror_axis(&s).center, axis.center + vectorcraft_geom::Vec2::new(dx, 0.0)));
}
s.apply_actions(d.finish()).unwrap();
assert_eq!(crate::tests::history(&s).0, h.0 + 1);
let after = node(&s, id);
let (NodeKind::Repeat(a), NodeKind::Repeat(b)) = (&before.kind, &after.kind) else { panic!() };
@@ -1695,33 +1705,29 @@ fn mirror_axis_drag_previews_once_and_undo_redo_preserve_source() {
#[test]
fn mirror_axis_rotation_snaps_and_escape_restores_document_and_history() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
rect(&mut s, 100.0, 100.0, 60.0, 80.0);
let id = id_of(&s.execute("object.repeat.mirror", &json!({})).unwrap());
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let before = node(&s, id);
let h = crate::tests::history(&s);
let axis = mirror_axis(&s);
let end = axis.ends[1];
let destination = axis.center + vectorcraft_geom::Vec2::new(70.0, 60.0);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Drag, destination.x, destination.y).with_mods(shift), v).unwrap();
let mut d = mirror_press(&mut s, end);
mirror_drag(&mut s, &mut d, destination, shift);
assert!((mirror_axis(&s).angle - 45.0).abs() < 1e-6);
assert_eq!(mirror_axis(&s).center, axis.center);
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
s.pointer(&PointerEvent::new(PointerKind::Up, destination.x, destination.y), v).unwrap();
s.apply_actions(d.cancel()).unwrap();
assert_eq!(node(&s, id), before);
assert_eq!(crate::tests::history(&s), h);
// A click is not an edit, and a subsequent real drag still works after cancellation.
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y), v).unwrap();
let click = mirror_press(&mut s, end).finish();
s.apply_actions(click).unwrap();
assert_eq!(crate::tests::history(&s), h);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, destination.x, destination.y).with_mods(shift), v).unwrap();
let mut d = mirror_press(&mut s, end);
mirror_drag(&mut s, &mut d, destination, shift);
s.apply_actions(d.finish()).unwrap();
assert!((mirror_axis(&s).angle - 45.0).abs() < 1e-6);
assert_eq!(crate::tests::history(&s).0, h.0 + 1);
}
+5 -4
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use crate::Session;
use crate::cmd::fileio::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
fn session() -> Session {
let mut s = Session::new();
@@ -31,14 +31,15 @@ fn built_in_presets_are_listed_and_read_only() {
let mut s = session();
let v = s.execute("pdf.preset.list", &json!({})).unwrap();
let rows = v["presets"].as_array().unwrap();
assert_eq!(rows[0]["name"], DEFAULT_PRESET);
let default = default_preset_name(APP);
assert_eq!(rows[0]["name"], default);
assert!(rows.iter().all(|r| r["builtIn"] == true && !r["description"].as_str().unwrap().is_empty()));
let row = |n: &str| rows.iter().find(|r| r["name"] == n).unwrap_or_else(|| panic!("{n}"));
for n in ["High Quality Print", "Press Quality", "Smallest File Size", "PDF/X-1a:2001", "PDF/X-3:2002", "PDF/X-4:2010"] {
assert_eq!(row(n)["builtIn"], true);
}
assert!(rows.iter().all(|r| r["supported"] == true), "every built-in standard is written");
assert_eq!(row(DEFAULT_PRESET)["settings"]["preserveEditing"], true);
assert_eq!(row(&default)["settings"]["preserveEditing"], true);
// Read-only: neither changed nor deleted, in any case.
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "press quality", "compatibility": "1.4"}))));
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "default"}))));
@@ -96,7 +97,7 @@ fn presets_export_and_import_round_trip() {
let r = s.execute("pdf.preset.import", &json!({"data": text})).unwrap();
assert_eq!(r["imported"], json!(["Proof", "Press Quality 2"]), "a built-in name gets a number");
assert_eq!(s.prefs.pdf_presets[0], saved[0], "the same preset comes back");
let press = vectorcraft_pdf::builtin_preset("Press Quality").unwrap();
let press = vectorcraft_pdf::builtin_preset("Press Quality", APP).unwrap();
assert_eq!(s.prefs.pdf_presets[1].settings, press.settings);
// replace: saved presets of the same names are overwritten.
let r = s.execute("pdf.preset.import", &json!({"data": text, "replace": true})).unwrap();
+4 -1
View File
@@ -999,7 +999,10 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.edit("Brush", |d, _| {
d.images.insert("k".into(), vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert(
"k".into(),
vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() },
);
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 2,
+50 -31
View File
@@ -699,7 +699,8 @@ fn double_clicking_a_single_object_isolates_it() {
}
/// General › Use Precise Cursors (#394): the Pen's pointer becomes a crosshair; the Selection
/// tool's arrow stays.
/// tool's arrow stays. The canvas applies the preference to the tool's own pointer
/// (`Cursor::precise`).
#[test]
fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
use vectorcraft_tools::{Cursor, Mods};
@@ -712,41 +713,31 @@ fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(cursor(&mut s, "pen").precise(), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper").precise(), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection").precise(), Cursor::Arrow);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
}
/// Caps Lock gives the drawing tools the precise crosshair while it is on, and leaves the saved
/// Use Precise Cursors preference as it was.
/// Caps Lock is reported and set through `view.capsLock`, and leaves the saved Use Precise
/// Cursors preference as it was; the canvas gives the drawing tools the crosshair while it is on.
#[test]
fn caps_lock_gives_drawing_tools_the_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let cursor = |s: &mut Session, tool: &str| {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.cursor(vectorcraft_geom::Point::new(300.0, 300.0), Mods::default(), ViewInfo::default())
};
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
assert_eq!(s.execute("view.capsLock", &json!({"on": true})).unwrap(), json!({"on": true}));
assert!(!s.prefs.use_precise_cursors, "Caps Lock leaves the preference off");
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "lasso"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": true}));
assert_eq!(s.execute("view.capsLock", &json!({"on": false})).unwrap(), json!({"on": false}));
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
assert!(s.execute("view.capsLock", &json!({"on": 1})).is_err());
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
}
/// Use Precise Cursors changes the pointer of the tools that have one of their own: off, each shows its own
/// pointer; on, a crosshair. Every other drawing tool shows a crosshair either way, and the Type tool and the
/// Scissors over no path keep theirs.
/// pointer; on, a crosshair (the canvas applies `Cursor::precise` to it). Every other drawing tool shows a
/// crosshair either way, and the Type tool and the Scissors over no path keep theirs.
#[test]
fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
@@ -804,13 +795,13 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
}
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
for (tool, _) in own {
assert_eq!(cursor(&mut s, tool), Cursor::Crosshair, "{tool} on");
assert_eq!(cursor(&mut s, tool).precise(), Cursor::Crosshair, "{tool} on");
}
for tool in always {
assert_eq!(cursor(&mut s, tool), Cursor::Crosshair, "{tool} on");
assert_eq!(cursor(&mut s, tool).precise(), Cursor::Crosshair, "{tool} on");
}
assert_eq!(cursor(&mut s, "type"), Cursor::Text);
assert_eq!(cursor(&mut s, "scissors"), Cursor::ScissorsNotAllowed);
assert_eq!(cursor(&mut s, "type").precise(), Cursor::Text);
assert_eq!(cursor(&mut s, "scissors").precise(), Cursor::ScissorsNotAllowed);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
for (tool, c) in own {
assert_eq!(cursor(&mut s, tool), c, "{tool} off again");
@@ -818,7 +809,8 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
}
/// With no selected path, the Smooth tool shows Not Allowed, and Use Precise Cursors leaves it so; with a
/// selected path, it shows its own pointer, or a crosshair with the preference on.
/// selected path, it shows its own pointer, or a crosshair with the preference on (the canvas applies
/// `Cursor::precise`).
#[test]
fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
use vectorcraft_tools::{Cursor, Mods};
@@ -826,20 +818,21 @@ fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let at = vectorcraft_geom::Point::new(300.0, 300.0);
s.select_tool("smooth", ViewInfo::default()).unwrap();
let shown = |c: Cursor, precise: bool| if precise { c.precise() } else { c };
for precise in [false, true] {
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), Cursor::NotAllowed, "precise {precise}");
assert_eq!(shown(s.cursor(at, Mods::default(), ViewInfo::default()), precise), Cursor::NotAllowed, "precise {precise}");
}
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for (precise, c) in [(false, Cursor::Smooth), (true, Cursor::Crosshair)] {
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), c, "precise {precise}");
assert_eq!(shown(s.cursor(at, Mods::default(), ViewInfo::default()), precise), c, "precise {precise}");
}
}
/// With Alt held while drawing, the Pencil and the Paintbrush show their closing cursors, and Use Precise Cursors
/// turns those into a crosshair too.
/// turns those into a crosshair too (the canvas applies `Cursor::precise`).
#[test]
fn alt_shows_the_pencil_and_paintbrush_closing_cursors() {
use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind};
@@ -853,7 +846,9 @@ fn alt_shows_the_pencil_and_paintbrush_closing_cursors() {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0), ViewInfo::default()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), ViewInfo::default()).unwrap();
assert_eq!(s.cursor(at, alt, ViewInfo::default()), if precise { Cursor::Crosshair } else { c }, "{tool}, precise {precise}");
let shown = s.cursor(at, alt, ViewInfo::default());
assert_eq!(shown, c, "{tool}, precise {precise}");
assert_eq!(shown.precise(), Cursor::Crosshair, "{tool}");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), ViewInfo::default()).unwrap();
}
}
@@ -2167,10 +2162,14 @@ fn real_time_drawing_off_still_shows_a_dragged_nine_slice_guide() {
let left = |s: &Session| s.doc().unwrap().doc.symbol_nine_slice("Box").unwrap().left;
assert_eq!(left(&s), 0.25);
let steps = s.doc().unwrap().history.undo.len();
s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 150.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 110.0, 150.0), v).unwrap();
let drag = crate::tests::symbol_nine_slice::guide_drag(
&mut s,
v,
vectorcraft_geom::Point::new(125.0, 150.0),
vectorcraft_geom::Point::new(110.0, 150.0),
);
assert!((left(&s) - 0.1).abs() < 1e-9, "the guide moves while dragged: {}", left(&s));
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 150.0), v).unwrap();
s.apply_actions(drag.finish()).unwrap();
let d = s.doc().unwrap();
assert!((left(&s) - 0.1).abs() < 1e-9);
assert_eq!((d.history.undo.len(), d.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Symbol Options")));
@@ -2979,6 +2978,26 @@ fn snap_to_glyph_options_read_set_and_reset() {
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
}
/// File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default)
/// reaches Open and Place as the `embeddedFonts` choice, unless a call gives its own (#4568).
#[test]
fn the_embedded_fonts_preference_reaches_the_import_options() {
use crate::cmd::fileio::LoadOptions;
let mut s = Session::new();
assert!(s.prefs.pdf_import_embedded_fonts, "on by default");
let on = s.prefs.with_pdf_font_choice(&json!({}));
assert!(LoadOptions::from_params("x", &on).unwrap().embedded_fonts);
s.execute("prefs.set", &json!({"key": "pdfImportEmbeddedFonts", "value": false})).unwrap();
let off = s.prefs.with_pdf_font_choice(&json!({"page": 2}));
assert_eq!(off["page"], 2, "the call's own params stay");
assert!(!LoadOptions::from_params("x", &off).unwrap().embedded_fonts);
assert!(!LoadOptions::from_params("x", &s.prefs.with_pdf_font_choice(&Value::Null)).unwrap().embedded_fonts);
// A call that says so wins over the preference.
let own = s.prefs.with_pdf_font_choice(&json!({"embeddedFonts": true}));
assert!(LoadOptions::from_params("x", &own).unwrap().embedded_fonts);
assert!(LoadOptions::from_params("x", &json!({"embeddedFonts": "yes"})).is_err());
}
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
/// values change nothing, preferences saved without the group read it as all on, and resetting the
+71
View File
@@ -69,6 +69,77 @@ fn native_recovery_copies_leave_out_the_pdf() {
assert_eq!(vectorcraft_format::load(&bytes).unwrap().node_count(), s.doc().unwrap().doc.node_count());
}
const RECOVERY_FONT_FAMILY: &str = "Recovery Carried Font Regression";
const RECOVERY_FONT_BYTES: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
fn carried_font_copy() -> (Arc<MemoryStore>, vectorcraft_doc::NodeId) {
use vectorcraft_doc::{CharStyle, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind, TextObject};
let (mut s, store) = session();
let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.images.insert("recovered-font".into(), ImageBlob::new(FILE_FONT_MIME, RECOVERY_FONT_BYTES.to_vec()));
// An uninstalled family ensures the fixture must be read from the recovered resource.
let style = CharStyle { font_family: RECOVERY_FONT_FAMILY.into(), size: 20.0, ..Default::default() };
let mut text = TextObject::point(kurbo::Point::new(10.0, 40.0), "x", style);
text.file_fonts = Some(Box::new(FileFonts::new(
vec![FileFont { family: RECOVERY_FONT_FAMILY.into(), style: "Regular".into(), key: "recovered-font".into() }],
"x",
)));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
let saved = s.execute("file.recovery.save", &json!({})).unwrap();
let file = saved["saved"][0]["file"].as_str().unwrap();
let lean = vectorcraft_format::load(&store.read(&format!("{file}.vectorcraft")).unwrap()).unwrap();
assert!(lean.images.is_empty(), "the font travels in the recovery store, not the document entry");
drop(s);
(store, id)
}
#[test]
fn recovered_carried_fonts_bind_after_their_resources_are_restored() {
use vectorcraft_doc::NodeKind;
use vectorcraft_text::FontDb;
let (store, id) = carried_font_copy();
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
assert!(reply["restored"][0]["warnings"].as_array().unwrap().is_empty(), "{reply}");
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.images["recovered-font"].bytes.as_slice(), RECOVERY_FONT_BYTES);
let NodeKind::Text(text) = &doc.node(id).unwrap().kind else { panic!("text") };
let db = FontDb::global();
let laid = vectorcraft_text::layout(db, text);
assert_eq!(laid.glyphs.len(), 1);
let face = db.face_by_id(laid.glyphs[0].font_id).unwrap();
assert_eq!(face.file_data(), RECOVERY_FONT_BYTES, "layout uses the recovered font's exact bytes");
}
#[test]
fn recovered_missing_or_corrupt_carried_fonts_report_the_actual_refusal() {
for missing in [true, false] {
let (store, id) = carried_font_copy();
let blob = store.list().unwrap().into_iter().find(|name| name.ends_with(".blob")).unwrap();
if missing {
store.remove(&blob).unwrap();
} else {
store.write(&blob, b"not a font").unwrap();
}
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
let warnings = reply["restored"][0]["warnings"].as_array().unwrap();
assert!(
warnings.iter().any(|note| note.as_str().is_some_and(|note| note.contains(RECOVERY_FONT_FAMILY) && note.contains("substitute"))),
"missing={missing}: {reply}"
);
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
assert!(vectorcraft_text::FontDb::global().file_faces(text).is_empty(), "missing={missing}");
}
}
#[test]
fn restored_recovery_copies_keep_the_original_pdf_preference() {
let dir = crate::tests_links::Folder::new("recovered-pdf-preference");
+8 -2
View File
@@ -366,12 +366,18 @@ fn shaper_widget_switches_between_face_selection_and_construction_mode() {
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
}
};
// A click on the widget, as the canvas's selection widgets run it before the tool.
let widget_click = |s: &mut Session, p: Point| {
let acts: Vec<_> = s.with_tool_context(v, |cx| vectorcraft_tools::shaperwidget::click(cx, p).into_iter().collect());
assert!(!acts.is_empty(), "the click is on the widget");
s.apply_actions(acts).unwrap();
};
for tool in ["shaper", "selection"] {
s.select_tool(tool, v).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let w = widget(&s);
assert!(!w.construction);
click(&mut s, w.at);
widget_click(&mut s, w.at);
assert_eq!(s.doc().unwrap().isolation, Some(sources), "{tool}");
assert!(widget(&s).construction);
if tool == "shaper" {
@@ -388,7 +394,7 @@ fn shaper_widget_switches_between_face_selection_and_construction_mode() {
assert_eq!(fill(&s, g, 15.0, 50.0).as_deref(), Some("#ff0000"));
let w = widget(&s);
assert!(w.construction);
click(&mut s, w.at);
widget_click(&mut s, w.at);
assert_eq!(s.doc().unwrap().isolation, None, "{tool}");
assert_eq!(s.doc().unwrap().selection.objects, vec![g]);
s.execute("object.move", &json!({"dx": -10, "dy": 0})).unwrap();
+14 -6
View File
@@ -220,6 +220,16 @@ fn a_dynamic_instance_keeps_its_changes_through_the_guides() {
assert_ne!(fills[0].as_deref(), Some("#ff0000"), "only the changed object");
}
/// A press on the edited symbol's 9-slice guide at `from` dragged to `to`, run as the canvas's
/// selection widgets run it; the caller ends it with `finish` or `cancel`.
pub(super) fn guide_drag(s: &mut Session, v: ViewInfo, from: Point, to: Point) -> vectorcraft_tools::nineslice::GuideDrag {
let press = PointerEvent::new(PointerKind::Down, from.x, from.y);
let mut d = s.with_tool_context(v, |cx| vectorcraft_tools::nineslice::GuideDrag::hit(cx, &press)).expect("a guide at the press");
let acts = s.with_tool_context(v, |cx| d.drag(cx, to));
s.apply_actions(acts).unwrap();
d
}
/// The boxes of the paths a symbol instance `id` draws, placed through its symbol's guides.
fn placed_boxes(s: &Session, id: NodeId) -> Vec<Rect> {
let d = &s.doc().unwrap().doc;
@@ -247,9 +257,8 @@ fn a_guide_dragged_on_the_canvas_changes_how_a_scaled_instance_draws() {
// that span to the left of the left guide.
let (from, right) = (mid(&e, NineSliceGuide::Left), mid(&e, NineSliceGuide::Right));
let to = from + (from - right) * 0.4;
s.pointer(&PointerEvent::new(PointerKind::Down, from.x + 1.0, from.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y), v).unwrap();
let d = guide_drag(&mut s, v, Point::new(from.x + 1.0, from.y), to);
s.apply_actions(d.finish()).unwrap();
s.execute("symbol.exitEditing", &json!({})).unwrap();
let boxes = placed_boxes(&s, id);
assert_eq!(boxes.len(), 3, "{boxes:?}");
@@ -316,9 +325,8 @@ fn a_guide_dragged_past_the_arts_edge_lies_outside_it() {
// The guides lie a quarter in from each edge, so the art's left edge lies half the guides'
// distance to the left of the left guide, and 25 % outside it lies as far again.
let to = l - (r - l);
s.pointer(&PointerEvent::new(PointerKind::Down, l + 1.0, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to, y), v).unwrap();
let d = guide_drag(&mut s, v, Point::new(l + 1.0, y), Point::new(to, y));
s.apply_actions(d.finish()).unwrap();
let g = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap();
assert!((g.left + 0.25).abs() < 1e-9, "{g:?}");
let e = s.doc().unwrap().doc.edited_nine_slice().unwrap();
+16 -44
View File
@@ -6,7 +6,7 @@ use vectorcraft_geom::Point;
use vectorcraft_tools::distort::perspective::widget::WidgetPlace;
use vectorcraft_tools::draw2::FEEDBACK;
use vectorcraft_tools::shape::MAX_CORNER_RADIUS;
use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
use crate::{EngineError, Prefs, Result, Session};
@@ -42,6 +42,9 @@ pub struct ViewInfo {
pub screen: Option<vectorcraft_tools::ScreenFrame>,
/// The view's active artboard (an index): artboard rulers measure from it.
pub artboard: usize,
/// Precise cursors in this call: the canvas's `CanvasSpace::precise`, the preference toggled by
/// Caps Lock. The one source for the tools' crosshair and for hiding the brush tip.
pub precise: bool,
}
impl Default for ViewInfo {
@@ -61,6 +64,7 @@ impl Default for ViewInfo {
shape_widgets: true,
screen: None,
artboard: 0,
precise: false,
}
}
}
@@ -501,7 +505,7 @@ impl Session {
screen: view.screen,
plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position),
plane_targets: self.prefs.perspective_widget.targets(),
precise_cursors: self.precise_cursors(),
precise_cursors: view.precise,
global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()),
interaction_doc: st.interaction.as_ref().map(|it| &*it.doc),
};
@@ -519,6 +523,13 @@ impl Session {
}
}
/// Runs `f` with the context the tools read for the active document seen through `view`, for code
/// outside the engine that draws on the tools' geometry (the canvas's selection widgets).
/// `R::default()` with no document open.
pub fn with_tool_context<R: Default>(&mut self, view: ViewInfo, f: impl FnOnce(&ToolContext) -> R) -> R {
self.with_tool_cx(view, |_, cx| f(cx))
}
/// The error of a tool that panicked in the last [`Self::with_tool_cx`] call, if any.
fn take_tool_panic(&mut self) -> Result<()> {
self.tool_panic.take().map_or(Ok(()), Err)
@@ -1094,30 +1105,6 @@ impl Session {
r
}
/// Would [`Session::tool_text`] insert `text` unchanged (no control-character filtering,
/// newline normalization or document formatting such as Typographer's Quotes)? An IME commit
/// the application rewrites is an application edit, not an accepted IME insertion.
pub fn tool_text_is_verbatim(&mut self, text: &str, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.text_input_is_verbatim(cx, text))
}
/// [`Session::tool_text_is_verbatim`] for text typed on the keyboard, as
/// [`Session::tool_typed_text`] would insert it: a lone typed `”` that Typographer's Quotes
/// turns into an opening quote is not verbatim.
pub fn tool_typed_text_is_verbatim(&mut self, text: &str, view: ViewInfo) -> bool {
self.keyboard_text = true;
let v = self.tool_text_is_verbatim(text, view);
self.keyboard_text = false;
v
}
/// Does the active tool's open typing session still match the document? An IME commit after
/// an external edit starts a fresh session (an application-side reset), so its receipt must
/// not be accepted as an unchanged IME insertion.
pub fn tool_ime_session_matches(&mut self, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.ime_session_matches_document(cx))
}
/// Whether the active tool currently owns keyboard text input, as the Type tool does while editing.
pub fn tool_wants_text(&self) -> bool {
self.tool.wants_text()
@@ -1154,14 +1141,6 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.ime_target(cx))
}
/// The committed logical text around the IME cursor (UTF-8 byte offsets), with any pre-edit
/// removed and at most `max_bytes` bytes copied: the app's outgoing surrounding-text producer
/// (egui E21b) reads it. An explicit [`ImeSurrounding::Unavailable`] carries the narrow reason
/// (no editor, invalid offsets, or a selection wider than the limit).
pub fn tool_ime_surrounding(&mut self, max_bytes: usize, view: ViewInfo) -> ImeSurrounding {
self.with_tool_cx(view, |t, cx| t.ime_surrounding(cx, max_bytes))
}
/// Is the active tool showing uncommitted IME text?
pub fn tool_composing(&self) -> bool {
self.tool.composing()
@@ -1322,13 +1301,12 @@ impl Session {
v
}
/// The pointer the active tool shows at `p` (General › Use Precise Cursors, or Caps Lock while
/// it is on, makes the drawing tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None };
let c = match lent {
match lent {
Some(id) => {
let lent = self.make_tool(id);
let own = std::mem::replace(&mut self.tool, lent);
@@ -1337,13 +1315,7 @@ impl Session {
c
}
None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)),
};
if self.precise_cursors() { c.precise() } else { c }
}
/// General › Use Precise Cursors is on, or Caps Lock is.
fn precise_cursors(&self) -> bool {
self.prefs.use_precise_cursors || self.caps_lock
}
}
pub fn tool_options(&self) -> Value {