Merge main into feat/outline-object-image-alpha

This commit is contained in:
dotCooCoo
2026-11-12 06:33:36 -08:00
128 changed files with 4396 additions and 711 deletions
+30 -8
View File
@@ -1,7 +1,8 @@
//! File → File Info (`file.info`): the document title and its descriptive metadata (author,
//! description, keywords, rating, copyright), with the read-only created and modified dates. The
//! SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or `.ai` opens with the File Info
//! it gives ([`read_pdf`]).
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
use serde_json::{Map, Value, json};
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
@@ -22,7 +23,7 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
pub(crate) fn info_json(d: &Document) -> Value {
let m = &d.metadata;
json!({
"title": d.title,
"title": d.info_title(),
"author": m.author,
"authorTitle": m.author_title,
"description": m.description,
@@ -48,14 +49,22 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
_ => return Err(bad(C, "params must be an object")),
};
let d = &s.doc()?.doc;
let (mut title, mut m) = (d.title.clone(), d.metadata.clone());
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
for (k, v) in o {
apply(&mut title, &mut m, k, v)?;
}
let d = &s.doc()?.doc;
if title != d.title || m != d.metadata {
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
// offer it where the document has no file), and replaces the one its file gave.
let retitled = title != d.info_title();
if retitled {
m.title = None;
}
if retitled || m != d.metadata {
s.edit("File Info", |d, _| {
d.title = title;
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
@@ -64,8 +73,8 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
}
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
/// field that `file.info` would take (a value it refuses is left out), and the created and
/// modified dates.
/// field that `file.info` would take (a value it refuses is left out), its title ([`imported_title`])
/// as the File Info title, and the created and modified dates.
pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
@@ -83,6 +92,7 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
let _ = apply(&mut title, m, k, &v);
}
}
m.title = f.title.as_deref().and_then(imported_title);
m.created = f.created.or(m.created);
m.modified = f.modified.or(m.modified);
}
@@ -141,6 +151,18 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> {
Ok(s.to_string())
}
/// The File Info title `raw`, read from a file, makes: runs of white space (line breaks too)
/// become single spaces, other control characters are dropped, at most [`MAX_TEXT`] characters
/// are kept, as `file.info` takes a title. `None` when nothing is left, or when it is the
/// Untitled-N name New gives (what a document that never had a title writes to its files).
pub(crate) fn imported_title(raw: &str) -> Option<String> {
let words: Vec<String> =
raw.split_whitespace().map(|w| w.chars().filter(|c| !c.is_control()).collect::<String>()).filter(|w| !w.is_empty()).collect();
let title: String = words.join(" ").chars().take(MAX_TEXT).collect();
let title = title.trim_end();
super::fileio::is_own_title(title).then(|| title.to_string())
}
/// Keywords from a list or a comma- or semicolon-separated string: trimmed, each once (ignoring
/// case), empty ones dropped.
fn keywords(v: &Value) -> Result<Vec<String>> {
+1
View File
@@ -143,6 +143,7 @@ pub(crate) use export_names::{
artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return,
};
use export_names::{distinct_names_by, write_encoded};
pub(crate) use formats::is_own_title;
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
pub use formats::{
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
+1 -1
View File
@@ -592,7 +592,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?;
// File Info as PNG text chunks.
let bytes = if matches!(format, RasterFormat::Png | RasterFormat::Png8) {
vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(&doc.title))
vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(doc.info_title()))
} else {
bytes
};
+1 -1
View File
@@ -370,7 +370,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
let o = EpsOptions {
region,
origin,
title: doc.title.clone(),
title: doc.info_title().to_owned(),
created,
native: Some(native(&editing, if whole { None } else { board }, set.include_linked)),
..set.eps.clone()
+8 -1
View File
@@ -930,13 +930,20 @@ pub(crate) fn import_name(base: &str, taken: impl Fn(&str) -> bool) -> String {
/// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep
/// the stored title.
pub fn has_own_title(doc: &vectorcraft_doc::Document) -> bool {
!doc.title.trim().is_empty() && !doc.title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
is_own_title(doc.info_title())
}
/// Is `title` one a person or a file gave, not blank and not the Untitled-N name New gives?
pub(crate) fn is_own_title(title: &str) -> bool {
!title.trim().is_empty() && !title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
}
pub fn titled_for_export(doc: &vectorcraft_doc::Document, path: Option<&str>, format: &str) -> Option<vectorcraft_doc::Document> {
let path = path.filter(|_| !has_own_title(doc) && !matches!(format, "vectorcraft" | "template" | "ai"))?;
let mut d = doc.clone();
d.title = file_stem(path);
// A File Info title that is no title of its own (blank, or an Untitled-N name) would hide it.
d.metadata.title = None;
Some(d)
}
+1 -1
View File
@@ -145,7 +145,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
}
}
}
let o = vectorcraft_eps::LegacyAiOptions { title: doc.title.clone(), created, hidden, outline_text };
let o = vectorcraft_eps::LegacyAiOptions { title: doc.info_title().to_owned(), created, hidden, outline_text };
let out = vectorcraft_eps::export_legacy_ai(&d, &o).map_err(|e| bad(cmd, e))?;
for w in placed.iter().chain(&out.warnings) {
note(&mut enc.warnings, w);
+12 -1
View File
@@ -7,6 +7,7 @@ use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_geom::Affine;
use vectorcraft_render::effects::pixel::LoadedTexture;
use super::super::fileinfo::imported_title;
use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param};
use super::pdfimport::LoadOptions;
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name};
@@ -550,6 +551,15 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) {
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays);
}
// The title the file gives itself (an SVG's `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title`
// or Info `Title`, which the readers put in File Info) is separate from the document's name.
// Restored File Info is preserved exactly; newly imported SVG candidates and a restored
// document's legacy name fallback are cleaned as imported text. The name stays the file's (#3626).
if !restored && matches!(format.id, "svg" | "svgz") {
doc.metadata.title = doc.metadata.title.as_deref().and_then(imported_title);
}
let held = restored.then_some(doc.title.as_str()).filter(|t| *t != title);
doc.metadata.title = doc.metadata.title.or_else(|| held.and_then(imported_title));
// Imports are named after the file; a native document keeps its own title (the tab shows the
// file name once it has a path).
if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() {
@@ -678,6 +688,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
if template {
doc.template = false;
doc.title = s.next_untitled();
doc.metadata.title = None;
}
// A .ai (or .ait) another app wrote carries no open Layers rows we read: all of them start
// closed, its top-level layers as its groups (#1475). Ours carry their own.
@@ -711,7 +722,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
st.import_losses = losses;
st.links_from = read_from;
let opened = &s.documents()[index];
let (title, file_info_title) = (opened.title(), opened.doc.title.clone());
let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string());
Ok(super::merge(
json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }),
links.to_json(),
+1 -1
View File
@@ -731,7 +731,7 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
// With the artboards' background colors, as the pages draw them.
let art = super::export::with_artboard_fills(art, &params, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?;
let o = vectorcraft_eps::AiEditingOptions {
title: doc.title.clone(),
title: doc.info_title().to_owned(),
created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time),
};
let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?;
+11 -1
View File
@@ -183,6 +183,16 @@ fn a_picked_folder_inside_other_apps_folders_is_refused() {
assert!(p.error().is_some_and(|e| e.ends_with("is not a folder")), "{p:?}");
let p = search(&root, "missing", Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.starts_with(&root.join("missing").display().to_string())), "{p:?}");
// Each failure has the same reason without the folder's path.
let briefs = [
("missing", "the folder can't be read"),
("file.ttf", "the path isn't a folder"),
("refused", "VectorCraft doesn't search other apps' or the system's folders"),
("Users/Public/x", "VectorCraft doesn't search the Shared or Public folder in Users"),
];
for (picked, why) in briefs {
assert_eq!(search(&root, picked, Limits::default(), 1, &[]).failure(), Some(why), "{picked}");
}
}
#[test]
@@ -362,7 +372,7 @@ fn a_picked_folder_that_cant_be_listed_fails_the_search() {
let p = search(&root, "locked", Limits::default(), 2, &["y.ttf"]);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
if enforced {
assert!(matches!(&p.end, Some(End::Failed(e)) if e.contains("locked")), "{p:?}");
assert!(matches!(&p.end, Some(End::Failed(e, "the folder can't be listed")) if e.contains("locked")), "{p:?}");
} else {
assert_eq!(found(&root, &p), ["locked/y.ttf"]);
}
+51 -15
View File
@@ -23,6 +23,13 @@ const CHECK_EVERY: u64 = 1024;
/// How a search ends when every walker thread stopped on a bug.
const INTERNAL: &str = "every search thread stopped on an internal error (please report this bug)";
/// Why a search couldn't start, without the folder's path ([`Progress::failure`]).
const UNREADABLE: &str = "the folder can't be read";
const NOT_A_FOLDER: &str = "the path isn't a folder";
const SHARED: &str = "VectorCraft doesn't search the Shared or Public folder in Users";
const APPS: &str = "VectorCraft doesn't search other apps' or the system's folders";
const UNLISTED: &str = "the folder can't be listed";
/// What a search looks for.
pub trait Visitor: Send + Sync {
/// Whether the regular file named `name` is to be read: asked of the files a folder lists until
@@ -77,8 +84,9 @@ pub enum End {
/// reached their [`Limits`]. Folders deeper than [`Limits::depth`] are skipped and an item
/// keeps at most [`Limits::per_item`] files, without ending the search.
Limit,
/// It couldn't start: the folder can't be read, isn't a folder or isn't one to search.
Failed(String),
/// It couldn't start: the folder can't be read, isn't a folder or isn't one to search. Why,
/// and the same without the folder's path.
Failed(String, &'static str),
}
/// Where a search stands ([`Search::progress`]).
@@ -114,7 +122,7 @@ impl Progress {
None => "searching",
Some(End::Done | End::Found) => "done",
Some(End::Stopped | End::Time | End::Limit) => "stopped",
Some(End::Failed(_)) => "failed",
Some(End::Failed(..)) => "failed",
}
}
@@ -131,10 +139,38 @@ impl Progress {
/// Why a failed search failed.
pub fn error(&self) -> Option<&str> {
match &self.end {
Some(End::Failed(e)) => Some(e),
Some(End::Failed(e, _)) => Some(e),
_ => None,
}
}
/// Why a failed search failed, without the folder's path.
pub fn failure(&self) -> Option<&'static str> {
match &self.end {
Some(End::Failed(_, why)) => Some(why),
_ => None,
}
}
/// Keep what the caller asking now may read under its read roots ([`crate::file_access::current`]),
/// for a reply to it: the files found inside them. Returns the folder searched (`given` until a
/// walker checked it) and why the search failed, when that folder lies inside them too;
/// otherwise no folder and why without its path ([`Self::failure`]). Without read roots in
/// force, everything is kept.
pub fn keep_readable(&mut self, given: &str) -> (Option<String>, Option<String>) {
let folder = if self.folder.as_os_str().is_empty() { given.to_string() } else { self.folder.to_string_lossy().into_owned() };
if crate::file_access::current().is_none() {
return (Some(folder), self.error().map(str::to_string));
}
// A path that isn't valid text is never shown: its lossy form names another file.
let readable = |p: &Path| p.to_str().is_some_and(|p| crate::file_access::check_read(p).is_ok());
self.hits.retain(|(path, _)| readable(path));
if readable(Path::new(given)) && (self.folder.as_os_str().is_empty() || readable(&self.folder)) {
(Some(folder), self.error().map(str::to_string))
} else {
(None, self.failure().map(str::to_string))
}
}
}
/// Walker threads shared out among searches: all of them together run at most `cap` threads.
@@ -306,7 +342,7 @@ pub(crate) fn start_in(
return Err("the search couldn't start: try again in a moment".into());
}
if w.alive == 0 && w.end.is_none() {
shared.finish(&mut w, End::Failed(INTERNAL.into()));
shared.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL));
}
}
Ok(Search { shared })
@@ -401,13 +437,13 @@ impl Shared {
fn prepare(&self, root: &Path) {
let rules = self.rules.get_or_init(|| self.given.clone().unwrap_or_else(Rules::system));
let path = root.display();
let checked = match std::fs::canonicalize(root) {
Err(e) => Err(format!("{path}: {e}")),
Ok(folder) if !folder.is_dir() => Err(format!("{path} is not a folder")),
let (checked, brief) = match std::fs::canonicalize(root) {
Err(e) => (Err(format!("{path}: {e}")), UNREADABLE),
Ok(folder) if !folder.is_dir() => (Err(format!("{path} is not a folder")), NOT_A_FOLDER),
Ok(folder) => match rules.refusal(&folder) {
None => Ok(folder),
Some(Refusal::Shared) => Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")),
Some(Refusal::Apps) => Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")),
None => (Ok(folder), INTERNAL),
Some(Refusal::Shared) => (Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")), SHARED),
Some(Refusal::Apps) => (Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")), APPS),
},
};
let mut w = self.lock();
@@ -416,7 +452,7 @@ impl Shared {
w.folder = folder.clone();
w.stack.push((folder, 0));
}
Err(e) => self.finish(&mut w, End::Failed(e)),
Err(e) => self.finish(&mut w, End::Failed(e, brief)),
}
}
@@ -430,7 +466,7 @@ impl Shared {
let mut w = self.lock();
// The picked folder itself: the search can't run, and says why.
if depth == 0 {
self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display())));
self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display()), UNLISTED));
} else {
w.unreadable += 1;
w.folders += 1;
@@ -610,7 +646,7 @@ fn walker(s: &Shared) {
if done.is_err() {
let mut w = s.lock();
match job {
Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into())),
Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL)),
Job::List(..) => w.unreadable += 1,
}
}
@@ -640,7 +676,7 @@ impl Drop for Alive {
let mut w = self.0.lock();
w.alive = w.alive.saturating_sub(1);
if w.alive == 0 && w.end.is_none() {
self.0.finish(&mut w, End::Failed(INTERNAL.into()));
self.0.finish(&mut w, End::Failed(INTERNAL.into(), INTERNAL));
}
drop(w);
self.0.pool.release(1);
+18 -10
View File
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Font Files",
[],
None,
"{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
"{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links). With automation read roots, a reply leaves out the files found outside the caller's roots, and the folder when it is outside them (error then gives the reason without the path); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
always,
find
),
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Font Files",
[],
None,
"{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: the names Name.otf, Name 2.otf … Name 99.otf are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is kept; then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}",
"{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: the names Name.otf, Name 2.otf … Name 99.otf are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is kept; then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install. With automation read roots, folder is null when the Fonts folder is outside them, and a to or file path outside them is given as its file name; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}",
always,
add
),
@@ -275,7 +275,9 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
/// Where the session's last search stands (`text.findFontFiles` without `folder`).
fn state(s: &Session) -> Value {
let Some(f) = &s.font_search else { return json!({ "state": "idle", "fonts": [] }) };
let p = f.search.progress();
let mut p = f.search.progress();
// Only what the caller asking now may read: a search another caller started can hold more.
let (folder, error) = p.keep_readable(&f.folder);
let mut files: Vec<Vec<String>> = vec![vec![]; f.fonts.len()];
for (path, items) in &p.hits {
for i in items {
@@ -293,16 +295,18 @@ fn state(s: &Session) -> Value {
json!({ "family": font.family, "style": font.style, "status": font.status.as_str(), "files": files })
})
.collect();
let folder = if p.folder.as_os_str().is_empty() { f.folder.clone() } else { p.folder.to_string_lossy().into_owned() };
let mut out = json!({
"id": f.id, "state": p.state(), "folder": folder, "fonts": fonts,
"id": f.id, "state": p.state(), "fonts": fonts,
"searched": { "folders": p.folders, "files": p.files, "fontFiles": p.read },
"skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0,
});
if let Some(folder) = folder {
out["folder"] = json!(folder);
}
if let Some(why) = p.stopped() {
out["stopped"] = json!(why);
}
if let Some(e) = p.error() {
if let Some(e) = error {
out["error"] = json!(e);
}
out
@@ -348,12 +352,16 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// VectorCraft's own Fonts folder: no automation root applies to it.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir.to_string_lossy()))?;
let report = copy_into(&files, dir);
let pairs = |v: &[(PathBuf, PathBuf)]| {
v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": to.to_string_lossy() })).collect::<Vec<_>>()
// The caller sees the Fonts folder and the copies in it only where its read roots reach.
let readable = |p: &Path| crate::file_access::current().is_none() || p.to_str().is_some_and(|p| crate::file_access::check_read(p).is_ok());
let shown = |p: &Path| -> String {
let shown = if readable(p) { Some(p.as_os_str()) } else { p.file_name() };
shown.map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
};
let pairs = |v: &[(PathBuf, PathBuf)]| v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": shown(to) })).collect::<Vec<_>>();
let mut out = json!({
"folder": dir.to_string_lossy(), "copied": pairs(&report.copied), "kept": pairs(&report.kept),
"skipped": report.skipped.iter().map(|(file, why)| json!({ "file": file.to_string_lossy(), "reason": why })).collect::<Vec<_>>(),
"folder": readable(dir).then(|| dir.to_string_lossy()), "copied": pairs(&report.copied), "kept": pairs(&report.kept),
"skipped": report.skipped.iter().map(|(file, why)| json!({ "file": shown(file), "reason": why })).collect::<Vec<_>>(),
});
if !report.copied.is_empty() || !report.kept.is_empty() {
// The fonts are cataloged and type set in them redraws, as Refresh Font List does it.
+16 -7
View File
@@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Find Linked Files",
[],
None,
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits; none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
"{folder?: an absolute path, ids?: [image or placed document ids] (default: the active document's missing links), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders, on separate threads, for files with the names of the linked files (in any letter case), and answer at once with the search's state (searching while it runs); without folder: the last search's state, with the files found so far. Each linked file's files come best first: same (the size and hash saved with the link), size (the saved size, where there is no saved hash or the file is larger than 1 GiB), then name. Within each kind, a file whose name has the link's letter case comes first. Then each file's folder names are compared with the saved path's, from the innermost outward up to the first one that differs, and a file with more matching names comes first; files that still tie are listed by path. Before the comparison, the saved path's parent-folder steps (.., or the empty components of a classic Mac :: run) are resolved, and . components in a slash path are skipped. A search looks for at most 1000 linked files and keeps the first 10 files of each one's name, and up to 10 that are the same file; it ends once every linked file has its same file, and searches only the folders text.findFontFiles may search, with the same maxSeconds, depth and count limits. With automation read roots, a reply leaves out the files found outside the caller's roots, a link's path outside them, and the folder when it is outside them (error then gives the reason without the path); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, links: [{name, path?, ids, files: [{path, size, match: same|size|name, caseDiffers?: true}]}], searched?: {folders, files, read}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
always,
find
)]
@@ -52,6 +52,8 @@ pub(crate) struct LinkSearch {
pub(crate) id: u64,
/// The folder as given.
pub(crate) folder: String,
/// The path of the document the links were taken from, which a relative link path starts from.
pub(crate) doc: Option<String>,
pub(crate) links: Vec<Sought>,
/// The size of each file read, by the path the search reports ([`LinkFiles::sizes`]).
pub(crate) sizes: Arc<Mutex<HashMap<PathBuf, u64>>>,
@@ -163,6 +165,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
if links.is_empty() {
return Err(bad(C, if ids.is_some() { "these objects show no linked files" } else { "no linked files are missing" }));
}
let doc = super::links::LinkBase::of(st).doc.map(str::to_string);
// A new search stops the last one.
s.link_search = None;
let threads = s.search_threads.unwrap_or_else(findfiles::threads);
@@ -171,7 +174,7 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
let visitor = Arc::new(LinkFiles::new(&links, sizes.clone()));
let search =
findfiles::start(PathBuf::from(&folder), s.search_rules.clone(), limits, threads, 2 * links.len(), visitor).map_err(EngineError::Other)?;
s.link_search = Some(LinkSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, links, sizes, search });
s.link_search = Some(LinkSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, doc, links, sizes, search });
Ok(state(s))
}
@@ -209,7 +212,9 @@ fn shared_folders(saved: &str, found: &Path) -> usize {
/// Where the session's last search stands (`links.findFiles` without `folder`).
fn state(s: &Session) -> Value {
let Some(l) = &s.link_search else { return json!({ "state": "idle", "links": [] }) };
let p = l.search.progress();
let mut p = l.search.progress();
// Only what the caller asking now may read: a search another caller started can hold more.
let (folder, error) = p.keep_readable(&l.folder);
let n = l.links.len();
let sizes = lock(&l.sizes).clone();
// Per linked file: the files found, each with whether it is the same file.
@@ -267,19 +272,23 @@ fn state(s: &Session) -> Value {
f
})
.collect();
json!({ "name": link.name, "path": link.path, "ids": link.ids, "files": files })
let mut row = json!({ "name": link.name, "ids": link.ids, "files": files });
super::links::note_path(&mut row, "path", &link.path, l.doc.as_deref());
row
})
.collect();
let folder = if p.folder.as_os_str().is_empty() { l.folder.clone() } else { p.folder.to_string_lossy().into_owned() };
let mut out = json!({
"id": l.id, "state": p.state(), "folder": folder, "links": links,
"id": l.id, "state": p.state(), "links": links,
"searched": { "folders": p.folders, "files": p.files, "read": p.read },
"skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0,
});
if let Some(folder) = folder {
out["folder"] = json!(folder);
}
if let Some(why) = p.stopped() {
out["stopped"] = json!(why);
}
if let Some(e) = p.error() {
if let Some(e) = error {
out["error"] = json!(e);
}
out
+2 -2
View File
@@ -898,12 +898,12 @@ fn rows<'a>(gs: impl Iterator<Item = &'a Group>, doc_path: Option<&str>) -> Vec<
/// May a reply to the caller asking now carry the link path `path` (of the document saved at
/// `doc_path`)? Always without read roots in force; with them, only when the file it names (a
/// relative path taken from the document's folder) lies inside them.
fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
crate::file_access::current().is_none() || fileio::document_path(path, doc_path).is_ok_and(|p| crate::file_access::check_read(&p).is_ok())
}
/// `row[key] = path` when [`path_shown`] says so; otherwise `row` has no `key`.
fn note_path(row: &mut Value, key: &str, path: &str, doc_path: Option<&str>) {
pub(crate) fn note_path(row: &mut Value, key: &str, path: &str, doc_path: Option<&str>) {
if path_shown(path, doc_path) {
row[key] = json!(path);
} else if let Some(o) = row.as_object_mut() {
+4 -4
View File
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make with Warp…",
["Object", "Envelope Distort"],
Some("Cmd+Alt+Shift+W"),
"{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}",
"{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v, version?: 0|1 (1: each style bends the bounds as one Bézier patch; 0: VectorCraft's earlier map)} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}",
has_selection,
env_make_warp
),
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset with Warp…",
["Object", "Envelope Distort"],
None,
"{style?, bend?, h?, v?, horizontal? | orientation? (as makeWithWarp; unset: the envelope's current warp, else arc 50 %), horizontalDistortion?: as h, verticalDistortion?: as v} make the selected envelopes warp envelopes, keeping their content",
"{style?, bend?, h?, v?, horizontal? | orientation? (as makeWithWarp; unset: the envelope's current warp, else arc 50 %), horizontalDistortion?: as h, verticalDistortion?: as v, version?: as makeWithWarp (unset: a warp envelope's own, else 1)} make the selected envelopes warp envelopes, keeping their content",
has_envelope,
env_reset_warp
),
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Envelope Info",
[],
None,
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
has_doc,
env_info
),
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Envelope Options…",
["Object", "Envelope Distort"],
None,
"{fidelity?: 0..100, antiAlias?: bool, preserveShape?: clippingMask|transparency, distortAppearance?: bool, distortLinearGradients?: bool, distortPatternFills?: bool (the last two work with distortAppearance; on an envelope with boundsMargin, distortAppearance also switches the content between the box with the margins and its geometric box), style?, bend?, h?, v?, horizontal? (warp envelopes), horizontalDistortion?: as h, verticalDistortion?: as v, orientation?: horizontal|vertical} set the selected envelopes' options; with no envelope selected, the options new envelopes get (see object.envelope.info)",
"{fidelity?: 0..100, antiAlias?: bool, preserveShape?: clippingMask|transparency, distortAppearance?: bool, distortLinearGradients?: bool, distortPatternFills?: bool (the last two work with distortAppearance; on an envelope with boundsMargin, distortAppearance also switches the content between the box with the margins and its geometric box), style?, bend?, h?, v?, horizontal? (warp envelopes), horizontalDistortion?: as h, verticalDistortion?: as v, orientation?: horizontal|vertical, version?: 0|1 (warp envelopes' map, as makeWithWarp)} set the selected envelopes' options; with no envelope selected, the options new envelopes get (see object.envelope.info)",
has_doc,
env_options
),
+11 -6
View File
@@ -13,9 +13,14 @@ const WARP_NUMBERS: &[&str] = &["bend", "h", "v", "horizontalDistortion", "verti
fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<EnvelopeKind> {
check_numbers(p, WARP_NUMBERS, cmd)?;
let (mut style, mut bend, mut h, mut v, mut horizontal) = ("arc".to_string(), 50.0, 0.0, 0.0, true);
if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0 }) = cur {
(style, bend, h, v, horizontal) = (s0.clone(), *b0, *h0, *v0, *z0);
// A new warp takes its style's Bézier net; an edited one keeps the map it has unless `version`
// names one.
let (mut style, mut bend, mut h, mut v, mut horizontal, mut version) = ("arc".to_string(), 50.0, 0.0, 0.0, true, live::WARP_NET);
if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0, version: n0 }) = cur {
(style, bend, h, v, horizontal, version) = (s0.clone(), *b0, *h0, *v0, *z0, *n0);
}
if let Some(n) = p.get("version") {
version = live::warp_version(n).ok_or_else(|| bad(cmd, format!("`version` must be 0 or {}", live::WARP_NET)))?;
}
if let Some(s) = text_param(p, "style", cmd)? {
let s = s.strip_prefix("warp.").unwrap_or(s);
@@ -32,7 +37,7 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop
Some(o) => o == "horizontal",
None => given,
};
Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal })
Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal, version })
}
/// The options and fidelity new envelopes get (Envelope Options with no envelope selected).
@@ -206,8 +211,8 @@ pub(super) fn env_info(s: &mut Session, _: &Value) -> Result<Value> {
return Ok(envelope_options_json(json!({ "id": null }), &options, fidelity));
};
let v = match &**kind {
EnvelopeKind::Warp { style, bend, h, v, horizontal } => {
json!({"type": "warp", "style": style, "bend": bend, "h": h, "v": v, "horizontal": horizontal})
EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => {
json!({"type": "warp", "style": style, "bend": bend, "h": h, "v": v, "horizontal": horizontal, "version": version})
}
EnvelopeKind::Mesh { rows, cols, .. } => json!({"type": "mesh", "rows": rows, "cols": cols}),
EnvelopeKind::TopObject { .. } => json!({"type": "topObject"}),
+8
View File
@@ -317,6 +317,14 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") {
return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`"));
}
// A Warp's map is one this build draws: 0, the earlier map, or its style's Bézier net.
let newest = vectorcraft_render::effects::WARP_NET;
if effect.starts_with("warp.")
&& let Some(v) = given.get("version")
&& vectorcraft_render::effects::warp_version(v).is_none()
{
return Err(bad(id, format!("`version` must be 0 or {newest}")));
}
check_effect_color(id, effect, params)?;
check_effect_channel(id, effect, params)
}
+4 -2
View File
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Image Info",
[],
None,
"{id?} an image object (default: the one selected) → {id, name, linked, link, colorMode: RGB|Grayscale|CMYK, pixelWidth, pixelHeight, ppi: [x, y] at its placed size, width, height}",
"{id?} an image object (default: the one selected) → {id, name, linked, link (the linked file's path; null when embedded, or when automation read roots are in force and the file is outside them), colorMode: RGB|Grayscale|CMYK, pixelWidth, pixelHeight, ppi: [x, y] at its placed size, width, height}",
has_doc,
image_info
),
@@ -891,11 +891,13 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
let [a, b, c, d, ..] = im.xf.as_coeffs();
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
let size = n.geometric_bounds().unwrap_or_default();
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
let doc_path = super::links::LinkBase::of(st).doc;
Ok(json!({
"id": id.0,
"name": n.display_name(),
"linked": im.link.is_some(),
"link": im.link.as_ref().map(|l| &l.path),
"link": im.link.as_ref().map(|l| &l.path).filter(|path| super::links::path_shown(path, doc_path)),
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
"pixelWidth": im.width,
"pixelHeight": im.height,
@@ -645,6 +645,8 @@ pub(super) const ALLOWED: &[&str] = &[
"type.opticalMarginAlignment",
"type.orientation.horizontal",
"type.orientation.vertical",
"type.pathCenter.bottom",
"type.pathCenter.top",
"type.pathOptions",
"type.resetHorizontalScale",
"type.resetTracking",
+148
View File
@@ -60,6 +60,24 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
path_options
),
cmd!(
"type.pathCenter.top",
"Center on Top",
["Type", "Type on a Path"],
None,
"{ids?|id?} slide the selected type on a closed path along it so that the middle of the span between its start and end brackets lands on the path's topmost point as the object is drawn (after its transform, so a rotated, scaled or skewed path is measured as it appears; on a level stretch such as a rectangle's top edge, its middle; with several separate topmost points, the middle of the shortest part of the path that holds them all), keeping the span's length (a full turn stays a full turn), and set the first paragraph's alignment to Center unless it is Center or Justify Center, so the type is centered there. Point type and area type in the selection are left as they are. Type on an open or compound path, type in a thread, and type on a path with no length or no height are refused with an error that names them, and nothing changes. When every object is already centered there, nothing changes and no undo step is recorded → {ids, start, end} (the first object's brackets)",
has_closed_path_type,
path_center_top
),
cmd!(
"type.pathCenter.bottom",
"Center on Bottom",
["Type", "Type on a Path"],
None,
"{ids?|id?} as type.pathCenter.top, on the path's bottommost point as drawn. The type is not flipped: on the bottom of a path that runs clockwise it reads upside down until Type on a Path Options › Flip turns it → {ids, start, end} (the first object's brackets)",
has_closed_path_type,
path_center_bottom
),
cmd!(
"type.dynamicText",
"Dynamic Text",
@@ -430,6 +448,136 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
Ok(ids_json(&ids))
}
/// Whether type on a path `t` runs along one closed path (no open or compound path).
fn on_one_closed_path(t: &TextObject) -> bool {
matches!(&t.kind, TextKind::OnPath { path, .. } if path.subpaths.len() == 1 && path.is_closed())
}
/// Why `type.pathCenter.top` and `.bottom` refuse type on a path `ids`: those on an open or
/// compound path, then those in a thread; None when they take every one.
fn path_center_refusal(d: &Document, ids: &[NodeId]) -> Option<String> {
let open = ids.iter().filter(|id| !path_text(d.node(**id)).is_some_and(on_one_closed_path)).map(|id| id.0.to_string()).collect::<Vec<_>>();
if !open.is_empty() {
let open = open.join(", ");
return Some(format!("type on an open or compound path cannot be centered on its top or bottom: {open}"));
}
let frames = threaded_ids(d, ids);
(!frames.is_empty()).then(|| format!("type on a path in a thread cannot be centered on its top or bottom: {frames}"))
}
/// `type.pathCenter.top` and `.bottom` are enabled for a selection holding type on a path, all of
/// it on one closed path and none of it in a thread.
fn has_closed_path_type(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let d = &st.doc;
let selected: Vec<NodeId> = st.selection.objects.to_vec();
let paths: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| path_text(d.node(*id)).is_some()).collect();
if paths.is_empty() {
return Err("select type on a closed path".into());
}
path_center_refusal(d, &paths).map_or(Ok(()), Err)
}
/// The brackets that center type on a path `t` on its path's topmost point (`bottom`: its
/// bottommost) as `t.xf` draws it, its span keeping its length; None for a path with no length or
/// no height.
fn centered_brackets(t: &TextObject, bottom: bool) -> Option<(f64, Option<f64>)> {
let TextKind::OnPath { path, end, .. } = &t.kind else { return None };
let (from, to) = t.kind.path_span()?;
let arc = vectorcraft_geom::ArcPath::new(path);
if arc.is_empty() {
return None;
}
let flip = if bottom { Affine::FLIP_Y } else { Affine::IDENTITY };
let middle = arc.topmost(flip * t.xf)? / arc.len();
let run = to - from;
let start = (middle - run * 0.5).rem_euclid(1.0).clamp(0.0, 1.0);
// Without an end bracket the type runs once round; a full turn's end stays on its start.
let end = end.map(|_| if run >= 1.0 - 1e-12 { start } else { (start + run).rem_euclid(1.0).clamp(0.0, 1.0) });
Some((start, end))
}
/// Whether brackets `a` and `b`, fractions of a closed path's length, are at one place within
/// rounding (0 and 1 are one place).
fn same_bracket(a: f64, b: f64) -> bool {
let d = (a - b).rem_euclid(1.0);
d.min(1.0 - d) <= 1e-9
}
fn path_center_top(s: &mut Session, p: &Value) -> Result<Value> {
path_center(s, p, false)
}
fn path_center_bottom(s: &mut Session, p: &Value) -> Result<Value> {
path_center(s, p, true)
}
/// Type › Type on a Path › Center on Top and Center on Bottom: slide the selected type on closed
/// paths along them so the middle of each span lands on the path's top (`bottom`: its bottom) as
/// drawn, and center the first paragraph, in one undo step; none when nothing changes.
fn path_center(s: &mut Session, p: &Value, bottom: bool) -> Result<Value> {
let c = if bottom { "type.pathCenter.bottom" } else { "type.pathCenter.top" };
let centered = |j: Justify| matches!(j, Justify::Center | Justify::JustifyCenter);
// Each object the command changes, with its new brackets when they move and whether its first
// paragraph is set to Center.
let (ids, changes) = {
let d = &s.doc()?.doc;
let ids: Vec<NodeId> = texts(s, p, c)?.into_iter().filter(|i| path_text(d.node(*i)).is_some()).collect();
if ids.is_empty() {
return Err(bad(c, "select type on a closed path"));
}
if let Some(why) = path_center_refusal(d, &ids) {
return Err(bad(c, why));
}
let (mut changes, mut flat) = (vec![], vec![]);
for id in &ids {
let Some(t) = path_text(d.node(*id)) else { continue };
let TextKind::OnPath { start, end, .. } = &t.kind else { continue };
let Some((to_start, to_end)) = centered_brackets(t, bottom) else {
flat.push(id.0.to_string());
continue;
};
let stays = same_bracket(*start, to_start)
&& match (end, to_end) {
(None, None) => true,
(Some(a), Some(b)) => same_bracket(*a, b),
_ => false,
};
let align = !centered(t.para_at(0).justify);
if !stays || align {
changes.push((*id, (!stays).then_some((to_start, to_end)), align));
}
}
if !flat.is_empty() {
let flat = flat.join(", ");
return Err(bad(c, format!("type on a path with no length or no height cannot be centered: {flat}")));
}
(ids, changes)
};
if !changes.is_empty() {
s.edit(if bottom { "Center on Bottom" } else { "Center on Top" }, |d, _| {
for (id, brackets, align) in &changes {
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
if let (Some(b), TextKind::OnPath { start, end, .. }) = (brackets, &mut t.kind) {
(*start, *end) = *b;
}
if *align {
t.edit_paras(Some(0..1), |para| para.justify = Justify::Center);
}
refresh_bounds(t);
}
Ok(())
})?;
}
let d = &s.doc()?.doc;
let (start, end) = ids.first().and_then(|id| path_text(d.node(*id))).map_or((0.0, None), |t| match &t.kind {
TextKind::OnPath { start, end, .. } => (*start, *end),
_ => (0.0, None),
});
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "start": start, "end": end}))
}
/// The options `type.pathOptions` sets; with none of them given it queries.
const PATH_OPTIONS: [&str; 6] = ["start", "end", "flip", "effect", "alignToPath", "spacing"];
+1 -1
View File
@@ -645,7 +645,7 @@ fn flatten(rgba: &[u8], matte: [u8; 3]) -> impl Iterator<Item = [u8; 3]> + '_ {
/// The File Info text `s.metadata` lets into the files: `(keyword, text)`.
fn metadata(doc: &Document, s: &WebSettings) -> Vec<(&'static str, String)> {
doc.metadata.png_text(&doc.title).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect()
doc.metadata.png_text(doc.info_title()).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect()
}
/// Encode straight RGBA pixels (`w`×`h`) as `s` says; `doc` gives the metadata.
+2 -2
View File
@@ -285,8 +285,8 @@ fn document_base(s: &Session) -> Value {
json!({
"uid": st.uid,
"title": st.title(),
// The File Info title (`file.info`), where `title` comes from the file name once the document has one.
"fileInfoTitle": d.title,
// The File Info title (`file.info`): the title the file gave itself, else the document's name. `title` is the tab's name.
"fileInfoTitle": d.info_title(),
"path": st.path,
"dirty": st.is_dirty(),
"revision": st.revision,
+1
View File
@@ -206,6 +206,7 @@ mod typescale;
mod typeundo;
mod units;
mod variables;
mod warp_images;
mod webexport;
mod widthpoints;
mod widthprofiles;
+34
View File
@@ -147,3 +147,37 @@ fn show_all_hidden_attributes() {
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, id).appearance.has_hidden());
}
/// A Warp applied now takes its style's Bézier net (`version` 1) unless a map is given, an edit
/// keeps the map the effect has (one saved before the version existed keeps the earlier map), and
/// a map this build doesn't draw is refused.
#[test]
fn warps_keep_the_map_their_version_names() {
let (mut s, id) = session_with_rect();
let version = |s: &Session| node(s, id).appearance.effects[0].params.get("version").cloned();
run(&mut s, "effect.apply", json!({"effect": "warp.flag", "params": {"bend": 40}}));
assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET)));
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 20}, "warpStyle": "arc"}));
assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET)));
// As a file saved before the version existed gives it.
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(Value::Object(p)) = doc.node_mut(id).and_then(|n| n.appearance.effects.first_mut()).map(|e| &mut e.params) {
p.remove("version");
}
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 10, "horizontal": 20}}));
assert_eq!(version(&s), None);
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"version": 1}}));
assert_eq!(version(&s), Some(json!(1)));
run(&mut s, "effect.apply", json!({"effect": "warp.arc", "params": {"version": 0}}));
assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0));
// A whole number given as a float is that version.
run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 1.0}}));
assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(1));
run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 0.0}}));
assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0));
for bad in [json!(2), json!(-1), json!(0.5), json!("1")] {
assert!(s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"version": bad}})).is_err(), "{bad}");
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"version": bad}})).is_err(), "{bad}");
}
assert_eq!(node(&s, id).appearance.effects.len(), 2);
}
+47 -2
View File
@@ -123,6 +123,51 @@ fn reset_with_warp_and_mesh_switch_the_kind_and_keep_the_content() {
assert!(s.execute("object.envelope.resetWithMesh", &json!({})).is_err());
}
/// A new warp envelope bends with its style's Bézier net (`version` [`live::WARP_NET`]) and keeps
/// it through Reset with Warp. One saved before the version existed keeps the earlier map when its
/// warp or its options change.
#[test]
fn new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map() {
// The surface point a quarter of the way along the top edge.
let quarter = |s: &Session, e| live::EnvelopeMap::of(&node(s, e)).unwrap().surface_mesh(4, 4, vectorcraft_color::Color::BLACK).points[1].p;
let at = |x, y| vectorcraft_geom::Point::new(x, y);
let mut s = session();
let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40}));
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e));
assert_eq!(s.execute("object.envelope.info", &json!({})).unwrap()["version"], json!(live::WARP_NET));
// Flag moves the top edge 6 × bend × height × u(1 - u)(1 - 2u) down at u: 22.5 at u = 1/4.
assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e));
s.execute("object.envelope.resetWithWarp", &json!({"bend": -40})).unwrap();
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e));
assert!(quarter(&s, e).distance(at(150.0, 77.5)) < 1e-9, "{:?}", quarter(&s, e));
// As a file saved before the version existed gives it.
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(NodeKind::Envelope { kind, .. }) = doc.node_mut(e).map(|n| &mut n.kind)
&& let EnvelopeKind::Warp { version, .. } = &mut **kind
{
*version = 0;
}
s.execute("object.envelope.options", &json!({"fidelity": 75})).unwrap();
s.execute("object.envelope.resetWithWarp", &json!({"bend": 40})).unwrap();
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e));
// The earlier map's flag: half the bend times sin(π x), x = -1/2 here, in half heights.
assert!(quarter(&s, e).distance(at(150.0, 90.0)) < 1e-9, "{:?}", quarter(&s, e));
// `version` moves a warp to a map, and a new warp can take the earlier one.
s.execute("object.envelope.options", &json!({"version": 1.0})).unwrap();
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e));
assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e));
s.execute("object.envelope.resetWithWarp", &json!({"version": 0})).unwrap();
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e));
let (_, old) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40, "version": 0}));
assert!(matches!(kind(&s, old), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, old));
for bad in [json!(2), json!(-1), json!(0.5), json!("1"), json!(null)] {
for cmd in ["object.envelope.makeWithWarp", "object.envelope.resetWithWarp", "object.envelope.options"] {
let r = s.execute(cmd, &json!({"version": bad}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("`version` must be 0 or 1")), "{cmd} {bad}: {r:?}");
}
}
}
#[test]
fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() {
let mut s = session();
@@ -141,9 +186,9 @@ fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() {
let content = node(&s, a);
assert_eq!((content.opacity, content.blend, content.extras().mask.is_some()), (0.4, BlendMode::Multiply, true), "the content keeps the look");
let NodeKind::Mesh(m) = node(&s, ids[1]).kind else { panic!("the warp's shape comes back as a mesh") };
// The mesh follows the arc: its outline reaches below the content's bottom edge at the sides.
// The mesh follows the arc: its top corners swing out past the content's sides and up.
let b = m.outline().bounds().unwrap();
assert!(b.y1 > 201.0, "{b:?}");
assert!(b.x0 < 99.0 && b.x1 > 301.0 && b.y0 < 99.0, "{b:?}");
assert_eq!(s.doc().unwrap().selection.objects, ids);
}
+33 -3
View File
@@ -154,6 +154,35 @@ fn images_bend_as_a_raster_mesh_warp() {
assert_eq!(svg.matches("<image").count(), 1, "the pieces share the image's pixels");
}
#[test]
fn a_colorized_image_keeps_its_color_in_an_envelope() {
let mut s = session();
let img = image::GrayImage::from_pixel(4, 4, image::Luma([0]));
let mut png = vec![];
image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let im = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
let xf = Affine::translate((100.0, 100.0)) * Affine::scale(10.0);
let im =
vectorcraft_doc::ImageObject { key: "gray".into(), width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None };
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [im.0]})).unwrap();
sel(&mut s, &[im]);
arch(&mut s, 80.0, json!({}));
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true);
// The black pixels draw in the fill color, in the bent shape.
let mid = img.pixel(120, 97);
assert!(mid[0] > 200 && mid[1] < 60 && mid[2] < 60, "the middle rose, red: {mid:?}");
let inside = img.pixel(120, 120);
assert!(inside[0] > 200 && inside[1] < 60 && inside[2] < 60, "red inside: {inside:?}");
}
/// A selected embedded 2×2 image, 80×80 pt at (100, 100): a red column left of a blue one.
fn two_color_image(s: &mut Session) -> NodeId {
let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) });
@@ -286,17 +315,18 @@ fn symbols_bend_with_the_envelope() {
let e = arch(&mut s, 60.0, json!({}));
let pts = anchors(&evaluated(&s, e));
assert!(pts.iter().any(|p| p.y < 90.0), "the symbol's art rose in the middle");
// Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art).
// Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art). The
// arch lifts the middle of the 100..200 box by about 51, so (200, 120) is inside it.
let mut r = vectorcraft_render::Renderer::new();
let region = Rect::new(0.0, 0.0, 400.0, 300.0);
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] < 60);
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] < 60);
s.edit("edit symbol", |d, _| {
let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(-10.0, -10.0, -8.0, -8.0)), Default::default());
d.symbols[0].art = Arc::new(art);
Ok(())
})
.unwrap();
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] > 200);
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] > 200);
}
fn strokes(nodes: &[Node]) -> usize {
+188 -1
View File
@@ -161,7 +161,8 @@ fn an_exported_pdf_opens_with_its_file_info() {
assert_eq!(back["description"], "A poster\nfor the fair");
assert_eq!(back["keywords"], json!(["fair", "Poster", "print"]));
assert!(back["created"].as_str().is_some_and(|c| c.ends_with('Z')), "the file's creation date: {}", back["created"]);
assert_eq!(back["title"], "poster.pdf", "the title stays the file name");
assert_eq!(back["title"], "Poster", "File Info shows the title the PDF carries");
assert_eq!(s.doc().unwrap().title(), "poster.pdf", "the document stays named after the file");
assert_eq!(back["copyrightStatus"], "copyrighted");
assert_eq!(back["copyrightNotice"], "(c) 2026 Ada");
assert_eq!(back["copyrightUrl"], "https://example.com/rights");
@@ -277,6 +278,192 @@ fn a_pdf_compatible_ai_opens_with_the_file_info_of_its_xmp_packet() {
assert_eq!(m.copyright_url, "");
}
/// A one-page PDF whose trailer names an information dictionary with the entries `info`, and whose
/// catalog has a metadata stream holding an XMP `dc:title` of `xmp_title`.
fn pdf_titled(info: Option<&str>, xmp_title: Option<&str>) -> Vec<u8> {
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog};
let first = first_extra(1);
let mut objects = vec![];
let mut catalog = String::new();
if let Some(t) = xmp_title {
let xmp = format!(
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\
<dc:title><rdf:Alt><rdf:li xml:lang=\"de\">Zugangswege</rdf:li><rdf:li xml:lang=\"x-default\">{t}</rdf:li></rdf:Alt></dc:title>\
</rdf:Description></rdf:RDF></x:xmpmeta>"
);
objects.push(format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n{xmp}\nendstream", xmp.len()));
catalog = format!("/Metadata {first} 0 R ");
}
let info_at = first + objects.len();
if let Some(i) = info {
objects.push(format!("<< {i} >>"));
}
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
let bytes = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &refs, &catalog, None);
if info.is_none() {
return bytes;
}
// The trailer follows the cross-reference table, so a longer trailer moves no object.
String::from_utf8(bytes).unwrap().replacen("/Root 1 0 R", &format!("/Root 1 0 R /Info {info_at} 0 R"), 1).into_bytes()
}
/// A document called `name` with content `bytes` opened (as `document.open` with no path: the tab
/// shows the document's name), `s` holding it.
fn open_named(s: &mut Session, name: &str, bytes: &[u8]) -> Value {
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap()
}
/// The document's name (its tab) and its File Info title.
fn titles(s: &mut Session) -> [String; 2] {
let info = s.execute("file.info", &json!({})).unwrap();
[s.doc().unwrap().title(), info["title"].as_str().unwrap().to_string()]
}
/// What opening `bytes` as a file called `name` gives: the document's name and its File Info title.
fn opened(name: &str, bytes: &[u8]) -> [String; 2] {
let mut s = Session::new();
let r = open_named(&mut s, name, bytes);
let t = titles(&mut s);
assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some(t[0].as_str()), Some(t[1].as_str())), "the open reply");
assert_eq!(s.doc().unwrap().doc.title, t[0], "the tab is the document's title");
t
}
fn svg_titled(inner: &str) -> String {
format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\">{inner}<rect width=\"5\" height=\"5\"><title>Tooltip</title></rect></svg>"
)
}
#[test]
fn import_puts_the_files_own_title_in_file_info_only() {
// SVG: the root's `<title>`, its white space made single spaces (not a shape's tooltip), is the
// File Info title; the document keeps the file's name, with its extension.
assert_eq!(opened("box.svg", svg_titled("<title>\n Access\n paths </title>").as_bytes()), ["box.svg", "Access paths"]);
assert_eq!(
opened("/work/box.svg", svg_titled("<title>Zugangswege Rechenzentrum – Prüfdiagramm</title>").as_bytes()),
["box.svg", "Zugangswege Rechenzentrum – Prüfdiagramm"]
);
// PDF: the XMP `dc:title` (its `x-default` item) beats the Info `Title`; the Info `Title` stands alone.
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), Some("XMP title"))), ["plan.pdf", "XMP title"]);
assert_eq!(opened("plan.pdf", &pdf_titled(None, Some("XMP title"))), ["plan.pdf", "XMP title"]);
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.pdf", "Info title"]);
assert_eq!(opened("plan.ai", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.ai", "Info title"]);
// Compressed SVG too.
let svgz = |inner: &str| vectorcraft_svg::compress(&svg_titled(inner));
assert_eq!(opened("box.svgz", &svgz("<title>Access paths</title>")), ["box.svgz", "Access paths"]);
// A file that gives none (or a blank one) gives File Info the document's name.
assert_eq!(opened("box.svg", svg_titled("").as_bytes()), ["box.svg", "box.svg"]);
assert_eq!(opened("box.svg", svg_titled("<title> </title>").as_bytes()), ["box.svg", "box.svg"]);
assert_eq!(opened("plan.pdf", &pdf_titled(None, None)), ["plan.pdf", "plan.pdf"]);
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Author (Ada)"), None)), ["plan.pdf", "plan.pdf"]);
// The Untitled-N name New gives is no title (a document that never had one writes it).
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Untitled-2)"), None)), ["plan.pdf", "plan.pdf"]);
// A template opens as a new untitled document, whatever title its file gave.
let [name, info] = opened("plan.ait", &pdf_titled(Some("/Title (Info title)"), None));
assert!(name.starts_with("Untitled-") && info == name, "{name} / {info}");
}
#[test]
fn imported_svg_titles_are_filtered_and_bounded() {
for (raw, expected) in [
("Untitled-2".to_string(), None),
("\u{7f}".to_string(), None),
("Re\u{7f}lease Plan".to_string(), Some("Release Plan".to_string())),
("λ".repeat(65_537), Some("λ".repeat(65_536))),
] {
let svg = svg_titled(&format!("<title>{raw}</title>"));
for format in ["svg", "svgz"] {
let name = format!("box.{format}");
let bytes = if format == "svgz" { vectorcraft_svg::compress(&svg) } else { svg.as_bytes().to_vec() };
assert_eq!(opened(&name, &bytes), [name.clone(), expected.clone().unwrap_or(name)], "{format}");
}
}
}
#[test]
fn a_file_with_a_title_opened_from_a_path_is_named_after_the_file() {
let dir = std::env::temp_dir().join(format!("vc-infotitle-open-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("box.svg");
std::fs::write(&path, svg_titled("<title>Access paths</title>")).unwrap();
let mut s = Session::new();
let r = s.execute("document.open", &json!({"path": path.to_str().unwrap()})).unwrap();
assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths")));
let r = s.execute("document.inspect", &json!({"depth": 0})).unwrap();
assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths")));
// The default names of what the document exports are made from the file's name, not its title.
assert_eq!(s.doc().unwrap().doc.title, "box.svg");
assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "png"), "box.png");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn file_info_edits_a_files_own_title_and_the_document_follows() {
let mut s = Session::new();
open_named(&mut s, "box.svg", svg_titled("<title>Access paths</title>").as_bytes());
// The dialog sends back the title it was given: nothing changes (no undo step).
let before = s.doc().unwrap().revision;
let shown = s.execute("file.info", &json!({})).unwrap();
s.execute("file.info", &shown).unwrap();
assert_eq!(s.doc().unwrap().revision, before, "the title it gave is no edit");
assert_eq!(titles(&mut s), ["box.svg", "Access paths"]);
// Another title is the document's own, as ever, and the file's is gone.
let r = s.execute("file.info", &json!({"title": "Plan B"})).unwrap();
assert_eq!(r["title"], "Plan B");
assert_eq!(titles(&mut s), ["Plan B", "Plan B"]);
assert_eq!(s.doc().unwrap().doc.metadata.title, None);
// Undo brings the file's title back, and the name.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(titles(&mut s), ["box.svg", "Access paths"]);
}
#[test]
fn restored_file_info_title_keeps_authored_spaces() {
let mut s = session();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).metadata.title = Some("Release Plan".into());
for format in ["vectorcraft", "svg", "pdf"] {
let bytes = b64(&s.execute("document.export", &json!({"format": format, "preserveEditing": true})).unwrap());
let mut reopened = Session::new();
let reply = open_named(&mut reopened, &format!("again.{format}"), &bytes);
assert_eq!(reply["restored"], format != "vectorcraft", "{format}");
assert_eq!(reopened.doc().unwrap().doc.metadata.title.as_deref(), Some("Release Plan"), "{format}");
assert_eq!(titles(&mut reopened)[1], "Release Plan", "{format}");
}
}
#[test]
fn the_files_own_title_is_kept_by_saves_and_written_by_exports() {
let mut s = Session::new();
open_named(&mut s, "box.svg", svg_titled("<title>Access paths</title>").as_bytes());
// The native file: its own title is the document's name, the File Info title survives.
let native = b64(&s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap());
let mut t = Session::new();
open_named(&mut t, "other.vectorcraft", &native);
assert_eq!(titles(&mut t), ["box.svg", "Access paths"]);
// An SVG with the editing data it carries, reopened under another name.
let svg = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true, "metadata": true})).unwrap()["text"]
.as_str()
.unwrap()
.to_string();
assert!(svg.contains("<title>Access paths</title>") && svg.contains("<dc:title>Access paths</dc:title>"), "{svg}");
let mut u = Session::new();
let r = open_named(&mut u, "again.svg", svg.as_bytes());
assert_eq!(r["restored"], true);
assert_eq!(titles(&mut u), ["again.svg", "Access paths"]);
// PDF: the Info `Title` and the XMP `dc:title`, shown by the viewer.
for pdf in pdf_texts(&mut s) {
assert!(pdf.contains("/Title(Access paths)") && xmp_title(&pdf).contains("Access paths"), "{}", xmp_title(&pdf));
assert!(pdf.contains("/ViewerPreferences<</DisplayDocTitle true>>"), "{pdf}");
}
// PNG text.
let png = b64(&s.execute("document.export", &json!({"format": "png"})).unwrap());
assert!(crate::cmd::fileio::pngtext::text(&png).iter().any(|(k, v)| k == "Title" && v == "Access paths"));
// The default file names are made from the document's name.
assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "pdf"), "box.pdf");
}
#[test]
fn png_exports_carry_text_chunks() {
let mut s = session();
+37
View File
@@ -194,6 +194,43 @@ fn a_search_finds_a_missing_fonts_file_by_its_names() {
assert!(matches!(r["state"].as_str(), Some("stopped" | "done")), "{r}");
}
/// A caller confined by read roots sees, in the replies to a search another caller started, only
/// the files found inside its read roots, and the folder searched and a failed search's path only
/// when they are inside them.
#[test]
fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
let root = folder("read-roots");
let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3");
let (home, wide) = (root.join("home"), root.join("lrf-wide"));
for dir in [&home, &wide] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("Findme.otf"), &font).unwrap();
}
let mut s = session_for(&root);
let roots = |read: &[&Path]| crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap();
let (narrow, broad) = (roots(&[&home]), roots(&[&root]));
let ask = |s: &mut Session, r: &Arc<crate::file_access::AutomationRoots>, p: Value| {
crate::file_access::confine(Some(r), || s.execute("text.findFontFiles", &p).unwrap())
};
// A font no file has keeps the search going through every folder.
let fonts = json!([{"family": "Findme Sans 3"}, {"family": "No Such Sans"}]);
ask(&mut s, &broad, json!({"folder": root, "fonts": fonts}));
finished(&mut s);
let all = ask(&mut s, &broad, json!({}));
assert_eq!((&all["fonts"][0]["files"], &all["folder"]), (&json!([home.join("Findme.otf"), wide.join("Findme.otf")]), &json!(root)), "{all}");
for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] {
assert!(!r.to_string().contains("lrf-wide") && r.get("folder").is_none(), "{r}");
assert_eq!((&r["fonts"][0]["files"], &r["fonts"][0]["family"]), (&json!([home.join("Findme.otf")]), &json!("Findme Sans 3")), "{r}");
assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}");
}
// A search that failed: the reason shows without the path to a caller outside its folder.
ask(&mut s, &broad, json!({"folder": wide.join("gone"), "fonts": fonts}));
assert!(finished(&mut s)["error"].as_str().is_some_and(|e| e.contains("lrf-wide")));
let r = ask(&mut s, &narrow, json!({}));
assert_eq!((r["state"].as_str(), r["error"].as_str(), r.get("folder")), (Some("failed"), Some("the folder can't be read"), None), "{r}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn junk_search_params_never_fail_internally() {
let root = folder("junk");
+111 -1
View File
@@ -271,7 +271,7 @@ fn stop_ends_only_the_search_it_names() {
let (tx, rx) = mpsc::channel();
let search = findfiles::start(root.clone(), s.search_rules.clone(), Limits::default(), 1, 2, Arc::new(Blocked(Mutex::new(rx)))).unwrap();
let links = vec![Sought { name: "a.png".into(), path: "/gone/a.png".into(), ids: vec![], size: None, hash: None }];
s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), links, sizes: Arc::default(), search });
s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), doc: None, links, sizes: Arc::default(), search });
let until = Instant::now() + WAIT;
while s.execute("links.findFiles", &json!({})).unwrap()["searched"]["read"] != 1 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
@@ -284,6 +284,116 @@ fn stop_ends_only_the_search_it_names() {
drop(tx);
}
/// A caller confined by read roots sees, in the replies to a search another caller started and to
/// its own, only the paths inside its read roots: the files found outside them, a link's saved path
/// outside them and the folder searched are left out, and the rows, ids and counts stay. Without
/// roots, the replies are as before.
#[test]
fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
let root = folder("read-roots");
let mut s = session_for(&root);
let photo = png(40, 30, RED);
write(&root.join("lrf-away/photo.png"), &photo);
let id = placed(&mut s, &root.join("lrf-away/photo.png"));
std::fs::remove_file(root.join("lrf-away/photo.png")).unwrap();
// Files of the name with other contents: the search reads every folder.
let other = png(40, 30, BLUE);
let (home, wide) = (root.join("home"), root.join("lrf-wide"));
write(&home.join("photo.png"), &other);
write(&wide.join("photo.png"), &other);
let roots = |read: &[&Path], write: &[&Path]| crate::file_access::AutomationRoots::new(read, write).unwrap().unwrap();
let (narrow, write_only, broad) = (roots(&[&home], &[]), roots(&[], &[&root]), roots(&[&root], &[]));
let ask = |s: &mut Session, r: &Arc<crate::file_access::AutomationRoots>, p: Value| {
crate::file_access::confine(Some(r), || s.execute("links.findFiles", &p).unwrap())
};
let hidden = |r: &Value| {
let text = r.to_string();
assert!(!text.contains("lrf-away") && !text.contains("lrf-wide") && r.get("folder").is_none(), "{r}");
let row = &r["links"][0];
assert_eq!((row["name"].as_str(), &row["ids"], row.get("path")), (Some("photo.png"), &json!([id]), None), "{r}");
};
// Started with the broad roots, over the whole folder.
let r = ask(&mut s, &broad, json!({"folder": root}));
assert_eq!(r["folder"], json!(root), "{r}");
finished(&mut s);
let all = ask(&mut s, &broad, json!({}));
assert_eq!(all["links"][0]["files"].as_array().map(Vec::len), Some(2), "{all}");
for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] {
hidden(&r);
assert_eq!(r["links"][0]["files"], json!([{"path": home.join("photo.png"), "size": other.len(), "match": "name"}]), "{r}");
assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}");
}
let r = ask(&mut s, &write_only, json!({}));
hidden(&r);
assert_eq!(r["links"][0]["files"], json!([]), "{r}");
// Without roots, every path shows.
let r = s.execute("links.findFiles", &json!({})).unwrap();
assert_eq!((&r["folder"], &r["links"][0]["path"]), (&json!(root), &json!(root.join("lrf-away/photo.png"))), "{r}");
assert_eq!(r["links"][0]["files"].as_array().map(Vec::len), Some(2), "{r}");
// The narrow caller's own search shows the folder it gave.
let r = ask(&mut s, &narrow, json!({"folder": home}));
assert_eq!(r["folder"], json!(home), "{r}");
finished(&mut s);
let r = ask(&mut s, &narrow, json!({}));
assert_eq!((&r["folder"], r["links"][0].get("path")), (&json!(home), None), "{r}");
// A search that failed: the reason shows without the path to a caller outside its folder.
ask(&mut s, &broad, json!({"folder": root.join("lrf-wide/gone")}));
let r = finished(&mut s);
assert!(r["error"].as_str().is_some_and(|e| e.contains("lrf-wide")), "{r}");
let r = ask(&mut s, &narrow, json!({}));
assert_eq!((r["state"].as_str(), r["error"].as_str()), (Some("failed"), Some("the folder can't be read")), "{r}");
hidden(&r);
let _ = std::fs::remove_dir_all(&root);
}
/// A link's saved path relative to the document is shown to a confined caller when it leads to a
/// file inside its read roots, and left out when `..` leads out of them.
#[test]
fn a_relative_link_path_is_judged_from_the_documents_folder() {
let root = folder("read-roots-relative");
let mut s = session_for(&root);
let home = root.join("home");
write(&root.join("lrf-away/photo.png"), &png(40, 30, RED));
let id = placed(&mut s, &root.join("lrf-away/photo.png"));
std::fs::create_dir_all(&home).unwrap();
s.execute("document.save", &json!({"path": home.join("poster.vectorcraft")})).unwrap();
let narrow = crate::file_access::AutomationRoots::new(&[&home], &[]).unwrap().unwrap();
for (saved, shown) in [("sub/photo.png", true), ("../lrf-away/photo.png", false)] {
s.edit("relative path", |d, _| {
if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind {
im.link.as_mut().unwrap().path = saved.into();
}
Ok(())
})
.unwrap();
let r = crate::file_access::confine(Some(&narrow), || s.execute("links.findFiles", &json!({"folder": home, "ids": [id]})).unwrap());
assert_eq!(r["links"][0].get("path"), shown.then(|| json!(saved)).as_ref(), "{saved}: {r}");
finished(&mut s);
}
let _ = std::fs::remove_dir_all(&root);
}
/// `image.info` leaves a linked file outside the confined caller's read roots unnamed (`link`
/// null), as `links.info` leaves it out, and keeps the other fields.
#[test]
fn image_info_leaves_out_a_link_outside_the_read_roots() {
let root = folder("read-roots-info");
let mut s = session_for(&root);
let pic = root.join("lrf-away/photo.png");
write(&pic, &png(40, 30, RED));
let id = placed(&mut s, &pic);
std::fs::create_dir_all(root.join("home")).unwrap();
let narrow = crate::file_access::AutomationRoots::new(&[&root.join("home")], &[]).unwrap().unwrap();
let ask = |s: &mut Session, cmd: &str| crate::file_access::confine(Some(&narrow), || s.execute(cmd, &json!({"id": id})).unwrap());
let r = ask(&mut s, "image.info");
assert_eq!((&r["link"], &r["linked"], &r["pixelWidth"], &r["id"]), (&Value::Null, &json!(true), &json!(40), &json!(id)), "{r}");
assert!(!r.to_string().contains("lrf-away"), "{r}");
let info = ask(&mut s, "links.info");
assert!(info.get("link").is_none() && !info.to_string().contains("lrf-away"), "{info}");
assert_eq!(s.execute("image.info", &json!({"id": id})).unwrap()["link"], json!(pic));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn relinking_with_copy_puts_the_file_in_the_documents_folder() {
let root = folder("copy");
+2 -2
View File
@@ -570,8 +570,8 @@ fn envelope_warp_make_and_content_stays_inside_bounds() {
let pts = all_anchors(&out);
assert!(pts.len() > 4, "curves are subdivided");
assert!(pts.iter().all(|p| b.contains(*p)), "{b:?}");
// It really is bent: the sides moved down.
assert!(pts.iter().any(|p| p.y > 201.0));
// It really is bent: the top corners swung out past the sides.
assert!(pts.iter().any(|p| p.x < 99.0) && pts.iter().any(|p| p.x > 301.0));
}
#[test]
+178
View File
@@ -184,6 +184,184 @@ fn a_flip_round_a_closed_path_keeps_the_type_in_place() {
assert!(origins(&s, id)[0].distance(first) < 8.0);
}
/// A circle of radius 100 round (200, 200), starting at 9 o'clock and running clockwise, with
/// type on it from its start.
fn on_circle(s: &mut Session, text: &str) -> NodeId {
path_type(s, "M100 200 A100 100 0 1 1 300 200 A100 100 0 1 1 100 200 Z", [90.0, 200.0], text)
}
#[test]
fn center_on_top_and_bottom_of_a_circle() {
let mut s = session();
let id = on_circle(&mut s, "OOOO");
assert!(near(brackets(&s, id).0, 0.0), "{:?}", brackets(&s, id));
let steps = undo_len(&s);
let r = s.execute("type.pathCenter.top", &json!({})).unwrap();
// Once round, its middle at 12 o'clock, a quarter of the way round: the type sits on the top, centered.
let (start, end) = brackets(&s, id);
assert!(near(start, 0.75) && end.is_none(), "{start} {end:?}");
assert_eq!((r["ids"].clone(), r["end"].clone()), (json!([id.0]), Value::Null));
assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center);
let top = ink(&s, id);
assert!((top.center().x - 200.0).abs() < 0.5 && top.y1 < 101.0, "{top:?}");
assert_eq!((undo_len(&s), last_step(&s)), (steps + 1, "Center on Top".to_string()));
// Again: nothing moves, and no undo step is recorded.
s.execute("type.pathCenter.top", &json!({})).unwrap();
assert_eq!(undo_len(&s), steps + 1);
// The bottom: 6 o'clock, outside the circle (the type is not flipped).
s.execute("type.pathCenter.bottom", &json!({})).unwrap();
let (start, end) = brackets(&s, id);
assert!(near(start, 0.25) && end.is_none(), "{start} {end:?}");
let bottom = ink(&s, id);
assert!((bottom.center().x - 200.0).abs() < 0.5 && bottom.y0 > 299.0, "{bottom:?}");
assert_eq!((undo_len(&s), last_step(&s)), (steps + 2, "Center on Bottom".to_string()));
// Justify Center stays as it is.
s.execute("text.setStyle", &json!({"justify": "justifyCenter"})).unwrap();
s.execute("type.pathCenter.top", &json!({})).unwrap();
assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::JustifyCenter);
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(brackets(&s, id).0, 0.25));
// Brackets already in place with another alignment: only the alignment changes, in one step.
s.execute("text.setStyle", &json!({"justify": "left"})).unwrap();
let (steps, before) = (undo_len(&s), brackets(&s, id));
s.execute("type.pathCenter.bottom", &json!({})).unwrap();
assert_eq!((undo_len(&s), brackets(&s, id)), (steps + 1, before));
assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center);
}
#[test]
fn center_on_top_twice_records_one_step_for_any_span() {
let mut s = session();
let id = on_circle(&mut s, "OOOO");
for (start, end) in [(0.0, 0.2), (0.13, 0.41), (0.37, 0.52), (0.61, 0.97), (0.89, 0.07), (0.3, 0.3001)] {
s.execute("type.pathOptions", &json!({"start": start, "end": end})).unwrap();
for c in ["type.pathCenter.top", "type.pathCenter.bottom"] {
s.execute(c, &json!({})).unwrap();
let (steps, placed) = (undo_len(&s), brackets(&s, id));
// Again: the brackets stay exactly where they are, and no undo step is recorded.
s.execute(c, &json!({})).unwrap();
assert_eq!((undo_len(&s), brackets(&s, id)), (steps, placed), "{c} {start} {end}");
}
}
}
#[test]
fn center_on_top_keeps_the_span_and_measures_the_path_as_drawn() {
let mut s = session();
let id = on_circle(&mut s, "OOOO");
// A span of a fifth of the path keeps its length.
s.execute("type.pathOptions", &json!({"end": 0.2})).unwrap();
s.execute("type.pathCenter.top", &json!({})).unwrap();
let (start, end) = brackets(&s, id);
assert!(near(start, 0.15) && end.is_some_and(|e| near(e, 0.35)), "{start} {end:?}");
// Turned a quarter turn counter-clockwise, its 3 o'clock point, halfway round, is at the top.
s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap();
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
s.execute("type.pathCenter.top", &json!({})).unwrap();
let (start, _) = brackets(&s, id);
assert!(near(start.rem_euclid(1.0), 0.0) || near(start, 1.0), "{start}");
let bounds = text(&s, id).bounds().unwrap();
let top = ink(&s, id);
assert!((top.center().x - bounds.center().x).abs() < 0.5 && top.y1 < bounds.y0 + 1.0, "{top:?} {bounds:?}");
// A rectangle: the middle of its top edge.
let id = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO");
s.execute("type.pathCenter.top", &json!({})).unwrap();
let (start, end) = brackets(&s, id);
assert!(near(start, 0.625) && end.is_none(), "{start} {end:?}");
assert!((ink(&s, id).center().x - 200.0).abs() < 0.5);
}
#[test]
fn center_on_top_moves_every_selected_type_on_a_path_in_one_step() {
let mut s = session();
let a = on_circle(&mut s, "OOOO");
let b = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO");
let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0, p]})).unwrap();
let steps = undo_len(&s);
let r = s.execute("type.pathCenter.top", &json!({})).unwrap();
assert_eq!(r["ids"], json!([a.0, b.0]));
assert!(near(brackets(&s, a).0, 0.75) && near(brackets(&s, b).0, 0.625));
assert_eq!(undo_len(&s), steps + 1);
// Dynamic Text stays on, and the layout fits the text to the span where it now runs: a fifth of
// the circle, at its bottom.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("type.pathOptions", &json!({"start": 0, "end": 0.2})).unwrap();
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
s.execute("type.pathCenter.bottom", &json!({})).unwrap();
assert!(text(&s, a).dynamic_text && near(brackets(&s, a).0, 0.65), "{:?}", brackets(&s, a));
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, a));
assert!(lay.fit_scale > 1.5 && !lay.overflow, "{}", lay.fit_scale);
let bottom = ink(&s, a);
assert!((bottom.center().x - 200.0).abs() < 1.0 && bottom.y1 > 300.0, "{bottom:?}");
// Vertical type on a path moves the same way.
s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap();
s.execute("type.orientation.vertical", &json!({})).unwrap();
s.execute("type.pathCenter.top", &json!({})).unwrap();
assert!(near(brackets(&s, a).0, 0.75));
}
#[test]
fn center_on_top_refuses_open_compound_and_threaded_type() {
let mut s = session();
let circle = on_circle(&mut s, "OOOO");
let line = on_line(&mut s);
s.execute("select.set", &json!({"ids": [circle.0, line.0]})).unwrap();
let steps = undo_len(&s);
let before = brackets(&s, circle);
let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string();
assert!(e.contains("type on an open or compound path cannot be centered on its top or bottom") && e.ends_with(&line.0.to_string()), "{e}");
// Nothing changes, the type on the circle included, and the same holds for an explicit list.
assert_eq!((undo_len(&s), brackets(&s, circle)), (steps, before));
let e = s.execute("type.pathCenter.bottom", &json!({"ids": [circle.0, line.0]})).unwrap_err().to_string();
assert!(e.contains("open or compound path") && e.ends_with(&line.0.to_string()), "{e}");
s.execute("select.set", &json!({"ids": [circle.0]})).unwrap();
for bad in [json!({"ids": "all"}), json!({"ids": [999_999]})] {
assert!(s.execute("type.pathCenter.top", &bad).is_err(), "{bad}");
}
assert_eq!(undo_len(&s), steps);
// Two circles side by side in one path: a compound path.
let pair = path_type(
&mut s,
"M100 450 A40 40 0 1 1 180 450 A40 40 0 1 1 100 450 Z M300 450 A40 40 0 1 1 380 450 A40 40 0 1 1 300 450 Z",
[90.0, 450.0],
"OOOO",
);
let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string();
assert!(e.contains("open or compound path") && e.ends_with(&pair.0.to_string()), "{e}");
// A closed path that is level all round has no height.
let flat = path_type(&mut s, "M100 400 L300 400 Z", [90.0, 400.0], "OOOO");
let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string();
assert!(e.contains("type on a path with no length or no height cannot be centered") && e.ends_with(&flat.0.to_string()), "{e}");
// A frame of a thread is refused, alone or with other type on a closed path.
let threaded = on_circle(&mut s, "Threaded story");
let frame = s.execute("shape.rectangle", &json!({"x": 400, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap();
s.execute("text.thread.create", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [threaded.0]})).unwrap();
let before = brackets(&s, threaded);
for ids in [json!([threaded.0]), json!([circle.0, threaded.0])] {
let steps = undo_len(&s);
let e = s.execute("type.pathCenter.top", &json!({ "ids": ids })).unwrap_err().to_string();
assert!(e.contains("type on a path in a thread cannot be centered on its top or bottom") && e.ends_with(&threaded.0.to_string()), "{e}");
assert_eq!((undo_len(&s), brackets(&s, threaded)), (steps, before));
}
// Without type on one closed path selected, the commands are not available.
let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
for (ids, why) in [
(json!([p]), "select type on a closed path"),
(json!([line.0]), "open or compound path"),
(json!([circle.0, line.0]), "open or compound path"),
(json!([threaded.0]), "in a thread"),
] {
s.execute("select.set", &json!({ "ids": ids })).unwrap();
for c in ["type.pathCenter.top", "type.pathCenter.bottom"] {
let e = s.execute(c, &json!({})).unwrap_err().to_string();
assert!(e.contains(why), "{c} {ids}: {e}");
}
}
}
#[test]
fn align_to_path_and_spacing() {
let mut s = session();
+157
View File
@@ -234,3 +234,160 @@ fn a_marquee_that_touches_only_a_drop_shadow_does_not_select_its_object() {
// From above B, over B and the shadow: B only.
assert_eq!(press(&mut s, "selection", (105.0, 5.0), (115.0, 30.0), Mods::default()), [b]);
}
/// The selection after a drag with `tool` from `from` to `to`.
fn marquee(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)) -> vectorcraft_doc::Selection {
press(s, tool, from, to, Mods::default());
s.doc().unwrap().selection.clone()
}
/// The point of anchor `(si, ai)` of path `id`.
fn anchor_point(s: &Session, id: NodeId, (si, ai): vectorcraft_doc::AnchorRef) -> Point {
let path = s.doc().unwrap().doc.node(id).and_then(|n| n.path_data()).unwrap();
path.anchors().find(|(s, i, _)| (*s, *i) == (si, ai)).map(|(.., a)| a.p).unwrap()
}
/// The anchors a marquee or a click picked on `id`, as points.
fn picked_points(s: &Session, id: NodeId) -> Vec<Point> {
let refs: Vec<_> = s.doc().unwrap().selection.partial(id).into_iter().flatten().copied().collect();
refs.into_iter().map(|r| anchor_point(s, id, r)).collect()
}
/// The anchors the tool marks as hovered.
fn anchor_marks(s: &mut Session) -> Vec<Point> {
s.overlays(ViewInfo::default())
.into_iter()
.filter_map(|o| if let vectorcraft_tools::Overlay::Anchor { p, .. } = o { Some(p) } else { None })
.collect()
}
fn hover(s: &mut Session, x: f64, y: f64) -> Cursor {
let v = ViewInfo::default();
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), v).unwrap();
s.cursor(Point::new(x, y), Mods::default(), v)
}
#[test]
fn a_direct_selection_marquee_leaves_out_a_drop_shadow() {
let mut s = session();
let (a, b) = shadow_over_b(&mut s);
let (a_before, b_before) = (bounds(&s, a), bounds(&s, b));
assert_ne!(pixel(&s, 90, 50), WHITE);
run(&mut s, "select.none", json!({}));
// Over the shadow alone: no object, no anchor, no segment.
let sel = marquee(&mut s, "directSelection", (85.0, 40.0), (95.0, 60.0));
assert!(sel.objects.is_empty() && sel.anchors.is_empty() && sel.segments.is_empty(), "{sel:?}");
// Over the shadow and B's upper left corner: that anchor of B, and nothing of A.
let sel = marquee(&mut s, "directSelection", (90.0, 5.0), (105.0, 30.0));
assert_eq!(sel.objects, [b]);
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
// Across B's top edge under the shadow, with neither of its anchors inside: that segment.
run(&mut s, "select.none", json!({}));
assert_ne!(pixel(&s, 112, 25), BLUE);
let sel = marquee(&mut s, "directSelection", (110.0, 5.0), (115.0, 30.0));
assert_eq!(sel.objects, [b]);
assert!(sel.segments.contains_key(&b) && !sel.segments.contains_key(&a), "{sel:?}");
assert_eq!((bounds(&s, a), bounds(&s, b)), (a_before, b_before));
}
#[test]
fn direct_selection_hover_leaves_out_a_drop_shadow_and_marks_the_anchor_under_it() {
let mut s = session();
let (_, b) = shadow_over_b(&mut s);
// B's upper left corner lies under the shadow.
assert_ne!(pixel(&s, 101, 21), BLUE);
run(&mut s, "select.none", json!({}));
s.select_tool("directSelection", ViewInfo::default()).unwrap();
for (x, y) in [(90.0, 50.0), (110.0, 50.0)] {
assert_eq!(hover(&mut s, x, y), Cursor::ArrowHollow, "({x}, {y})");
assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})");
}
assert_eq!(hover(&mut s, 101.0, 21.0), Cursor::DirectAnchor);
assert_eq!(anchor_marks(&mut s), [Point::new(100.0, 20.0)]);
// A press there picks that anchor of B.
assert_eq!(press(&mut s, "directSelection", (101.0, 21.0), (101.0, 21.0), Mods::default()), [b]);
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
}
#[test]
fn a_group_selection_click_on_a_drop_shadow_selects_the_object_under_it() {
let mut s = session();
let (a, b) = shadow_over_b(&mut s);
run(&mut s, "select.none", json!({}));
assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]);
assert!(press(&mut s, "groupSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty());
assert_eq!(press(&mut s, "groupSelection", (50.0, 50.0), (50.0, 50.0), Mods::default()), [a]);
}
#[test]
fn group_selection_clicks_on_a_drop_shadow_climb_the_groups_of_the_object_under_it() {
let mut s = session();
// B and C in one group, A and D in another above it, and A's shadow over B.
let b = rect(&mut s, 100.0, 20.0, 60.0, 60.0, "#0000ff");
let c = rect(&mut s, 170.0, 20.0, 20.0, 20.0, "#0000ff");
run(&mut s, "select.set", json!({"ids": [b.0, c.0]}));
let gb = id_of(&run(&mut s, "object.group", json!({})));
let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000");
let d = rect(&mut s, 20.0, 120.0, 20.0, 20.0, "#ff0000");
run(&mut s, "select.set", json!({"ids": [a.0, d.0]}));
let ga = id_of(&run(&mut s, "object.group", json!({})));
shadow(&mut s, a, 40.0);
assert_ne!(pixel(&s, 110, 50), BLUE);
assert_ne!(pixel(&s, 90, 50), WHITE);
run(&mut s, "select.none", json!({}));
let click = |s: &mut Session, x, y| {
let mut sel = press(s, "groupSelection", (x, y), (x, y), Mods::default());
sel.sort_by_key(|n| n.0);
sel
};
assert_eq!(click(&mut s, 110.0, 50.0), [b]);
let mut both = vec![b, gb];
both.sort_by_key(|n| n.0);
assert_eq!(click(&mut s, 110.0, 50.0), both);
// With A selected, a click on its shadow over the canvas does not add A's group.
run(&mut s, "select.set", json!({"ids": [a.0]}));
assert!(click(&mut s, 90.0, 50.0).is_empty());
// On A itself the second click adds it.
assert_eq!(click(&mut s, 50.0, 50.0), [a]);
let mut both = vec![a, ga];
both.sort_by_key(|n| n.0);
assert_eq!(click(&mut s, 50.0, 50.0), both);
}
#[test]
fn a_group_selection_marquee_leaves_out_a_drop_shadow() {
let mut s = session();
let (a, b) = shadow_over_b(&mut s);
run(&mut s, "select.none", json!({}));
let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0));
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}");
// Over the shadow and B's upper left corner: that anchor of B.
let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0));
assert_eq!(sel.objects, [b]);
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
// With E, a marquee around B that crosses A's shadow selects B whole, and not A.
run(&mut s, "select.none", json!({}));
let v = ViewInfo::default();
s.select_tool("groupSelection", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 95.0, 10.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 50.0), v).unwrap();
s.tool_key(vectorcraft_tools::ToolKey::Letter('e'), Mods::default(), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 165.0, 90.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 165.0, 90.0), v).unwrap();
let sel = s.doc().unwrap().selection.clone();
assert_eq!(sel.objects, [b]);
assert!(sel.partial(b).is_none() && sel.partial(a).is_none(), "{sel:?}");
}
#[test]
fn group_selection_hover_over_a_drop_shadow_marks_nothing() {
let mut s = session();
let (_, b) = shadow_over_b(&mut s);
run(&mut s, "select.none", json!({}));
s.select_tool("groupSelection", ViewInfo::default()).unwrap();
for (x, y) in [(90.0, 50.0), (110.0, 50.0), (101.0, 21.0)] {
assert_eq!(hover(&mut s, x, y), Cursor::GroupSelection, "({x}, {y})");
assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})");
}
assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]);
}
+293
View File
@@ -0,0 +1,293 @@
//! Effect › Warp on placed images: the pixels bend with the frame, in the canvas and in exports.
use serde_json::{Value, json};
use vectorcraft_doc::live::{WarpNet, WarpStyle, uses_net, warp_version};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::{Affine, Point, Rect};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
/// The box of the image [`quarters`] places.
const FRAME: Rect = Rect::new(100.0, 100.0, 180.0, 180.0);
/// The color of the quarter of the image [`quarters`] places that holds (u, v) of its box: red top
/// left, green top right, blue bottom left, yellow bottom right.
fn quarter(u: f64, v: f64) -> [u8; 3] {
match (u < 0.5, v < 0.5) {
(true, true) => [255, 0, 0],
(false, true) => [0, 255, 0],
(true, false) => [0, 0, 255],
(false, false) => [255, 255, 0],
}
}
/// A selected embedded 40×40 px image filling [`FRAME`], each quarter one color ([`quarter`]).
fn quarters(s: &mut Session) -> NodeId {
let img = image::RgbaImage::from_fn(40, 40, |x, y| {
let [r, g, b] = quarter(x as f64 / 40.0, y as f64 / 40.0);
image::Rgba([r, g, b, 255])
});
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.edit("Place", |d, sel| {
d.images.insert("quarters".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0);
let im = vectorcraft_doc::ImageObject {
key: "quarters".into(),
width: 40,
height: 40,
xf,
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap()
}
/// Where an Arc warp bending `bend` % takes the point at (u, v) of [`FRAME`].
fn arced(bend: f64, u: f64, v: f64) -> Point {
let net = WarpNet::new(WarpStyle::Arc, bend / 100.0, 0.0, 0.0, FRAME.width(), FRAME.height(), false);
FRAME.origin() + net.at(u, v).to_vec2()
}
/// Points of the image's box: near each quarter's middle and on both sides of the line between
/// the top and bottom quarters, where a warp that moves the pixels up or down changes the color.
const SAMPLES: [(f64, f64); 10] =
[(0.2, 0.2), (0.8, 0.2), (0.2, 0.8), (0.8, 0.8), (0.4, 0.4), (0.6, 0.4), (0.4, 0.6), (0.6, 0.6), (0.3, 0.62), (0.7, 0.62)];
/// The document drawn over (0, 0)–(400, 400) at one pixel a point, on white.
fn drawn(s: &Session) -> vectorcraft_render::Rendered {
vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 400.0, 400.0), 1.0, true)
}
/// The sample points whose color in `img` at `at(u, v)` is not the image's color at (u, v).
fn wrong(img: &vectorcraft_render::Rendered, at: &dyn Fn(f64, f64) -> Point) -> Vec<(f64, f64, [u8; 4])> {
SAMPLES
.iter()
.filter_map(|&(u, v)| {
let p = at(u, v);
let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32);
let want = quarter(u, v);
let near = (0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40);
(!near).then_some((u, v, px))
})
.collect()
}
/// `quarters` with Effect › Warp › Arc at 50 %: the warp the effect holds, checked to be the
/// Bézier patch [`arced`] follows.
fn arc_image(s: &mut Session) -> NodeId {
let id = quarters(s);
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let e = &n.appearance.effects[0];
assert!(warp_version(&e.params["version"]).is_some_and(uses_net), "{}", e.params);
id
}
fn decoded(v: &Value) -> Vec<u8> {
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()
}
#[test]
fn an_images_pixels_bend_with_effect_warp() {
let mut s = session();
let id = arc_image(&mut s);
// The arc lifts the middle of the image: the line between the quarters rises there.
assert!(arced(50.0, 0.5, 0.6).y < FRAME.y0 + 0.5 * FRAME.height(), "{:?}", arced(50.0, 0.5, 0.6));
let bent = drawn(&s);
assert_eq!(wrong(&bent, &|u, v| arced(50.0, u, v)), vec![], "each pixel is drawn where the warp takes it");
// Drawn as pieces of the one image, each placed by the warp.
let d = &s.doc().unwrap().doc;
let art = vectorcraft_render::effects::reshape(Some(d), d.node(id).unwrap(), None).unwrap();
let mut pieces = 0;
art.walk(&mut |c| pieces += matches!(c.kind, NodeKind::Image(_)) as usize);
assert!(pieces >= 100, "{pieces} pieces");
// Removing the warp draws the image as it was, in one undo step.
let steps = s.doc().unwrap().history.undo.len();
s.execute("effect.remove", &json!({"index": 0})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
let plain = |u: f64, v: f64| Point::new(FRAME.x0 + u * FRAME.width(), FRAME.y0 + v * FRAME.height());
assert_eq!(wrong(&drawn(&s), &plain), vec![]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![], "undo brings the bend back");
}
/// `out`, an export of [`arc_image`]'s document named `name`, opened again: it draws the image
/// bent.
fn opens_bent(name: &str, out: &Value) {
let mut back = session();
back.execute("document.open", &json!({"name": name, "dataBase64": out["dataBase64"]})).unwrap();
assert_eq!(wrong(&drawn(&back), &|u, v| arced(50.0, u, v)), vec![], "{name}");
}
#[test]
fn a_warped_image_keeps_its_bend_in_svg() {
let mut s = session();
arc_image(&mut s);
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let text = String::from_utf8(decoded(&svg)).unwrap();
assert_eq!(text.matches("<image").count(), 1, "the pieces share the image's pixels");
opens_bent("warped.svg", &svg);
}
#[test]
fn a_warped_image_keeps_its_bend_in_pdf() {
let mut s = session();
arc_image(&mut s);
opens_bent("warped.pdf", &s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false})).unwrap());
}
#[test]
fn a_warped_image_keeps_its_bend_in_ai() {
let mut s = session();
arc_image(&mut s);
opens_bent("warped.ai", &s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap());
}
#[test]
fn a_warped_image_keeps_its_bend_in_eps() {
let mut s = session();
arc_image(&mut s);
opens_bent("warped.eps", &s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap());
}
#[test]
fn a_warped_image_keeps_its_bend_in_png() {
let mut s = session();
arc_image(&mut s);
let out = s.execute("document.export", &json!({"format": "png"})).unwrap();
let png = image::load_from_memory(&decoded(&out)).unwrap().to_rgba8();
// The artboard starts at (0, 0) and the export draws one pixel a point.
assert_eq!((png.width(), png.height()), (800, 600));
for &(u, v) in &SAMPLES {
let p = arced(50.0, u, v);
let px = png.get_pixel(p.x.floor() as u32, p.y.floor() as u32).0;
let want = quarter(u, v);
assert!((0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40), "({u}, {v}) at {p:?}: {px:?}");
}
}
/// A group the user made of two clip groups of the same image, each clipped by a rectangle, writes
/// the image once for each: only the pieces of a warp share one.
#[test]
fn svg_writes_an_image_clipped_twice_in_a_users_group_twice() {
let mut s = session();
let im = quarters(&mut s);
s.edit("Clip twice", |d, _| {
let image = d.node(im).cloned().unwrap();
let mut clipped = vec![];
for x in [FRAME.x0, FRAME.x0 + 40.0] {
let mut clip =
Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(x, FRAME.y0, x + 30.0, FRAME.y0 + 30.0)), Default::default());
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let image = Node { id: d.alloc_id(), ..image.clone() };
let children = vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)];
clipped.push(std::sync::Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children, clip: true })));
}
let group = Node::group(d.alloc_id(), clipped);
d.remove(im)?;
d.insert(d.default_layer(), 0, group)?;
Ok(())
})
.unwrap();
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let text = String::from_utf8(decoded(&svg)).unwrap();
assert_eq!(text.matches("<image").count(), 2, "{text}");
}
/// Expand Appearance of a warped image gives objects that draw as the canvas did, with ids of
/// their own, in one undo step.
#[test]
fn expand_appearance_of_a_warped_image_draws_as_the_canvas_did() {
let mut s = session();
let id = arc_image(&mut s);
let steps = s.doc().unwrap().history.undo.len();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
let d = &s.doc().unwrap().doc;
let mut ids = std::collections::HashSet::new();
let mut images = 0;
for layer in &d.layers {
layer.walk(&mut |c| {
assert!(ids.insert(c.id), "{:?} twice", c.id);
images += matches!(c.kind, NodeKind::Image(_)) as usize;
assert!(c.appearance.effects.iter().all(|e| !e.id.starts_with("warp.")));
});
}
assert!(images >= 100, "{images} pieces");
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
s.execute("edit.undo", &json!({})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
assert!(matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.len() == 1);
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
}
/// A selected embedded grayscale 40×40 px image filling [`FRAME`], black above white, colorized
/// red by its fill color: red above, nothing below.
fn red_on_clear(s: &mut Session) -> NodeId {
let img = image::GrayImage::from_fn(40, 40, |_, y| image::Luma([if y < 20 { 0 } else { 255 }]));
let mut png = vec![];
image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let id = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0);
let im = vectorcraft_doc::ImageObject {
key: "gray".into(),
width: 40,
height: 40,
xf,
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
id
}
#[test]
fn a_colorized_image_keeps_its_color_when_warped() {
let mut s = session();
red_on_clear(&mut s);
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
let img = drawn(&s);
let (red, white) = ([255u8, 0, 0], [255u8, 255, 255]);
for (u, v, want) in [(0.5, 0.35, red), (0.2, 0.2, red), (0.5, 0.65, white), (0.8, 0.8, white)] {
let p = arced(50.0, u, v);
let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32);
assert!((0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40), "({u}, {v}) at {p:?}: {px:?}");
}
}
#[test]
fn a_warp_on_a_group_bends_the_image_in_it() {
let mut s = session();
let im = quarters(&mut s);
// A group of the image and a line below it as wide as the image: the group's box is the image's.
let line = s.execute("shape.line", &json!({"x1": FRAME.x0, "y1": FRAME.y1, "x2": FRAME.x1, "y2": FRAME.y1})).unwrap();
let line = NodeId(line["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [im.0, line.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
}